From e013792cb0a6f218b2acd8e8cc2a771f48cd5ac6 Mon Sep 17 00:00:00 2001 From: Martin Vejmelka Date: Fri, 10 Sep 2010 16:28:41 +0200 Subject: [PATCH] Converted all CRLF to LF. --- .../promod/memory/MemoryIndicatorExtension.java | 172 +- .../memory/MemoryIndicatorExtensionModel.java | 228 +-- IndependentModeler/epcImageExportModule.properties | 8 +- IndependentModeler/epcNotation.properties | 28 +- IndependentModeler/memoryIndicator.properties | 22 +- IndependentModeler/phDiagramReference.properties | 2 +- IndependentModeler/resources/config/plugins.xsd | 104 +- IndependentModeler/resources/config/project.xsd | 174 +- .../cz/cvut/promod/actions/LoadDialogAction.java | 258 +-- .../src/cz/cvut/promod/gui/Modeler.java | 2136 ++++++++++---------- .../src/cz/cvut/promod/gui/ModelerModel.java | 176 +- .../src/cz/cvut/promod/gui/ModelerView.java | 668 +++--- .../addNewDiagramDialog/AddNewDiagramDialog.java | 440 ++-- .../AddNewDiagramDialogModel.java | 184 +- .../AddNewDiagramDialogView.java | 334 +-- .../ConfigurationDiffDialog.java | 432 ++-- .../ConfigurationDiffDialogView.java | 134 +- .../gui/dialogs/loadErrors/LoadErrorsDialog.java | 192 +- .../dialogs/loadErrors/LoadErrorsDialogModel.java | 78 +- .../dialogs/loadErrors/LoadErrorsDialogView.java | 138 +- .../gui/dialogs/newProject/NewProjectDialog.java | 406 ++-- .../dialogs/newProject/NewProjectDialogModel.java | 156 +- .../dialogs/newProject/NewProjectDialogView.java | 174 +- .../PluginsOverviewDialogDialog.java | 182 +- .../pluginsOverview/PluginsOverviewDialogView.java | 94 +- .../extensions/ExtensionOverviewTab.java | 120 +- .../extensions/ExtensionOverviewTabModel.java | 146 +- .../extensions/ExtensionOverviewTabView.java | 168 +- .../pluginsOverview/notations/ModuleListModel.java | 122 +- .../notations/NotationOverviewTab.java | 246 +-- .../notations/NotationOverviewTabModel.java | 188 +- .../notations/NotationOverviewTabView.java | 300 +-- .../SimpleTextFieldDialog.java | 200 +- .../SimpleTextFieldDialogExecutor.java | 24 +- .../SimpleTextFieldDialogModel.java | 52 +- .../SimpleTextFieldDialogView.java | 140 +- .../executors/AddProjectSubFolderExecutor.java | 114 +- .../promod/gui/listeners/ButtonPopupAdapter.java | 78 +- .../promod/gui/listeners/DockFrameListener.java | 198 +- .../listeners/ProjectNavigationActionTarget.java | 146 +- .../promod/gui/listeners/SideButtonListener.java | 130 +- .../gui/projectNavigation/ProjectNavigation.java | 1360 ++++++------- .../projectNavigation/ProjectNavigationView.java | 234 +-- .../actions/executors/RenameExecutor.java | 286 +-- .../events/ProjectTreeExpandEvent.java | 106 +- .../projectNavigation/listeners/MousePopup.java | 110 +- .../renderer/ProjectNavigationCellRenderer.java | 334 +-- .../cvut/promod/gui/settings/BasicSettingPage.java | 94 +- .../cvut/promod/gui/settings/SettingsDialog.java | 344 ++-- .../gui/support/utils/DockableFrameWrapper.java | 310 +-- .../support/utils/LoadProjectDialogFileFilter.java | 72 +- .../gui/support/utils/NotationGuiHolder.java | 990 ++++----- .../cz/cvut/promod/plugin/extension/Extension.java | 32 +- .../notationSpecificPlugIn/DockableFrameData.java | 180 +- .../NotationSpecificPlugin.java | 50 +- .../notationSpecificPlugIn/module/Module.java | 66 +- .../notation/NotationWorkspaceData.java | 42 +- .../notation/factory/DiagramModelFactory.java | 52 +- .../NotationLocalIOController.java | 128 +- .../notation/model/DiagramModel.java | 88 +- .../notation/model/DiagramModelChangeListener.java | 44 +- .../utils/DefaultUpdatableWorkspaceComponent.java | 218 +- .../utils/NotationWorkspaceDataDefault.java | 74 +- .../workspace/UpdatableWorkspaceComponent.java | 68 +- .../src/cz/cvut/promod/resources/Resources.java | 264 +-- .../cz/cvut/promod/resources/TranslationCheck.java | 454 ++--- .../cz/cvut/promod/services/ModelerSession.java | 912 ++++----- .../actionService/ActionControlService.java | 50 +- .../actionService/ActionControlServiceImpl.java | 388 ++-- .../services/actionService/ActionService.java | 206 +- .../actionService/ModuleSpecificActions.java | 164 +- .../actionService/NotationSpecificActions.java | 282 +-- .../actionService/actionUtils/ProModAction.java | 204 +- .../ComponentFactoryService.java | 426 ++-- .../ComponentFactoryServiceImpl.java | 366 ++-- .../extensionService/ExtensionService.java | 70 +- .../extensionService/ExtensionServiceImpl.java | 90 +- .../services/menuService/MenuControlService.java | 60 +- .../menuService/MenuControlServiceImpl.java | 1492 +++++++------- .../promod/services/menuService/MenuService.java | 510 ++--- .../menuService/utils/CheckableMenuItem.java | 58 +- .../menuService/utils/DefaultMenuItem.java | 58 +- .../menuService/utils/InsertMenuItemResult.java | 104 +- .../menuService/utils/MenuItemPosition.java | 326 +-- .../menuService/utils/ModelerMenuItem.java | 72 +- .../services/notationService/NotationService.java | 198 +- .../notationService/NotationServiceImpl.java | 262 +-- .../pluginLoaderService/PluginLoaderService.java | 198 +- .../PluginLoaderServiceImpl.java | 1950 +++++++++--------- .../errorHandling/PluginLoaderErrorHandler.java | 74 +- .../utils/ModifiableNotationSpecificPlugins.java | 188 +- .../utils/NotationSpecificPlugins.java | 218 +- .../pluginLoaderService/utils/PluginDetails.java | 206 +- .../utils/PluginLoadErrors.java | 662 +++--- .../projectService/ProjectControlService.java | 570 +++--- .../projectService/ProjectControlServiceImpl.java | 1646 +++++++-------- .../services/projectService/ProjectService.java | 374 ++-- .../projectService/dialogs/SyncDialog.java | 294 +-- .../projectService/dialogs/SyncDialogView.java | 176 +- .../projectService/localIO/ProjectFileLoader.java | 674 +++--- .../projectService/localIO/ProjectFileSaver.java | 506 ++--- .../localIO/ProjectFileXmlErrorHandler.java | 70 +- .../services/projectService/localIO/XmlConsts.java | 108 +- .../results/AddProjectItemResult.java | 68 +- .../results/AddProjectItemStatus.java | 88 +- .../results/ConfigurationDifference.java | 186 +- .../projectService/results/LoadProjectResult.java | 96 +- .../projectService/results/SaveProjectResult.java | 72 +- .../syncWorkers/SyncFromFSWorker.java | 1122 +++++----- .../syncWorkers/SyncFromPNWorker.java | 1050 +++++----- .../syncWorkers/SyncWorkersUtils.java | 252 +-- .../treeProjectNode/IdentifiableProjectItem.java | 42 +- .../treeProjectNode/ProjectContainer.java | 26 +- .../treeProjectNode/ProjectDiagram.java | 336 +-- .../treeProjectNode/ProjectDiagramChange.java | 234 +-- .../treeProjectNode/ProjectItem.java | 60 +- .../treeProjectNode/ProjectRoot.java | 160 +- .../treeProjectNode/ProjectSubFolder.java | 88 +- .../listener/ProjectDiagramListener.java | 52 +- .../projectService/utils/ProjectServiceUtils.java | 1184 +++++------ .../statusBarService/StatusBarControlService.java | 50 +- .../StatusBarControlServiceImpl.java | 198 +- .../statusBarService/StatusBarService.java | 76 +- .../utils/InsertStatusBarItemResult.java | 58 +- .../toolBarService/ToolBarControlService.java | 50 +- .../toolBarService/ToolBarControlServiceImpl.java | 258 +-- .../services/toolBarService/ToolBarService.java | 58 +- .../utils/InsertToolBarItemResult.java | 76 +- .../promod/services/userService/UserService.java | 80 +- 129 files changed, 17762 insertions(+), 17762 deletions(-) diff --git a/Extensions/ExtensionMemoryIndicator/src/cz/cvut/promod/memory/MemoryIndicatorExtension.java b/Extensions/ExtensionMemoryIndicator/src/cz/cvut/promod/memory/MemoryIndicatorExtension.java index 8b3c8b4..e1e3a40 100644 --- a/Extensions/ExtensionMemoryIndicator/src/cz/cvut/promod/memory/MemoryIndicatorExtension.java +++ b/Extensions/ExtensionMemoryIndicator/src/cz/cvut/promod/memory/MemoryIndicatorExtension.java @@ -1,86 +1,86 @@ -package cz.cvut.promod.memory; - -import cz.cvut.promod.plugin.extension.Extension; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.gui.ModelerModel; - -import java.util.List; -import java.util.Properties; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -import com.jidesoft.dialog.AbstractDialogPage; -import com.jidesoft.status.MemoryStatusBarItem; -import com.jidesoft.status.ResizeStatusBarItem; -import com.jidesoft.status.EmptyStatusBarItem; -import com.jidesoft.swing.JideBoxLayout; -import org.apache.log4j.Logger; - - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:20:52, 26.1.2010 - * - * Extension that appends memory indicator and resizer to the modeler's status bar. - */ -public class MemoryIndicatorExtension implements Extension { - - private static final Logger LOG = Logger.getLogger(MemoryIndicatorExtension.class); - - private final MemoryIndicatorExtensionModel model; - - public MemoryIndicatorExtension(final File propertiesFile) throws InstantiationException{ - final Properties properties = new Properties(); - try { - properties.load(new FileReader(propertiesFile)); - } catch (IOException e) { - LOG.error("Properties for the MemoryIndicator Extension couldn't be read.", e); - throw new InstantiationException("Mandatory properties couldn't be read."); - } - - model = new MemoryIndicatorExtensionModel(properties); - } - - /** {@inheritDoc} */ - public String getIdentifier() { - return model.getIdentifier(); - } - - /** {@inheritDoc} */ - public String getName() { - return model.getName(); - } - - /** {@inheritDoc} */ - public String getDescription() { - return model.getDescription(); - } - - public void init() { - ModelerSession.getStatusBarService().addStatusBarItem( - ModelerModel.MODELER_IDENTIFIER, new EmptyStatusBarItem(), JideBoxLayout.VARY - ); - - if(model.isMemoryIndicatorVisible()){ - ModelerSession.getStatusBarService().addStatusBarItem( - ModelerModel.MODELER_IDENTIFIER, new MemoryStatusBarItem(), model.getPosition() - ); - } - - if(model.isResizerVisible()){ - ModelerSession.getStatusBarService().addStatusBarItem( - ModelerModel.MODELER_IDENTIFIER, new ResizeStatusBarItem(), JideBoxLayout.FIX - ); - } - } - - public void finish() { - - } - - public List getSettingPages() { - return null; - } -} +package cz.cvut.promod.memory; + +import cz.cvut.promod.plugin.extension.Extension; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.gui.ModelerModel; + +import java.util.List; +import java.util.Properties; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import com.jidesoft.dialog.AbstractDialogPage; +import com.jidesoft.status.MemoryStatusBarItem; +import com.jidesoft.status.ResizeStatusBarItem; +import com.jidesoft.status.EmptyStatusBarItem; +import com.jidesoft.swing.JideBoxLayout; +import org.apache.log4j.Logger; + + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:20:52, 26.1.2010 + * + * Extension that appends memory indicator and resizer to the modeler's status bar. + */ +public class MemoryIndicatorExtension implements Extension { + + private static final Logger LOG = Logger.getLogger(MemoryIndicatorExtension.class); + + private final MemoryIndicatorExtensionModel model; + + public MemoryIndicatorExtension(final File propertiesFile) throws InstantiationException{ + final Properties properties = new Properties(); + try { + properties.load(new FileReader(propertiesFile)); + } catch (IOException e) { + LOG.error("Properties for the MemoryIndicator Extension couldn't be read.", e); + throw new InstantiationException("Mandatory properties couldn't be read."); + } + + model = new MemoryIndicatorExtensionModel(properties); + } + + /** {@inheritDoc} */ + public String getIdentifier() { + return model.getIdentifier(); + } + + /** {@inheritDoc} */ + public String getName() { + return model.getName(); + } + + /** {@inheritDoc} */ + public String getDescription() { + return model.getDescription(); + } + + public void init() { + ModelerSession.getStatusBarService().addStatusBarItem( + ModelerModel.MODELER_IDENTIFIER, new EmptyStatusBarItem(), JideBoxLayout.VARY + ); + + if(model.isMemoryIndicatorVisible()){ + ModelerSession.getStatusBarService().addStatusBarItem( + ModelerModel.MODELER_IDENTIFIER, new MemoryStatusBarItem(), model.getPosition() + ); + } + + if(model.isResizerVisible()){ + ModelerSession.getStatusBarService().addStatusBarItem( + ModelerModel.MODELER_IDENTIFIER, new ResizeStatusBarItem(), JideBoxLayout.FIX + ); + } + } + + public void finish() { + + } + + public List getSettingPages() { + return null; + } +} diff --git a/Extensions/ExtensionMemoryIndicator/src/cz/cvut/promod/memory/MemoryIndicatorExtensionModel.java b/Extensions/ExtensionMemoryIndicator/src/cz/cvut/promod/memory/MemoryIndicatorExtensionModel.java index e14b9d5..c65e2bf 100644 --- a/Extensions/ExtensionMemoryIndicator/src/cz/cvut/promod/memory/MemoryIndicatorExtensionModel.java +++ b/Extensions/ExtensionMemoryIndicator/src/cz/cvut/promod/memory/MemoryIndicatorExtensionModel.java @@ -1,114 +1,114 @@ -package cz.cvut.promod.memory; - -import org.apache.log4j.Logger; - -import java.util.Properties; - -import com.jidesoft.swing.JideBoxLayout; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 10:50:46, 28.1.2010 - * - * Implementation of a model component for MemoryIndicatorExtension extension. - */ -public class MemoryIndicatorExtensionModel { - - private static final Logger LOG = Logger.getLogger(MemoryIndicatorExtensionModel.class); - - public static final String MEM_INDICATOR_VISIBILITY_KEY = "memoryIndicator.memoryIndicator.visible"; - public static final String MEM_INDICATOR_SIZE_KEY = "memoryIndicator.memoryIndicator.size"; - public static final String RESIZER_VISIBILITY_KEY = "memoryIndicator.resizer.visible"; - - public static final String IDENTIFIER_KEY = "memoryIndicator.memoryIndicator.identifier"; - public static final String NAME_KEY = "memoryIndicator.memoryIndicator.name"; - public static final String DESCRIPTION_KEY = "memoryIndicator.memoryIndicator.description"; - - public static final String VARY_POSITION = "vary"; - public static final String FLEXIBLE_POSITION = "flexible"; - - private static final String MEM_INDICATOR_VISIBLE_DEFAULT = "true"; - private static final String RESIZER_VISIBLE_DEFAULT = "true"; - private static final String SIZE_VISIBLE_DEFAULT = JideBoxLayout.FLEXIBLE; - - public static final String NAME_DEFAULT = "Memory status bar indicator"; - public static final String DESCRIPTION_DEFAULT = "Basic modeler status bar extension."; - - private final boolean memoryIndicatorVisible; - private final boolean resizerVisible; - private final String position; - - private final String identifier; - private final String description; - private final String name; - - - public MemoryIndicatorExtensionModel(final Properties properties) throws InstantiationException{ - try{ - if(!properties.containsKey(MEM_INDICATOR_VISIBILITY_KEY)){ - LOG.info("Missing property " + MEM_INDICATOR_VISIBILITY_KEY + ". Using default value."); - } - memoryIndicatorVisible = Boolean.parseBoolean(properties.getProperty(MEM_INDICATOR_VISIBILITY_KEY, MEM_INDICATOR_VISIBLE_DEFAULT).trim()); - - if(!properties.containsKey(RESIZER_VISIBILITY_KEY)){ - LOG.info("Missing property " + RESIZER_VISIBILITY_KEY + ". Using default value."); - } - resizerVisible = Boolean.parseBoolean(properties.getProperty(RESIZER_VISIBILITY_KEY, RESIZER_VISIBLE_DEFAULT).trim()); - - final String size = properties.getProperty(MEM_INDICATOR_SIZE_KEY).trim(); - if(size.equalsIgnoreCase(VARY_POSITION)){ - position = JideBoxLayout.VARY; - } else if(size.equalsIgnoreCase(FLEXIBLE_POSITION)){ - position = JideBoxLayout.FLEXIBLE; - } else { - LOG.info("Missing property " + MEM_INDICATOR_SIZE_KEY + ". Using default value."); - position = SIZE_VISIBLE_DEFAULT; - } - - if(!properties.containsKey(NAME_KEY)){ - LOG.info("Missing property " + NAME_KEY + ". Using default value."); - } - name = properties.getProperty(NAME_KEY, NAME_DEFAULT).trim(); - - if(!properties.containsKey(DESCRIPTION_KEY)){ - LOG.info("Missing property " + DESCRIPTION_KEY + ". Using default value."); - } - description = properties.getProperty(DESCRIPTION_KEY, DESCRIPTION_DEFAULT).trim(); - - if(!properties.containsKey(IDENTIFIER_KEY)){ - LOG.info("Missing property " + IDENTIFIER_KEY + ". Stopping instantiation."); - throw new InstantiationException("Missing property " + IDENTIFIER_KEY + ". Stopping instantiation."); - } - identifier = properties.getProperty(IDENTIFIER_KEY); - - } catch (Exception exception){ - LOG.error("An error has occurred.", exception); - throw new InstantiationException(exception.getMessage()); - } - } - - public String getPosition() { - return position; - } - - public boolean isResizerVisible() { - return resizerVisible; - } - - public boolean isMemoryIndicatorVisible() { - return memoryIndicatorVisible; - } - - public String getIdentifier() { - return identifier; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } -} +package cz.cvut.promod.memory; + +import org.apache.log4j.Logger; + +import java.util.Properties; + +import com.jidesoft.swing.JideBoxLayout; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 10:50:46, 28.1.2010 + * + * Implementation of a model component for MemoryIndicatorExtension extension. + */ +public class MemoryIndicatorExtensionModel { + + private static final Logger LOG = Logger.getLogger(MemoryIndicatorExtensionModel.class); + + public static final String MEM_INDICATOR_VISIBILITY_KEY = "memoryIndicator.memoryIndicator.visible"; + public static final String MEM_INDICATOR_SIZE_KEY = "memoryIndicator.memoryIndicator.size"; + public static final String RESIZER_VISIBILITY_KEY = "memoryIndicator.resizer.visible"; + + public static final String IDENTIFIER_KEY = "memoryIndicator.memoryIndicator.identifier"; + public static final String NAME_KEY = "memoryIndicator.memoryIndicator.name"; + public static final String DESCRIPTION_KEY = "memoryIndicator.memoryIndicator.description"; + + public static final String VARY_POSITION = "vary"; + public static final String FLEXIBLE_POSITION = "flexible"; + + private static final String MEM_INDICATOR_VISIBLE_DEFAULT = "true"; + private static final String RESIZER_VISIBLE_DEFAULT = "true"; + private static final String SIZE_VISIBLE_DEFAULT = JideBoxLayout.FLEXIBLE; + + public static final String NAME_DEFAULT = "Memory status bar indicator"; + public static final String DESCRIPTION_DEFAULT = "Basic modeler status bar extension."; + + private final boolean memoryIndicatorVisible; + private final boolean resizerVisible; + private final String position; + + private final String identifier; + private final String description; + private final String name; + + + public MemoryIndicatorExtensionModel(final Properties properties) throws InstantiationException{ + try{ + if(!properties.containsKey(MEM_INDICATOR_VISIBILITY_KEY)){ + LOG.info("Missing property " + MEM_INDICATOR_VISIBILITY_KEY + ". Using default value."); + } + memoryIndicatorVisible = Boolean.parseBoolean(properties.getProperty(MEM_INDICATOR_VISIBILITY_KEY, MEM_INDICATOR_VISIBLE_DEFAULT).trim()); + + if(!properties.containsKey(RESIZER_VISIBILITY_KEY)){ + LOG.info("Missing property " + RESIZER_VISIBILITY_KEY + ". Using default value."); + } + resizerVisible = Boolean.parseBoolean(properties.getProperty(RESIZER_VISIBILITY_KEY, RESIZER_VISIBLE_DEFAULT).trim()); + + final String size = properties.getProperty(MEM_INDICATOR_SIZE_KEY).trim(); + if(size.equalsIgnoreCase(VARY_POSITION)){ + position = JideBoxLayout.VARY; + } else if(size.equalsIgnoreCase(FLEXIBLE_POSITION)){ + position = JideBoxLayout.FLEXIBLE; + } else { + LOG.info("Missing property " + MEM_INDICATOR_SIZE_KEY + ". Using default value."); + position = SIZE_VISIBLE_DEFAULT; + } + + if(!properties.containsKey(NAME_KEY)){ + LOG.info("Missing property " + NAME_KEY + ". Using default value."); + } + name = properties.getProperty(NAME_KEY, NAME_DEFAULT).trim(); + + if(!properties.containsKey(DESCRIPTION_KEY)){ + LOG.info("Missing property " + DESCRIPTION_KEY + ". Using default value."); + } + description = properties.getProperty(DESCRIPTION_KEY, DESCRIPTION_DEFAULT).trim(); + + if(!properties.containsKey(IDENTIFIER_KEY)){ + LOG.info("Missing property " + IDENTIFIER_KEY + ". Stopping instantiation."); + throw new InstantiationException("Missing property " + IDENTIFIER_KEY + ". Stopping instantiation."); + } + identifier = properties.getProperty(IDENTIFIER_KEY); + + } catch (Exception exception){ + LOG.error("An error has occurred.", exception); + throw new InstantiationException(exception.getMessage()); + } + } + + public String getPosition() { + return position; + } + + public boolean isResizerVisible() { + return resizerVisible; + } + + public boolean isMemoryIndicatorVisible() { + return memoryIndicatorVisible; + } + + public String getIdentifier() { + return identifier; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } +} diff --git a/IndependentModeler/epcImageExportModule.properties b/IndependentModeler/epcImageExportModule.properties index b34ae6b..992b1ea 100644 --- a/IndependentModeler/epcImageExportModule.properties +++ b/IndependentModeler/epcImageExportModule.properties @@ -1,5 +1,5 @@ -epc.notation.identifier = f8b79111-ddb3-4c23-8d2d-f9fc687278fb - -epc.imageexport.png.identifier = EPCImageExport -epc.imageexport.png.name = EPCImageExportModule +epc.notation.identifier = f8b79111-ddb3-4c23-8d2d-f9fc687278fb + +epc.imageexport.png.identifier = EPCImageExport +epc.imageexport.png.name = EPCImageExportModule epc.imageexport.png.description = A module for image export (PNG format) of diagrams defined by EPC Notation (EPCNotation plugin). \ No newline at end of file diff --git a/IndependentModeler/epcNotation.properties b/IndependentModeler/epcNotation.properties index 7d8f967..db84529 100644 --- a/IndependentModeler/epcNotation.properties +++ b/IndependentModeler/epcNotation.properties @@ -1,15 +1,15 @@ -epc.identifier = f8b79111-ddb3-4c23-8d2d-f9fc687278fb -epc.full.name = Event-Driven Process -epc.abbreviation = EPC -epc.file.extension = epc -epc.name = EPCNotation -epc.description = Plugin implemeting the EPC notation. - -epc.action.refresh = epc.action.refresh -epc.action.undo = epc.action.undo -epc.action.redo = epc.action.redo -epc.action.save = epc.action.save -epc.action.save.all = epc.action.save.all -epc.action.delete = epc.action.delete - +epc.identifier = f8b79111-ddb3-4c23-8d2d-f9fc687278fb +epc.full.name = Event-Driven Process +epc.abbreviation = EPC +epc.file.extension = epc +epc.name = EPCNotation +epc.description = Plugin implemeting the EPC notation. + +epc.action.refresh = epc.action.refresh +epc.action.undo = epc.action.undo +epc.action.redo = epc.action.redo +epc.action.save = epc.action.save +epc.action.save.all = epc.action.save.all +epc.action.delete = epc.action.delete + undo.limit = 10 \ No newline at end of file diff --git a/IndependentModeler/memoryIndicator.properties b/IndependentModeler/memoryIndicator.properties index e77fcf0..7ed9e6d 100644 --- a/IndependentModeler/memoryIndicator.properties +++ b/IndependentModeler/memoryIndicator.properties @@ -1,12 +1,12 @@ -memoryIndicator.memoryIndicator.identifier = b51716d6-cedd-4466-a0a9-dc1225b90494 -memoryIndicator.memoryIndicator.name = Basic status bar -memoryIndicator.memoryIndicator.description = Appends memory indicator and a simple resizer to the modeler status bar. - -memoryIndicator.memoryIndicator.visible = true -#memoryIndicator.memoryIndicator.visible = false - -memoryIndicator.memoryIndicator.size = flexible -#memoryIndicator.memoryIndicator.size = vary - -memoryIndicator.resizer.visible = true +memoryIndicator.memoryIndicator.identifier = b51716d6-cedd-4466-a0a9-dc1225b90494 +memoryIndicator.memoryIndicator.name = Basic status bar +memoryIndicator.memoryIndicator.description = Appends memory indicator and a simple resizer to the modeler status bar. + +memoryIndicator.memoryIndicator.visible = true +#memoryIndicator.memoryIndicator.visible = false + +memoryIndicator.memoryIndicator.size = flexible +#memoryIndicator.memoryIndicator.size = vary + +memoryIndicator.resizer.visible = true #memoryIndicator.resizer.visible = false \ No newline at end of file diff --git a/IndependentModeler/phDiagramReference.properties b/IndependentModeler/phDiagramReference.properties index 797640b..f0f669e 100644 --- a/IndependentModeler/phDiagramReference.properties +++ b/IndependentModeler/phDiagramReference.properties @@ -1 +1 @@ -identifier = 1234567890 +identifier = 1234567890 diff --git a/IndependentModeler/resources/config/plugins.xsd b/IndependentModeler/resources/config/plugins.xsd index 42d3e87..ce56c06 100644 --- a/IndependentModeler/resources/config/plugins.xsd +++ b/IndependentModeler/resources/config/plugins.xsd @@ -1,53 +1,53 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/IndependentModeler/resources/config/project.xsd b/IndependentModeler/resources/config/project.xsd index f340242..3670ad7 100644 --- a/IndependentModeler/resources/config/project.xsd +++ b/IndependentModeler/resources/config/project.xsd @@ -1,88 +1,88 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/actions/LoadDialogAction.java b/IndependentModeler/src/cz/cvut/promod/actions/LoadDialogAction.java index 55dba4b..d6d9696 100644 --- a/IndependentModeler/src/cz/cvut/promod/actions/LoadDialogAction.java +++ b/IndependentModeler/src/cz/cvut/promod/actions/LoadDialogAction.java @@ -1,129 +1,129 @@ -package cz.cvut.promod.actions; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.results.AddProjectItemResult; -import cz.cvut.promod.services.projectService.results.LoadProjectResult; -import cz.cvut.promod.services.projectService.results.ConfigurationDifference; -import cz.cvut.promod.gui.support.utils.LoadProjectDialogFileFilter; -import cz.cvut.promod.gui.projectNavigation.ProjectNavigation; -import cz.cvut.promod.gui.projectNavigation.events.ProjectTreeExpandEvent; -import cz.cvut.promod.gui.ModelerModel; -import cz.cvut.promod.gui.dialogs.configurationChangeDialog.ConfigurationDiffDialog; - -import javax.swing.*; -import javax.swing.tree.TreePath; -import java.io.File; -import java.awt.event.ActionEvent; -import java.util.List; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:47:03, 11.11.2009 - * - * Project load actions. - */ -public class LoadDialogAction extends ProModAction { - - private static final Logger LOG = Logger.getLogger(LoadDialogAction.class); - - public LoadDialogAction(final String displayName, - final Icon icon, - final KeyStroke keyStroke) { - - super(displayName, icon, keyStroke); - } - - public void actionPerformed(ActionEvent event) { - - final JFileChooser fileChooser = new JFileChooser(); - fileChooser.setFileFilter(new LoadProjectDialogFileFilter()); - - final int returnVal = fileChooser.showOpenDialog(ModelerSession.getFrame()); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - final File selectedFile = fileChooser.getSelectedFile(); - - final LoadProjectResult loadResult = ModelerSession.getProjectControlService().loadProject(selectedFile); - - if(loadResult.getProjectRoot() == null){ - JOptionPane.showMessageDialog( - ModelerSession.getFrame(), - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile"), - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile.title"), - JOptionPane.ERROR_MESSAGE); - - return; - } - - // show the configuration differences dialog - final List differences = loadResult.getMessages(); - if(differences != null && !differences.isEmpty()){ - new ConfigurationDiffDialog(differences); - } - - final AddProjectItemResult result = ModelerSession.getProjectControlService().addProject( - new ProjectRoot(loadResult.getProjectRoot().getDisplayName(), loadResult.getProjectRoot().getProjectLocation()), true - ); - - switch (result.getStatus()){ - case SUCCESS: - //sync project structure with file system = load project data - ModelerSession.getProjectControlService().synchronize( - loadResult.getProjectRoot().getProjectFile(), null, true, false, false, true); - - final ProModAction action = ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ProjectNavigation.ACTION_EXPAND); - - final TreePath projectTreePath = result.getTreePath(); - ModelerSession.getProjectControlService().setSelectedItem(projectTreePath); - - if(action != null && projectTreePath != null){ - action.actionPerformed(new ProjectTreeExpandEvent(this, projectTreePath, 1, true)); - } else { - LOG.error("Expand action and/or project node is/are not available."); - } - - break; - case NAME_DUPLICITY: - alertNameDuplicity(); - break; - case INVALID_NAME: - alertIllegalName(); - break; - default: - alertGeneralError(); - } - - } - } - - private void alertGeneralError() { - JOptionPane.showMessageDialog( - ModelerSession.getFrame(), - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile"), - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile.title"), - JOptionPane.ERROR_MESSAGE); - } - - private void alertIllegalName() { - JOptionPane.showMessageDialog( - ModelerSession.getFrame(), - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile"), - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile.title"), - JOptionPane.ERROR_MESSAGE); - } - - private void alertNameDuplicity() { - JOptionPane.showMessageDialog( - ModelerSession.getFrame(), - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile"), - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile.title"), - JOptionPane.ERROR_MESSAGE); - } - -} +package cz.cvut.promod.actions; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.results.AddProjectItemResult; +import cz.cvut.promod.services.projectService.results.LoadProjectResult; +import cz.cvut.promod.services.projectService.results.ConfigurationDifference; +import cz.cvut.promod.gui.support.utils.LoadProjectDialogFileFilter; +import cz.cvut.promod.gui.projectNavigation.ProjectNavigation; +import cz.cvut.promod.gui.projectNavigation.events.ProjectTreeExpandEvent; +import cz.cvut.promod.gui.ModelerModel; +import cz.cvut.promod.gui.dialogs.configurationChangeDialog.ConfigurationDiffDialog; + +import javax.swing.*; +import javax.swing.tree.TreePath; +import java.io.File; +import java.awt.event.ActionEvent; +import java.util.List; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:47:03, 11.11.2009 + * + * Project load actions. + */ +public class LoadDialogAction extends ProModAction { + + private static final Logger LOG = Logger.getLogger(LoadDialogAction.class); + + public LoadDialogAction(final String displayName, + final Icon icon, + final KeyStroke keyStroke) { + + super(displayName, icon, keyStroke); + } + + public void actionPerformed(ActionEvent event) { + + final JFileChooser fileChooser = new JFileChooser(); + fileChooser.setFileFilter(new LoadProjectDialogFileFilter()); + + final int returnVal = fileChooser.showOpenDialog(ModelerSession.getFrame()); + + if (returnVal == JFileChooser.APPROVE_OPTION) { + final File selectedFile = fileChooser.getSelectedFile(); + + final LoadProjectResult loadResult = ModelerSession.getProjectControlService().loadProject(selectedFile); + + if(loadResult.getProjectRoot() == null){ + JOptionPane.showMessageDialog( + ModelerSession.getFrame(), + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile"), + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile.title"), + JOptionPane.ERROR_MESSAGE); + + return; + } + + // show the configuration differences dialog + final List differences = loadResult.getMessages(); + if(differences != null && !differences.isEmpty()){ + new ConfigurationDiffDialog(differences); + } + + final AddProjectItemResult result = ModelerSession.getProjectControlService().addProject( + new ProjectRoot(loadResult.getProjectRoot().getDisplayName(), loadResult.getProjectRoot().getProjectLocation()), true + ); + + switch (result.getStatus()){ + case SUCCESS: + //sync project structure with file system = load project data + ModelerSession.getProjectControlService().synchronize( + loadResult.getProjectRoot().getProjectFile(), null, true, false, false, true); + + final ProModAction action = ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ProjectNavigation.ACTION_EXPAND); + + final TreePath projectTreePath = result.getTreePath(); + ModelerSession.getProjectControlService().setSelectedItem(projectTreePath); + + if(action != null && projectTreePath != null){ + action.actionPerformed(new ProjectTreeExpandEvent(this, projectTreePath, 1, true)); + } else { + LOG.error("Expand action and/or project node is/are not available."); + } + + break; + case NAME_DUPLICITY: + alertNameDuplicity(); + break; + case INVALID_NAME: + alertIllegalName(); + break; + default: + alertGeneralError(); + } + + } + } + + private void alertGeneralError() { + JOptionPane.showMessageDialog( + ModelerSession.getFrame(), + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile"), + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile.title"), + JOptionPane.ERROR_MESSAGE); + } + + private void alertIllegalName() { + JOptionPane.showMessageDialog( + ModelerSession.getFrame(), + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile"), + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile.title"), + JOptionPane.ERROR_MESSAGE); + } + + private void alertNameDuplicity() { + JOptionPane.showMessageDialog( + ModelerSession.getFrame(), + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile"), + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.loadfile.title"), + JOptionPane.ERROR_MESSAGE); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/Modeler.java b/IndependentModeler/src/cz/cvut/promod/gui/Modeler.java index f1b4d52..e563f32 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/Modeler.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/Modeler.java @@ -1,1068 +1,1068 @@ -package cz.cvut.promod.gui; - -import com.jidesoft.dialog.AbstractDialogPage; -import com.jidesoft.docking.DockableFrame; -import com.jidesoft.swing.JideButton; -import cz.cvut.promod.actions.LoadDialogAction; -import cz.cvut.promod.gui.dialogs.loadErrors.LoadErrorsDialog; -import cz.cvut.promod.gui.dialogs.newProject.NewProjectDialog; -import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialog; -import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialogExecutor; -import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogDialog; -import cz.cvut.promod.gui.listeners.ButtonPopupAdapter; -import cz.cvut.promod.gui.listeners.DockFrameListener; -import cz.cvut.promod.gui.listeners.SideButtonListener; -import cz.cvut.promod.gui.settings.BasicSettingPage; -import cz.cvut.promod.gui.settings.SettingsDialog; -import cz.cvut.promod.gui.support.utils.DockableFrameWrapper; -import cz.cvut.promod.gui.support.utils.NotationGuiHolder; -import cz.cvut.promod.plugin.extension.Extension; -import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; -import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.NotationWorkspaceData; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.utils.NotationWorkspaceDataDefault; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.workspace.UpdatableWorkspaceComponent; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import cz.cvut.promod.services.menuService.MenuControlService; -import cz.cvut.promod.services.menuService.MenuService; -import cz.cvut.promod.services.menuService.utils.ModelerMenuItem; -import cz.cvut.promod.services.menuService.utils.MenuItemPosition; -import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; -import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; -import cz.cvut.promod.resources.Resources; -import org.apache.log4j.Logger; - -import javax.swing.*; -import javax.swing.tree.TreePath; -import java.awt.*; -import java.awt.event.*; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:09:42, 10.10.2009 - */ - -/** - * Basic class of the host application. - */ -public class Modeler extends ModelerView{ - - private static final Logger LOG = Logger.getLogger(Modeler.class); - - public static final String ACTION_NEW_PROJECT_DIALOG = "modeler.action.new.project"; - public static final String ACTION_EXIT = "modeler.action.exit"; - public static final String ACTION_PROJECT_LOAD = "modeler.action.project.load"; - public static final String ACTION_PROJECT_SAVE = "modeler.action.project.save"; - public static final String ACTION_SWITH_USER = "modeler.action.switch.user"; - public static final String ACTION_PROJECT_NAVIG_SHOW = "modeler.action.navigation"; - public static final String ACTION_SETTINGS_SHOW = "modeler.action.settings"; - public static final String ACTION_PLUGINS_OVERVIEW_SHOW = "modeler.action.plugins.overview"; - - public static final String LOAD_SYNC_TITLE_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.sync.title"); - public static final String LOAD_SYNC_MESSAGE_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.sync.message"); - public static final String USER_CHANGE_DIALOG_TITLE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.user.service"); - public static final String USER_CHANGE_DIALOG_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.user.name"); - public static final String OK_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.ok"); - public static final String YES_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.yes"); - public static final String NO_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.no"); - public static final String CANCEL_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.cancel"); - public static final String USER_CHANGE_DIALOG_INVALID_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.user.invalid.name"); - public static final String SAVE_ALL_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.exit.save.all"); - public static final String SKIP_ALL_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.exit.skip.all"); - public static final String PROMOD_EXIT_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.exit"); - public static final String UNSAVED_CHANGE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.exit.diagram.unsaved.change"); - public static final String SETTINGS_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.settings"); - public static final String FILE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.menu.file"); - public static final String PROJECT_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.menu.project"); - public static final String EDIT_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.menu.edit"); - public static final String WINDOW_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.menu.window"); - public static final String PLUGINS_OVERVIEW_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview"); - - public static final Object[] EXIT_DIALOG_OPTIONS = { - YES_LABEL,NO_LABEL, SAVE_ALL_LABEL, SKIP_ALL_LABEL, CANCEL_LABEL}; - - public static enum ExitDialogReturnValues {CONTINUE, STOP, CANCEL} - - private final ModelerModel model; - - - public Modeler( ){ - ModelerSession.setFrame(this); - - this.model = new ModelerModel(); - - initActions(); - - initMainMenu(); - - initProjectNavigation(); - - initEventHandling(); - } - - /** - * Initialize actions that belong to the 'virtual' "modeler" notation. - */ - private void initActions(){ - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_PLUGINS_OVERVIEW_SHOW, - new ProModAction(PLUGINS_OVERVIEW_LABEL, null, KeyStroke.getKeyStroke( - KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ - public void actionPerformed(ActionEvent event) { - new PluginsOverviewDialogDialog(); - } - } - ); - - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_PLUGINS_OVERVIEW_SHOW, - new ProModAction(PLUGINS_OVERVIEW_LABEL, null, KeyStroke.getKeyStroke( - KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ - public void actionPerformed(ActionEvent event) { - new PluginsOverviewDialogDialog(); - } - } - ); - - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_SETTINGS_SHOW, - new ProModAction(SETTINGS_LABEL, null, KeyStroke.getKeyStroke( - KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ - public void actionPerformed(ActionEvent event) { - SettingsDialog.showOptionsDialog(model.getSettingPagesModel()); - } - } - ); - - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_SWITH_USER, - new ProModAction(USER_CHANGE_DIALOG_LABEL, null, null){ - public void actionPerformed(ActionEvent event) { - new SimpleTextFieldDialog( - USER_CHANGE_DIALOG_TITLE_LABEL, - USER_CHANGE_DIALOG_LABEL, - "", - OK_LABEL, - CANCEL_LABEL, - new SimpleTextFieldDialogExecutor(){ - public String execute(final String text) { - if(text != null && !text.isEmpty()){ - ModelerSession.getUserService().setUser(text); - return null; - } - - return USER_CHANGE_DIALOG_INVALID_LABEL; - } - }, - ModelerSession.getFrame(), - true - ); - } - }); - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_NEW_PROJECT_DIALOG, - new ProModAction(ModelerSession.getCommonResourceBundle().getString( - ACTION_NEW_PROJECT_DIALOG), - Resources.getIcon(Resources.MODELER + Resources.NEW_PROJECT_ICON), - KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)){ - public void actionPerformed(ActionEvent event) { - new NewProjectDialog(); - } - }); - - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_EXIT, - new ProModAction(ModelerSession.getCommonResourceBundle().getString(ACTION_EXIT), null, null){ - public void actionPerformed(ActionEvent event) { - modelerExit(); - } - }); - - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_PROJECT_NAVIG_SHOW, - new ProModAction(ModelerSession.getCommonResourceBundle().getString(ACTION_PROJECT_NAVIG_SHOW), null, null){ - public void actionPerformed(ActionEvent event) { - swapProjectNavigationVisibility(); - - // update control components selection - putValue(Action.SELECTED_KEY, projectNavigationDockableFrame.isAvailable()); - projectNavigatorButton.setSelected(projectNavigationDockableFrame.isAvailable()); - } - } - ); - - - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_PROJECT_SAVE, - new ProModAction(ModelerSession.getCommonResourceBundle().getString(ACTION_PROJECT_SAVE), - Resources.getIcon(Resources.MODELER + Resources.SAVE_ALL_ICON), - KeyStroke.getKeyStroke( - KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)){ - public void actionPerformed(ActionEvent event) { - LOG.debug("Action save invoked."); - - final TreePath projectTreePath = ModelerSession.getProjectService().getSelectedProjectPath(); - - if(projectTreePath == null){ - - } else { - final boolean syncResult = ModelerSession.getProjectControlService().synchronize( - projectTreePath, true, true, false, false); - - if (!syncResult){ - JOptionPane.showMessageDialog( - ModelerSession.getFrame(), - LOAD_SYNC_MESSAGE_ERROR_LABEL, - LOAD_SYNC_TITLE_ERROR_LABEL, - JOptionPane.ERROR_MESSAGE); - } - } - } - }); - - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_PROJECT_LOAD, - new LoadDialogAction(ModelerSession.getCommonResourceBundle().getString( - ACTION_PROJECT_LOAD), - Resources.getIcon(Resources.MODELER + Resources.OPEN_ICON), - KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK))); - } - - /** - * Changed the project navigation visibility. - */ - private void swapProjectNavigationVisibility(){ - if( projectNavigationDockableFrame.isAvailable() ){ - dockingManager.setFrameUnavailable(projectNavigationDockableFrame.getName()); - } else{ - final String currentNotation = ModelerSession.getProjectService().getSelectedProjectNotationIndentifier(); - - final NotationGuiHolder specification = model.getNotationGuiHolder(currentNotation); - - if( specification != null ){ - final List visibleDockableFrames = new LinkedList(); - - for( final DockableFrame dockableFrame : specification.getListOfFrames(NotationGuiHolder.Position.LEFT) ){ - if( dockableFrame.isAvailable() ){ - visibleDockableFrames.add((dockableFrame)); - specification.getButton(dockableFrame.getName(), NotationGuiHolder.Position.LEFT).doClick(); - } - } - - dockingManager.setFrameAvailable(projectNavigationDockableFrame.getName()); - - for( final DockableFrame dockableFrame : visibleDockableFrames ){ - specification.getButton(dockableFrame.getName(), NotationGuiHolder.Position.LEFT).doClick(); - } - } else{ - dockingManager.setFrameAvailable(projectNavigationDockableFrame.getName()); - } - } - } - - /** - * Performs the terminating sequence. - */ - private void modelerExit() { - LOG.info("Modeler is shutting down."); - - if(!checkForUnsavedChanges()){ - LOG.info("ProMod shut-down has been canceled by user"); - return; - } - - setVisible(false); - - // finishing notations & modules - for(final String notationIdentifier : ModelerSession.getNotationService().getNotationsIdentifiers()){ - final NotationSpecificPlugins notationSpecificPlugins = ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier); - - notationSpecificPlugins.getNotation().finish(); - - for(final Module module : notationSpecificPlugins.getModules()){ - module.finish(); - } - } - - // finishing extensions - for(Extension extension : ModelerSession.getExtensionService().getExtensions()){ - extension.finish(); - } - - dispose(); - System.exit(0); - } - - /** - * Looks for unsaved changes in projects. - * - * @return true if ProMod is supposed to be terminated, false if the ProMod termination has been canceled - */ - private boolean checkForUnsavedChanges() { - for(final TreePath projectTreePath : ModelerSession.getProjectService().getProjectPaths()){ - if(ExitDialogReturnValues.CANCEL.equals( - projectNavigationDockableFrame.checkForUnsavedChanges(projectTreePath, projectTreePath) - )){ - // ProMod termination has been canceled by user - return false; - } - } - - return true; - } - - /** - * Performs the context switching mechanism. - */ - private void updateView(){ - String newNotationIdentifier = ModelerSession.getProjectService().getSelectedProjectNotationIndentifier(); - final String oldNotationIdentifier = model.getSelectedNotation(); - - //if no diagram is selected, use default modeler view - if(newNotationIdentifier == null){ - newNotationIdentifier = ModelerModel.MODELER_IDENTIFIER; - } - - updateProjectDiagram(false); // order of over method invocation with respect to possible automatic sync. mechanisms - updateWorkspaceComponent(oldNotationIdentifier, false); - - if(!newNotationIdentifier.equals(oldNotationIdentifier)){ - updateModelerView(newNotationIdentifier); - ModelerSession.getActionControlService().updateActionsVisibility(newNotationIdentifier); - updateMainMenusVisibility(newNotationIdentifier); - updateDockableFramesVisibility(newNotationIdentifier, oldNotationIdentifier); - } - - updateWorkspaceComponent(newNotationIdentifier, true); // order of over method invocation with respect to possible automatic sync. mechanisms - updateProjectDiagram(true); - - model.setSelectedNotation(newNotationIdentifier); - } - - /** - * Updates the project diagram. - * - * @param update if true, update will be performed, otherwise over will be performed - */ - private void updateProjectDiagram(final boolean update) { - if(ModelerSession.getProjectService().getSelectedDiagram() != null){ - if(update){ - ModelerSession.getProjectService().getSelectedDiagram().getDiagramModel().update(); - } else { - ModelerSession.getProjectService().getSelectedDiagram().getDiagramModel().over(); - } - } - } - - /** - * Updates the main menu items visibility. - * - * @param newNotationIdentifier is the identifier of active notation - */ - private void updateMainMenusVisibility(final String newNotationIdentifier) { - final JMenuBar menuBar = getJMenuBar(); - - if(menuBar != null){ - - for(int i = 0; i < menuBar.getMenuCount(); i++){ - final JMenuItem menuItem = menuBar.getMenu(i); - boolean isVisible = updateMenuItemVisibility(menuItem, newNotationIdentifier); - - if(isVisible){ - menuItem.setEnabled(true); - } else { - menuItem.setEnabled(false); - } - } - - } - } - - /** - * Recursively goes through the menu structure and ensures that only items related to the currently selected notation - * will be enabled. - * - * @param parentMenuItem is the menu where the recursion begins - * @param newNotationIdentifier is the identifier of selected notation - * - * @return true if the parentMenuItem is supposed to be disabled, false otherwise - */ - private boolean updateMenuItemVisibility(final JMenuItem parentMenuItem, final String newNotationIdentifier) { - boolean isEnabled = false; - - parentMenuItem.setVisible(true); // always start with all items visible - - if(parentMenuItem instanceof JMenu){ - - final JMenu menu = (JMenu) parentMenuItem; - for(int i = 0; i < menu.getItemCount(); i++){ - final JMenuItem menuItem = menu.getItem(i); - - if(menuItem != null){ //separator is returned like a null item - isEnabled |= updateMenuItemVisibility(menuItem, newNotationIdentifier); - } - } - - menu.setEnabled(isEnabled); - return isEnabled; - } - - // menu item, hide relatives (menu items with the same text) - final boolean menuItemEnabled = parentMenuItem.isEnabled(); - - if(parentMenuItem instanceof ModelerMenuItem && !menuItemEnabled){ - final ModelerMenuItem menuItem = (ModelerMenuItem) parentMenuItem; - - final List relatives = menuItem.getListOfRelatives(); - if(relatives != null){ - if(relatives.isEmpty()){ - parentMenuItem.setVisible(false); - } else { - if(isAnotherRelativeVisible(relatives)){ - parentMenuItem.setVisible(false); - } - } - } - } - - return menuItemEnabled; - } - - /** - * Checks the list of relatives (relative are items in the menu under the same root with the same text on it) and - * decides whether this any of relative items is visible or not. - * - * @param relatives is the list of relative items - * @return true if any another relative item is visible, false otherwise - */ - private boolean isAnotherRelativeVisible(final List relatives) { - if(relatives == null || relatives.isEmpty()){ - return false; - } - - for(ModelerMenuItem modelerMenuItem : relatives){ - if(modelerMenuItem instanceof JMenuItem){ - final JMenuItem menuItem = (JMenuItem) modelerMenuItem; - if(menuItem.isEnabled()){ - return true; - } - } - } - - return false; - } - - /** - * Performs the context switch. - * - * @param newNotationIdentifier is the identifier of active notation. - */ - private void updateModelerView(final String newNotationIdentifier) { - if(newNotationIdentifier != null){ - cardLayoutLeftSidePane.show(leftSidePane, newNotationIdentifier); - cardLayoutRightSidePane.show(rightSidePane, newNotationIdentifier); - cardLayoutBottomSidePane.show(bottomSidePane, newNotationIdentifier); - cardLayoutTopSidePane.show(topSidePane, newNotationIdentifier); - - cardLayoutWorkspacePane.show(workspacePane, newNotationIdentifier); - - cardLayoutToolBar.show(toolBarPane, newNotationIdentifier); - - cardLayoutStatusBar.show(statusBarPane, newNotationIdentifier); - - } else { - LOG.error("Modeler view update error. Notation name cannot be null."); - } - } - - /** - * Performs the update() or ever() methods on workspace component if this component implements the - * UpdatableWorkspaceComponent interface. - * - * @param notationIdentifier is the identifier of the notation to which the workspace component belongs - * @param update is true when update() method is supposed to be invoked, the over() methods is invoked otherwise - */ - private void updateWorkspaceComponent(final String notationIdentifier, final boolean update) { - if(notationIdentifier != null && !ModelerModel.MODELER_IDENTIFIER.equals(notationIdentifier)){ - final JComponent workspaceComponent; - try{ - workspaceComponent = model.getNotationGuiHolder(notationIdentifier).getNotationWorkspace().getWorkspaceComponentSingleton(); - - if(workspaceComponent instanceof UpdatableWorkspaceComponent){ - final UpdatableWorkspaceComponent updatableWorkspaceComponent = (UpdatableWorkspaceComponent)workspaceComponent; - - if(update){ - updatableWorkspaceComponent.update(); - } else { - ModelerSession.clearFrameTitleText(); - updatableWorkspaceComponent.over(); - } - } - - } catch (NullPointerException exception){ - LOG.error("Not workspace provided, notationIdentifier: " + notationIdentifier); - } - } - } - - /** - * Updates the dockable frame visibility. - * - * @param newNotationIdentifier is the identifier of active notation - * @param oldNotationIdentifier is the identifier of previous notation. - */ - private void updateDockableFramesVisibility(final String newNotationIdentifier, final String oldNotationIdentifier) { - if(newNotationIdentifier == null || newNotationIdentifier.equals(oldNotationIdentifier)){ - // should never happened - LOG.debug("UpdateDockableFramesVisibility method has been invoked, even though newNotationIdentifier is the same as oldNotationIdentifier."); - } - - if(!ModelerModel.MODELER_IDENTIFIER.equals(oldNotationIdentifier) && oldNotationIdentifier != null){ - model.getNotationGuiHolder(oldNotationIdentifier).unable(); - } - - if(!ModelerModel.MODELER_IDENTIFIER.equals(newNotationIdentifier)){ - model.getNotationGuiHolder(newNotationIdentifier).enable(); - } - } - - /** - * Initialize main menu. - */ - private void initMainMenu() { - final MenuControlService mainMenuControlService; - try{ - mainMenuControlService = (MenuControlService) ModelerSession.getMenuService(); - } catch(ClassCastException exception){ - LOG.error("Main menu initialization not possible.", exception); - return; - } - - setJMenuBar(mainMenuControlService.getMenuBar()); - - // insert common menu items - // 'file' menu - ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_EXIT), - new MenuItemPosition(FILE_LABEL), MenuService.MenuSeparator.BEFORE - ); - - // 'project' menu - ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_NEW_PROJECT_DIALOG), - new MenuItemPosition(PROJECT_LABEL, MenuItemPosition.PlacementStyle.FIRST) - ); - - ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_PROJECT_SAVE), - new MenuItemPosition(PROJECT_LABEL), MenuService.MenuSeparator.BEFORE - ); - ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_PROJECT_LOAD), - new MenuItemPosition(PROJECT_LABEL) - ); - - // 'edit' Menu - ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_SETTINGS_SHOW), - new MenuItemPosition(EDIT_LABEL) - ); - - // 'window' menu - ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_PROJECT_NAVIG_SHOW), - new MenuItemPosition(WINDOW_LABEL), true - ); - ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_PLUGINS_OVERVIEW_SHOW), - new MenuItemPosition(WINDOW_LABEL) - ); - } - - /** - * Initialize the event handling. - */ - private void initEventHandling(){ - ModelerSession.getUserService().getUserValueModel().addValueChangeListener( - new PropertyChangeListener(){ - public void propertyChange(PropertyChangeEvent evt) { - loggedUserLabel.setText(ModelerSession.getUserService().getUser()); - } - } - ); - - switchUserButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_SWITH_USER).actionPerformed(null); - } - }); - - ModelerSession.getProjectService().getSelectedItem().addValueChangeListener(new PropertyChangeListener(){ - public void propertyChange(PropertyChangeEvent evt) { - updateView(); - } - }); - - // listener of window's closing button (cross button) - this.addWindowListener(new WindowAdapter(){ - @Override - public void windowClosing(WindowEvent e){ - - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_EXIT).actionPerformed(null); - } - }); - - projectNavigatorButton.addActionListener(ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_PROJECT_NAVIG_SHOW)); - } - - /** - * Installs the plugins into the gui. - */ - public void deployNotationSpecificPlugIns( ){ - for(final String notationIdentifier : ModelerSession.getNotationService().getNotationsIdentifiers()){ - final NotationSpecificPlugins notationSpecificPlugins = ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier); - - installNotationsAndModules(notationSpecificPlugins); - } - } - - /** - * Shows the application frame window. - */ - public void showFrame(){ - // update view to initial state - updateView(); - - dockingManager.loadLayoutData(); - - dockingManager.setFrameUnavailable(projectNavigationDockableFrame.getName()); - - for( final NotationGuiHolder notationGuiHolder : model.getNotationGuiHolders() ){ - for( final DockableFrameWrapper wrapper : notationGuiHolder.getAllDockableFrameFacades() ){ - dockingManager.setFrameAvailable(wrapper.getDockableFrame().getName()); - dockingManager.setFrameUnavailable(wrapper.getDockableFrame().getName()); - } - } - - setVisible(true); - - projectNavigatorButton.doClick(); - - showLoadingErrors(); - } - - /** - * Decides whether there were any errors during plugins loading and if there were any, then show a visual report - * about these errors. - */ - private void showLoadingErrors(){ - final List errors = ModelerSession.getNotationService().getErrors(); - - if(errors == null){ - LOG.error("Nullary loading error info."); - return; - } - - if(!errors.isEmpty()){ - new LoadErrorsDialog(errors); - } - } - - /** - * Installs the notations ad modules. - * - * @param notationSpecificPlugins is the holder of notations and it's modules - */ - private void installNotationsAndModules(final NotationSpecificPlugins notationSpecificPlugins ){ - final NotationGuiHolder notationGuiHolder = new NotationGuiHolder( - notationSpecificPlugins.getNotation().getIdentifier(), - dockingManager - ); - - model.addNotationGuiHolder(notationGuiHolder); - - final Collection dockableFramesData = notationSpecificPlugins.getDockableFramesData(); - - if( dockableFramesData != null ){ - for( final DockableFrameData item : dockableFramesData ){ - - final DockableFrame frame = createDockableFrame( - item.getDockableFrameComponent(), - item.getInitialPosition(), - item.getDockableFrameTitle(), - item.isMaximizable(), - item.getInitialState()); - - final JMenu menu = ModelerSession.getComponentFactoryService().createMenu( - ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move")); - - final JMenuItem moveToLeftMenuItem = ModelerSession.getComponentFactoryService().createMenuItem( - ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move.left")); - moveToLeftMenuItem.addActionListener(new MenuItemMoveListener(notationGuiHolder, frame, NotationGuiHolder.Position.LEFT)); - - final JMenuItem moveToRightMenuItem = ModelerSession.getComponentFactoryService().createMenuItem( - ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move.right")); - moveToRightMenuItem.addActionListener(new MenuItemMoveListener(notationGuiHolder, frame, NotationGuiHolder.Position.RIGHT)); - - final JMenuItem moveToTopMenuItem = ModelerSession.getComponentFactoryService().createMenuItem( - ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move.top")); - moveToTopMenuItem.addActionListener(new MenuItemMoveListener(notationGuiHolder, frame, NotationGuiHolder.Position.TOP)); - - final JMenuItem moveToBottomMenuItem = ModelerSession.getComponentFactoryService().createMenuItem( - ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move.bottom")); - moveToBottomMenuItem.addActionListener(new MenuItemMoveListener(notationGuiHolder, frame, NotationGuiHolder.Position.BOTTOM)); - - final JPopupMenu popupMenu = ModelerSession.getComponentFactoryService().createPopupMenu(); - - if(item.getAllowedDockableFramePositions() != null){ - boolean insertMenu = false; - - for(final NotationGuiHolder.Position position : NotationGuiHolder.Position.values()){ - if(item.getAllowedDockableFramePositions().contains(position)){ - switch (position){ - case LEFT: - menu.add(moveToLeftMenuItem); - insertMenu = true; - break; - case RIGHT: - menu.add(moveToRightMenuItem); - insertMenu = true; - break; - case TOP: - menu.add(moveToTopMenuItem); - insertMenu = true; - break; - case BOTTOM: - menu.add(moveToBottomMenuItem); - insertMenu = true; - break; - default: - LOG.error("No such a choice for allowed position of dockable frame."); - } - } - } - - if(insertMenu){ - popupMenu.add(menu); - } - } - - final JideButton button; - switch (item.getInitialPosition()){ - case BOTTOM: - case TOP: - button = ModelerSession.getComponentFactoryService().createJideButton(item.getDockableFrameTitle(), - item.getButtonIcon(), - 0); - break; - default: - // case LEFT: - // case RIGHT: - button = ModelerSession.getComponentFactoryService().createJideButton(item.getDockableFrameTitle(), - item.getButtonIcon(), - 1); - } - - button.addActionListener(new SideButtonListener(notationGuiHolder, dockingManager, frame)); - button.addMouseListener(new ButtonPopupAdapter(button, popupMenu)); - - frame.addDockableFrameListener(new DockFrameListener(notationGuiHolder, dockingManager)); - - notationGuiHolder.addFrameWithButton( - frame, - button, - popupMenu, - moveToLeftMenuItem, - moveToRightMenuItem, - moveToBottomMenuItem, - moveToTopMenuItem, - item.getInitialPosition(), - item.getInitialState()); - } - } - - final String notationIdentifier = notationSpecificPlugins.getNotation().getIdentifier(); - - // insert notation workspace - if( notationSpecificPlugins.getNotation().getNotationWorkspaceData() != null ){ - notationGuiHolder.setNotationWorkspace(notationSpecificPlugins.getNotation().getNotationWorkspaceData()); - } else { - notationGuiHolder.setNotationWorkspace(new NotationWorkspaceDataDefault(notationIdentifier)); - - LOG.error("No workspace definition provided. Default panel has been inserted instead. " + - "Notation identifier: " + notationIdentifier); - } - - // insert notation specific tool bar - addToolBarPane(notationIdentifier, ModelerSession.getToolBarControlService().getCommandBar(notationIdentifier)); - - // insert notation specific status bar - addStatusBar(notationIdentifier, ModelerSession.getStatusBarControlService().getStatusBar(notationIdentifier)); - - deployWorkspace(notationIdentifier); - deployButtons(notationIdentifier); - } - - /** - * Installs the workspace component. - * - * @param notationIdentifier is the identifier of associated notation - */ - private void deployWorkspace( final String notationIdentifier ){ - final NotationWorkspaceData notationWorkspaceData = model.getNotationGuiHolder(notationIdentifier).getNotationWorkspace(); - - final JComponent workspaceComponent = notationWorkspaceData.getWorkspaceComponentSingleton(); - - if(!(workspaceComponent instanceof UpdatableWorkspaceComponent)){ - LOG.warn("The obtained workspace component for notation (" + notationIdentifier + ") doesn't implement the UpdatableWorkspaceComponent inytercae. " + - "Any methods of this interface won't be never invoked for this workspace component."); - } - - addMainWindowPane(notationIdentifier, workspaceComponent); - } - - /** - * Deploys buttons. - * - * @param notationIdentifier is the notation identifier. - */ - private void deployButtons( final String notationIdentifier ){ - final NotationGuiHolder spec = model.getNotationGuiHolder(notationIdentifier); - - addSidePane(notationIdentifier, rightSidePane, spec.getListOfButtons( - NotationGuiHolder.Position.RIGHT), true); - - addSidePane(notationIdentifier, leftSidePane, spec.getListOfButtons( - NotationGuiHolder.Position.LEFT), true); - - addSidePane(notationIdentifier, bottomSidePane, spec.getListOfButtons( - NotationGuiHolder.Position.BOTTOM), false); - - addSidePane(notationIdentifier, topSidePane, spec.getListOfButtons( - NotationGuiHolder.Position.TOP), false); - } - - /** - * Initializes the common settings dialog. - */ - public void initSettingsDialog() { - LOG.info("Initializing settings dialog."); - - for(final Notation notation : ModelerSession.getNotationService().getNotations()){ - final NotationSpecificPlugins notationSpecificPlugins = - ModelerSession.getNotationService().getNotationSpecificPlugins(notation.getIdentifier()); - - // init notation's settings screens - List pages = notationSpecificPlugins.getNotation().getSettingPages(); - - if(pages == null){ - LOG.info("Notation " + notation.getIdentifier() + " provides nullary setting pages list."); - pages = new LinkedList(); - } - - - pages.add(0, new BasicSettingPage(notation.getFullName())); - - final AbstractDialogPage parentPage = pages.get(0); - - installPagesParent(pages, parentPage); - - model.addSettingPages(pages); - - // init module's settings screens - for(final Module module : notationSpecificPlugins.getModules()){ - pages = module.getSettingPages(); - - if(pages != null){ - installPagesParent(pages, parentPage); - - model.addSettingPages(pages); - - } else { - LOG.info("Module " + module.getIdentifier() + " provides nullary setting pages list."); - } - } - } - - // init extension's settings screens - for(final Extension extension : ModelerSession.getExtensionService().getExtensions()){ - List pages = extension.getSettingPages(); - - if(pages == null){ - LOG.info("Extension " + extension.getIdentifier() + " provides nullary setting pages list."); - pages = new LinkedList(); - } - - - pages.add(0, new BasicSettingPage(extension.getName())); - - final AbstractDialogPage parentPage = pages.get(0); - - installPagesParent(pages, parentPage); - - model.addSettingPages(pages); - } - } - - /** - * Sets the proper parent to all settings pages. If the parent of the page is already set then nothing is changed. - * - * @param pages is the page - * @param parentDialogPage is the parent of the page - */ - private void installPagesParent(final List pages, final AbstractDialogPage parentDialogPage) { - if(pages.size() > 1){ - pages.get(1).setParentPage(parentDialogPage); - } - - for(final AbstractDialogPage page : pages){ - if(page.getParent() == null && page != parentDialogPage){ - page.setParentPage(parentDialogPage); - } - } - } - - /** - * Performs dockable frame moves. - */ - private class MenuItemMoveListener implements ActionListener{ - - private final NotationGuiHolder notationGuiHolder; - private final DockableFrame dockableFrame; - private final NotationGuiHolder.Position directionOfMovement; - - public MenuItemMoveListener( final NotationGuiHolder notationGuiHolder, - final DockableFrame correspondingFrame, - final NotationGuiHolder.Position directionOfMovement){ - this.notationGuiHolder = notationGuiHolder; - this.dockableFrame = correspondingFrame; - this.directionOfMovement = directionOfMovement; - } - - public void actionPerformed( ActionEvent e ){ - try{ - final String notationIdentifier = notationGuiHolder.getNotationIdentifier(); - final String dockableFrameName = dockableFrame.getName(); - - NotationGuiHolder.Position oldPosition = notationGuiHolder.getPosition(dockableFrameName); - - notationGuiHolder.moveButtonAndFrame(dockableFrameName, directionOfMovement); - - final JPanel oldPanel; - final CardLayout oldCardLayout; - boolean isVertical; - switch (oldPosition){ - case LEFT: - oldPanel = leftSidePane; - oldCardLayout = cardLayoutLeftSidePane; - isVertical = true; - break; - case RIGHT: - oldPanel = rightSidePane; - oldCardLayout = cardLayoutRightSidePane; - isVertical = true; - break; - case TOP: - oldPanel = topSidePane; - oldCardLayout = cardLayoutTopSidePane; - isVertical = false; - break; - case BOTTOM: - oldPanel = bottomSidePane; - oldCardLayout = cardLayoutBottomSidePane; - isVertical = false; - break; - default: - oldPanel = null; - isVertical = true; - oldCardLayout = null; - LOG.error("No such a position for dockable frame."); - } - - addSidePane(notationIdentifier, oldPanel, notationGuiHolder.getListOfButtons(oldPosition), isVertical); - oldCardLayout.show(oldPanel, notationIdentifier); - - - final JPanel newPanel; - final NotationGuiHolder.Position newPosition; - final CardLayout newCardLayout; - switch(directionOfMovement){ - case LEFT: - newPanel = leftSidePane; - newPosition = NotationGuiHolder.Position.LEFT; - isVertical = true; - newCardLayout = cardLayoutLeftSidePane; - break; - case RIGHT: - newPanel = rightSidePane; - newPosition = NotationGuiHolder.Position.RIGHT; - isVertical = true; - newCardLayout = cardLayoutRightSidePane; - break; - case BOTTOM: - newPanel = bottomSidePane; - newPosition = NotationGuiHolder.Position.BOTTOM; - isVertical = false; - newCardLayout = cardLayoutBottomSidePane; - break; - case TOP: - newPanel = topSidePane; - newPosition = NotationGuiHolder.Position.TOP; - isVertical = false; - newCardLayout = cardLayoutTopSidePane; - break; - default: - newPanel = null; - newPosition = null; - isVertical = true; - newCardLayout = null; - LOG.error("No such a position for dockable frame."); - } - - addSidePane(notationIdentifier, newPanel, notationGuiHolder.getListOfButtons(newPosition), isVertical); - newCardLayout.show(newPanel, notationIdentifier); - - } catch(IllegalArgumentException exception){ - LOG.error("Illegal position or unknown frame during low level navigation movement.", exception); - } - } - - } - -} +package cz.cvut.promod.gui; + +import com.jidesoft.dialog.AbstractDialogPage; +import com.jidesoft.docking.DockableFrame; +import com.jidesoft.swing.JideButton; +import cz.cvut.promod.actions.LoadDialogAction; +import cz.cvut.promod.gui.dialogs.loadErrors.LoadErrorsDialog; +import cz.cvut.promod.gui.dialogs.newProject.NewProjectDialog; +import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialog; +import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialogExecutor; +import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogDialog; +import cz.cvut.promod.gui.listeners.ButtonPopupAdapter; +import cz.cvut.promod.gui.listeners.DockFrameListener; +import cz.cvut.promod.gui.listeners.SideButtonListener; +import cz.cvut.promod.gui.settings.BasicSettingPage; +import cz.cvut.promod.gui.settings.SettingsDialog; +import cz.cvut.promod.gui.support.utils.DockableFrameWrapper; +import cz.cvut.promod.gui.support.utils.NotationGuiHolder; +import cz.cvut.promod.plugin.extension.Extension; +import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; +import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.NotationWorkspaceData; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.utils.NotationWorkspaceDataDefault; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.workspace.UpdatableWorkspaceComponent; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import cz.cvut.promod.services.menuService.MenuControlService; +import cz.cvut.promod.services.menuService.MenuService; +import cz.cvut.promod.services.menuService.utils.ModelerMenuItem; +import cz.cvut.promod.services.menuService.utils.MenuItemPosition; +import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; +import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; +import cz.cvut.promod.resources.Resources; +import org.apache.log4j.Logger; + +import javax.swing.*; +import javax.swing.tree.TreePath; +import java.awt.*; +import java.awt.event.*; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:09:42, 10.10.2009 + */ + +/** + * Basic class of the host application. + */ +public class Modeler extends ModelerView{ + + private static final Logger LOG = Logger.getLogger(Modeler.class); + + public static final String ACTION_NEW_PROJECT_DIALOG = "modeler.action.new.project"; + public static final String ACTION_EXIT = "modeler.action.exit"; + public static final String ACTION_PROJECT_LOAD = "modeler.action.project.load"; + public static final String ACTION_PROJECT_SAVE = "modeler.action.project.save"; + public static final String ACTION_SWITH_USER = "modeler.action.switch.user"; + public static final String ACTION_PROJECT_NAVIG_SHOW = "modeler.action.navigation"; + public static final String ACTION_SETTINGS_SHOW = "modeler.action.settings"; + public static final String ACTION_PLUGINS_OVERVIEW_SHOW = "modeler.action.plugins.overview"; + + public static final String LOAD_SYNC_TITLE_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.sync.title"); + public static final String LOAD_SYNC_MESSAGE_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.error.sync.message"); + public static final String USER_CHANGE_DIALOG_TITLE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.user.service"); + public static final String USER_CHANGE_DIALOG_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.user.name"); + public static final String OK_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.ok"); + public static final String YES_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.yes"); + public static final String NO_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.no"); + public static final String CANCEL_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.cancel"); + public static final String USER_CHANGE_DIALOG_INVALID_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.user.invalid.name"); + public static final String SAVE_ALL_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.exit.save.all"); + public static final String SKIP_ALL_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.exit.skip.all"); + public static final String PROMOD_EXIT_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.exit"); + public static final String UNSAVED_CHANGE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.exit.diagram.unsaved.change"); + public static final String SETTINGS_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.settings"); + public static final String FILE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.menu.file"); + public static final String PROJECT_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.menu.project"); + public static final String EDIT_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.menu.edit"); + public static final String WINDOW_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.menu.window"); + public static final String PLUGINS_OVERVIEW_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview"); + + public static final Object[] EXIT_DIALOG_OPTIONS = { + YES_LABEL,NO_LABEL, SAVE_ALL_LABEL, SKIP_ALL_LABEL, CANCEL_LABEL}; + + public static enum ExitDialogReturnValues {CONTINUE, STOP, CANCEL} + + private final ModelerModel model; + + + public Modeler( ){ + ModelerSession.setFrame(this); + + this.model = new ModelerModel(); + + initActions(); + + initMainMenu(); + + initProjectNavigation(); + + initEventHandling(); + } + + /** + * Initialize actions that belong to the 'virtual' "modeler" notation. + */ + private void initActions(){ + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_PLUGINS_OVERVIEW_SHOW, + new ProModAction(PLUGINS_OVERVIEW_LABEL, null, KeyStroke.getKeyStroke( + KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ + public void actionPerformed(ActionEvent event) { + new PluginsOverviewDialogDialog(); + } + } + ); + + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_PLUGINS_OVERVIEW_SHOW, + new ProModAction(PLUGINS_OVERVIEW_LABEL, null, KeyStroke.getKeyStroke( + KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ + public void actionPerformed(ActionEvent event) { + new PluginsOverviewDialogDialog(); + } + } + ); + + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_SETTINGS_SHOW, + new ProModAction(SETTINGS_LABEL, null, KeyStroke.getKeyStroke( + KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ + public void actionPerformed(ActionEvent event) { + SettingsDialog.showOptionsDialog(model.getSettingPagesModel()); + } + } + ); + + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_SWITH_USER, + new ProModAction(USER_CHANGE_DIALOG_LABEL, null, null){ + public void actionPerformed(ActionEvent event) { + new SimpleTextFieldDialog( + USER_CHANGE_DIALOG_TITLE_LABEL, + USER_CHANGE_DIALOG_LABEL, + "", + OK_LABEL, + CANCEL_LABEL, + new SimpleTextFieldDialogExecutor(){ + public String execute(final String text) { + if(text != null && !text.isEmpty()){ + ModelerSession.getUserService().setUser(text); + return null; + } + + return USER_CHANGE_DIALOG_INVALID_LABEL; + } + }, + ModelerSession.getFrame(), + true + ); + } + }); + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_NEW_PROJECT_DIALOG, + new ProModAction(ModelerSession.getCommonResourceBundle().getString( + ACTION_NEW_PROJECT_DIALOG), + Resources.getIcon(Resources.MODELER + Resources.NEW_PROJECT_ICON), + KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)){ + public void actionPerformed(ActionEvent event) { + new NewProjectDialog(); + } + }); + + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_EXIT, + new ProModAction(ModelerSession.getCommonResourceBundle().getString(ACTION_EXIT), null, null){ + public void actionPerformed(ActionEvent event) { + modelerExit(); + } + }); + + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_PROJECT_NAVIG_SHOW, + new ProModAction(ModelerSession.getCommonResourceBundle().getString(ACTION_PROJECT_NAVIG_SHOW), null, null){ + public void actionPerformed(ActionEvent event) { + swapProjectNavigationVisibility(); + + // update control components selection + putValue(Action.SELECTED_KEY, projectNavigationDockableFrame.isAvailable()); + projectNavigatorButton.setSelected(projectNavigationDockableFrame.isAvailable()); + } + } + ); + + + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_PROJECT_SAVE, + new ProModAction(ModelerSession.getCommonResourceBundle().getString(ACTION_PROJECT_SAVE), + Resources.getIcon(Resources.MODELER + Resources.SAVE_ALL_ICON), + KeyStroke.getKeyStroke( + KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)){ + public void actionPerformed(ActionEvent event) { + LOG.debug("Action save invoked."); + + final TreePath projectTreePath = ModelerSession.getProjectService().getSelectedProjectPath(); + + if(projectTreePath == null){ + + } else { + final boolean syncResult = ModelerSession.getProjectControlService().synchronize( + projectTreePath, true, true, false, false); + + if (!syncResult){ + JOptionPane.showMessageDialog( + ModelerSession.getFrame(), + LOAD_SYNC_MESSAGE_ERROR_LABEL, + LOAD_SYNC_TITLE_ERROR_LABEL, + JOptionPane.ERROR_MESSAGE); + } + } + } + }); + + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_PROJECT_LOAD, + new LoadDialogAction(ModelerSession.getCommonResourceBundle().getString( + ACTION_PROJECT_LOAD), + Resources.getIcon(Resources.MODELER + Resources.OPEN_ICON), + KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK))); + } + + /** + * Changed the project navigation visibility. + */ + private void swapProjectNavigationVisibility(){ + if( projectNavigationDockableFrame.isAvailable() ){ + dockingManager.setFrameUnavailable(projectNavigationDockableFrame.getName()); + } else{ + final String currentNotation = ModelerSession.getProjectService().getSelectedProjectNotationIndentifier(); + + final NotationGuiHolder specification = model.getNotationGuiHolder(currentNotation); + + if( specification != null ){ + final List visibleDockableFrames = new LinkedList(); + + for( final DockableFrame dockableFrame : specification.getListOfFrames(NotationGuiHolder.Position.LEFT) ){ + if( dockableFrame.isAvailable() ){ + visibleDockableFrames.add((dockableFrame)); + specification.getButton(dockableFrame.getName(), NotationGuiHolder.Position.LEFT).doClick(); + } + } + + dockingManager.setFrameAvailable(projectNavigationDockableFrame.getName()); + + for( final DockableFrame dockableFrame : visibleDockableFrames ){ + specification.getButton(dockableFrame.getName(), NotationGuiHolder.Position.LEFT).doClick(); + } + } else{ + dockingManager.setFrameAvailable(projectNavigationDockableFrame.getName()); + } + } + } + + /** + * Performs the terminating sequence. + */ + private void modelerExit() { + LOG.info("Modeler is shutting down."); + + if(!checkForUnsavedChanges()){ + LOG.info("ProMod shut-down has been canceled by user"); + return; + } + + setVisible(false); + + // finishing notations & modules + for(final String notationIdentifier : ModelerSession.getNotationService().getNotationsIdentifiers()){ + final NotationSpecificPlugins notationSpecificPlugins = ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier); + + notationSpecificPlugins.getNotation().finish(); + + for(final Module module : notationSpecificPlugins.getModules()){ + module.finish(); + } + } + + // finishing extensions + for(Extension extension : ModelerSession.getExtensionService().getExtensions()){ + extension.finish(); + } + + dispose(); + System.exit(0); + } + + /** + * Looks for unsaved changes in projects. + * + * @return true if ProMod is supposed to be terminated, false if the ProMod termination has been canceled + */ + private boolean checkForUnsavedChanges() { + for(final TreePath projectTreePath : ModelerSession.getProjectService().getProjectPaths()){ + if(ExitDialogReturnValues.CANCEL.equals( + projectNavigationDockableFrame.checkForUnsavedChanges(projectTreePath, projectTreePath) + )){ + // ProMod termination has been canceled by user + return false; + } + } + + return true; + } + + /** + * Performs the context switching mechanism. + */ + private void updateView(){ + String newNotationIdentifier = ModelerSession.getProjectService().getSelectedProjectNotationIndentifier(); + final String oldNotationIdentifier = model.getSelectedNotation(); + + //if no diagram is selected, use default modeler view + if(newNotationIdentifier == null){ + newNotationIdentifier = ModelerModel.MODELER_IDENTIFIER; + } + + updateProjectDiagram(false); // order of over method invocation with respect to possible automatic sync. mechanisms + updateWorkspaceComponent(oldNotationIdentifier, false); + + if(!newNotationIdentifier.equals(oldNotationIdentifier)){ + updateModelerView(newNotationIdentifier); + ModelerSession.getActionControlService().updateActionsVisibility(newNotationIdentifier); + updateMainMenusVisibility(newNotationIdentifier); + updateDockableFramesVisibility(newNotationIdentifier, oldNotationIdentifier); + } + + updateWorkspaceComponent(newNotationIdentifier, true); // order of over method invocation with respect to possible automatic sync. mechanisms + updateProjectDiagram(true); + + model.setSelectedNotation(newNotationIdentifier); + } + + /** + * Updates the project diagram. + * + * @param update if true, update will be performed, otherwise over will be performed + */ + private void updateProjectDiagram(final boolean update) { + if(ModelerSession.getProjectService().getSelectedDiagram() != null){ + if(update){ + ModelerSession.getProjectService().getSelectedDiagram().getDiagramModel().update(); + } else { + ModelerSession.getProjectService().getSelectedDiagram().getDiagramModel().over(); + } + } + } + + /** + * Updates the main menu items visibility. + * + * @param newNotationIdentifier is the identifier of active notation + */ + private void updateMainMenusVisibility(final String newNotationIdentifier) { + final JMenuBar menuBar = getJMenuBar(); + + if(menuBar != null){ + + for(int i = 0; i < menuBar.getMenuCount(); i++){ + final JMenuItem menuItem = menuBar.getMenu(i); + boolean isVisible = updateMenuItemVisibility(menuItem, newNotationIdentifier); + + if(isVisible){ + menuItem.setEnabled(true); + } else { + menuItem.setEnabled(false); + } + } + + } + } + + /** + * Recursively goes through the menu structure and ensures that only items related to the currently selected notation + * will be enabled. + * + * @param parentMenuItem is the menu where the recursion begins + * @param newNotationIdentifier is the identifier of selected notation + * + * @return true if the parentMenuItem is supposed to be disabled, false otherwise + */ + private boolean updateMenuItemVisibility(final JMenuItem parentMenuItem, final String newNotationIdentifier) { + boolean isEnabled = false; + + parentMenuItem.setVisible(true); // always start with all items visible + + if(parentMenuItem instanceof JMenu){ + + final JMenu menu = (JMenu) parentMenuItem; + for(int i = 0; i < menu.getItemCount(); i++){ + final JMenuItem menuItem = menu.getItem(i); + + if(menuItem != null){ //separator is returned like a null item + isEnabled |= updateMenuItemVisibility(menuItem, newNotationIdentifier); + } + } + + menu.setEnabled(isEnabled); + return isEnabled; + } + + // menu item, hide relatives (menu items with the same text) + final boolean menuItemEnabled = parentMenuItem.isEnabled(); + + if(parentMenuItem instanceof ModelerMenuItem && !menuItemEnabled){ + final ModelerMenuItem menuItem = (ModelerMenuItem) parentMenuItem; + + final List relatives = menuItem.getListOfRelatives(); + if(relatives != null){ + if(relatives.isEmpty()){ + parentMenuItem.setVisible(false); + } else { + if(isAnotherRelativeVisible(relatives)){ + parentMenuItem.setVisible(false); + } + } + } + } + + return menuItemEnabled; + } + + /** + * Checks the list of relatives (relative are items in the menu under the same root with the same text on it) and + * decides whether this any of relative items is visible or not. + * + * @param relatives is the list of relative items + * @return true if any another relative item is visible, false otherwise + */ + private boolean isAnotherRelativeVisible(final List relatives) { + if(relatives == null || relatives.isEmpty()){ + return false; + } + + for(ModelerMenuItem modelerMenuItem : relatives){ + if(modelerMenuItem instanceof JMenuItem){ + final JMenuItem menuItem = (JMenuItem) modelerMenuItem; + if(menuItem.isEnabled()){ + return true; + } + } + } + + return false; + } + + /** + * Performs the context switch. + * + * @param newNotationIdentifier is the identifier of active notation. + */ + private void updateModelerView(final String newNotationIdentifier) { + if(newNotationIdentifier != null){ + cardLayoutLeftSidePane.show(leftSidePane, newNotationIdentifier); + cardLayoutRightSidePane.show(rightSidePane, newNotationIdentifier); + cardLayoutBottomSidePane.show(bottomSidePane, newNotationIdentifier); + cardLayoutTopSidePane.show(topSidePane, newNotationIdentifier); + + cardLayoutWorkspacePane.show(workspacePane, newNotationIdentifier); + + cardLayoutToolBar.show(toolBarPane, newNotationIdentifier); + + cardLayoutStatusBar.show(statusBarPane, newNotationIdentifier); + + } else { + LOG.error("Modeler view update error. Notation name cannot be null."); + } + } + + /** + * Performs the update() or ever() methods on workspace component if this component implements the + * UpdatableWorkspaceComponent interface. + * + * @param notationIdentifier is the identifier of the notation to which the workspace component belongs + * @param update is true when update() method is supposed to be invoked, the over() methods is invoked otherwise + */ + private void updateWorkspaceComponent(final String notationIdentifier, final boolean update) { + if(notationIdentifier != null && !ModelerModel.MODELER_IDENTIFIER.equals(notationIdentifier)){ + final JComponent workspaceComponent; + try{ + workspaceComponent = model.getNotationGuiHolder(notationIdentifier).getNotationWorkspace().getWorkspaceComponentSingleton(); + + if(workspaceComponent instanceof UpdatableWorkspaceComponent){ + final UpdatableWorkspaceComponent updatableWorkspaceComponent = (UpdatableWorkspaceComponent)workspaceComponent; + + if(update){ + updatableWorkspaceComponent.update(); + } else { + ModelerSession.clearFrameTitleText(); + updatableWorkspaceComponent.over(); + } + } + + } catch (NullPointerException exception){ + LOG.error("Not workspace provided, notationIdentifier: " + notationIdentifier); + } + } + } + + /** + * Updates the dockable frame visibility. + * + * @param newNotationIdentifier is the identifier of active notation + * @param oldNotationIdentifier is the identifier of previous notation. + */ + private void updateDockableFramesVisibility(final String newNotationIdentifier, final String oldNotationIdentifier) { + if(newNotationIdentifier == null || newNotationIdentifier.equals(oldNotationIdentifier)){ + // should never happened + LOG.debug("UpdateDockableFramesVisibility method has been invoked, even though newNotationIdentifier is the same as oldNotationIdentifier."); + } + + if(!ModelerModel.MODELER_IDENTIFIER.equals(oldNotationIdentifier) && oldNotationIdentifier != null){ + model.getNotationGuiHolder(oldNotationIdentifier).unable(); + } + + if(!ModelerModel.MODELER_IDENTIFIER.equals(newNotationIdentifier)){ + model.getNotationGuiHolder(newNotationIdentifier).enable(); + } + } + + /** + * Initialize main menu. + */ + private void initMainMenu() { + final MenuControlService mainMenuControlService; + try{ + mainMenuControlService = (MenuControlService) ModelerSession.getMenuService(); + } catch(ClassCastException exception){ + LOG.error("Main menu initialization not possible.", exception); + return; + } + + setJMenuBar(mainMenuControlService.getMenuBar()); + + // insert common menu items + // 'file' menu + ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_EXIT), + new MenuItemPosition(FILE_LABEL), MenuService.MenuSeparator.BEFORE + ); + + // 'project' menu + ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_NEW_PROJECT_DIALOG), + new MenuItemPosition(PROJECT_LABEL, MenuItemPosition.PlacementStyle.FIRST) + ); + + ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_PROJECT_SAVE), + new MenuItemPosition(PROJECT_LABEL), MenuService.MenuSeparator.BEFORE + ); + ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_PROJECT_LOAD), + new MenuItemPosition(PROJECT_LABEL) + ); + + // 'edit' Menu + ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_SETTINGS_SHOW), + new MenuItemPosition(EDIT_LABEL) + ); + + // 'window' menu + ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_PROJECT_NAVIG_SHOW), + new MenuItemPosition(WINDOW_LABEL), true + ); + ModelerSession.getMenuService().insertMainMenuItem(ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_PLUGINS_OVERVIEW_SHOW), + new MenuItemPosition(WINDOW_LABEL) + ); + } + + /** + * Initialize the event handling. + */ + private void initEventHandling(){ + ModelerSession.getUserService().getUserValueModel().addValueChangeListener( + new PropertyChangeListener(){ + public void propertyChange(PropertyChangeEvent evt) { + loggedUserLabel.setText(ModelerSession.getUserService().getUser()); + } + } + ); + + switchUserButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_SWITH_USER).actionPerformed(null); + } + }); + + ModelerSession.getProjectService().getSelectedItem().addValueChangeListener(new PropertyChangeListener(){ + public void propertyChange(PropertyChangeEvent evt) { + updateView(); + } + }); + + // listener of window's closing button (cross button) + this.addWindowListener(new WindowAdapter(){ + @Override + public void windowClosing(WindowEvent e){ + + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_EXIT).actionPerformed(null); + } + }); + + projectNavigatorButton.addActionListener(ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_PROJECT_NAVIG_SHOW)); + } + + /** + * Installs the plugins into the gui. + */ + public void deployNotationSpecificPlugIns( ){ + for(final String notationIdentifier : ModelerSession.getNotationService().getNotationsIdentifiers()){ + final NotationSpecificPlugins notationSpecificPlugins = ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier); + + installNotationsAndModules(notationSpecificPlugins); + } + } + + /** + * Shows the application frame window. + */ + public void showFrame(){ + // update view to initial state + updateView(); + + dockingManager.loadLayoutData(); + + dockingManager.setFrameUnavailable(projectNavigationDockableFrame.getName()); + + for( final NotationGuiHolder notationGuiHolder : model.getNotationGuiHolders() ){ + for( final DockableFrameWrapper wrapper : notationGuiHolder.getAllDockableFrameFacades() ){ + dockingManager.setFrameAvailable(wrapper.getDockableFrame().getName()); + dockingManager.setFrameUnavailable(wrapper.getDockableFrame().getName()); + } + } + + setVisible(true); + + projectNavigatorButton.doClick(); + + showLoadingErrors(); + } + + /** + * Decides whether there were any errors during plugins loading and if there were any, then show a visual report + * about these errors. + */ + private void showLoadingErrors(){ + final List errors = ModelerSession.getNotationService().getErrors(); + + if(errors == null){ + LOG.error("Nullary loading error info."); + return; + } + + if(!errors.isEmpty()){ + new LoadErrorsDialog(errors); + } + } + + /** + * Installs the notations ad modules. + * + * @param notationSpecificPlugins is the holder of notations and it's modules + */ + private void installNotationsAndModules(final NotationSpecificPlugins notationSpecificPlugins ){ + final NotationGuiHolder notationGuiHolder = new NotationGuiHolder( + notationSpecificPlugins.getNotation().getIdentifier(), + dockingManager + ); + + model.addNotationGuiHolder(notationGuiHolder); + + final Collection dockableFramesData = notationSpecificPlugins.getDockableFramesData(); + + if( dockableFramesData != null ){ + for( final DockableFrameData item : dockableFramesData ){ + + final DockableFrame frame = createDockableFrame( + item.getDockableFrameComponent(), + item.getInitialPosition(), + item.getDockableFrameTitle(), + item.isMaximizable(), + item.getInitialState()); + + final JMenu menu = ModelerSession.getComponentFactoryService().createMenu( + ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move")); + + final JMenuItem moveToLeftMenuItem = ModelerSession.getComponentFactoryService().createMenuItem( + ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move.left")); + moveToLeftMenuItem.addActionListener(new MenuItemMoveListener(notationGuiHolder, frame, NotationGuiHolder.Position.LEFT)); + + final JMenuItem moveToRightMenuItem = ModelerSession.getComponentFactoryService().createMenuItem( + ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move.right")); + moveToRightMenuItem.addActionListener(new MenuItemMoveListener(notationGuiHolder, frame, NotationGuiHolder.Position.RIGHT)); + + final JMenuItem moveToTopMenuItem = ModelerSession.getComponentFactoryService().createMenuItem( + ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move.top")); + moveToTopMenuItem.addActionListener(new MenuItemMoveListener(notationGuiHolder, frame, NotationGuiHolder.Position.TOP)); + + final JMenuItem moveToBottomMenuItem = ModelerSession.getComponentFactoryService().createMenuItem( + ModelerSession.getCommonResourceBundle().getString("modeler.dockable.frame.move.bottom")); + moveToBottomMenuItem.addActionListener(new MenuItemMoveListener(notationGuiHolder, frame, NotationGuiHolder.Position.BOTTOM)); + + final JPopupMenu popupMenu = ModelerSession.getComponentFactoryService().createPopupMenu(); + + if(item.getAllowedDockableFramePositions() != null){ + boolean insertMenu = false; + + for(final NotationGuiHolder.Position position : NotationGuiHolder.Position.values()){ + if(item.getAllowedDockableFramePositions().contains(position)){ + switch (position){ + case LEFT: + menu.add(moveToLeftMenuItem); + insertMenu = true; + break; + case RIGHT: + menu.add(moveToRightMenuItem); + insertMenu = true; + break; + case TOP: + menu.add(moveToTopMenuItem); + insertMenu = true; + break; + case BOTTOM: + menu.add(moveToBottomMenuItem); + insertMenu = true; + break; + default: + LOG.error("No such a choice for allowed position of dockable frame."); + } + } + } + + if(insertMenu){ + popupMenu.add(menu); + } + } + + final JideButton button; + switch (item.getInitialPosition()){ + case BOTTOM: + case TOP: + button = ModelerSession.getComponentFactoryService().createJideButton(item.getDockableFrameTitle(), + item.getButtonIcon(), + 0); + break; + default: + // case LEFT: + // case RIGHT: + button = ModelerSession.getComponentFactoryService().createJideButton(item.getDockableFrameTitle(), + item.getButtonIcon(), + 1); + } + + button.addActionListener(new SideButtonListener(notationGuiHolder, dockingManager, frame)); + button.addMouseListener(new ButtonPopupAdapter(button, popupMenu)); + + frame.addDockableFrameListener(new DockFrameListener(notationGuiHolder, dockingManager)); + + notationGuiHolder.addFrameWithButton( + frame, + button, + popupMenu, + moveToLeftMenuItem, + moveToRightMenuItem, + moveToBottomMenuItem, + moveToTopMenuItem, + item.getInitialPosition(), + item.getInitialState()); + } + } + + final String notationIdentifier = notationSpecificPlugins.getNotation().getIdentifier(); + + // insert notation workspace + if( notationSpecificPlugins.getNotation().getNotationWorkspaceData() != null ){ + notationGuiHolder.setNotationWorkspace(notationSpecificPlugins.getNotation().getNotationWorkspaceData()); + } else { + notationGuiHolder.setNotationWorkspace(new NotationWorkspaceDataDefault(notationIdentifier)); + + LOG.error("No workspace definition provided. Default panel has been inserted instead. " + + "Notation identifier: " + notationIdentifier); + } + + // insert notation specific tool bar + addToolBarPane(notationIdentifier, ModelerSession.getToolBarControlService().getCommandBar(notationIdentifier)); + + // insert notation specific status bar + addStatusBar(notationIdentifier, ModelerSession.getStatusBarControlService().getStatusBar(notationIdentifier)); + + deployWorkspace(notationIdentifier); + deployButtons(notationIdentifier); + } + + /** + * Installs the workspace component. + * + * @param notationIdentifier is the identifier of associated notation + */ + private void deployWorkspace( final String notationIdentifier ){ + final NotationWorkspaceData notationWorkspaceData = model.getNotationGuiHolder(notationIdentifier).getNotationWorkspace(); + + final JComponent workspaceComponent = notationWorkspaceData.getWorkspaceComponentSingleton(); + + if(!(workspaceComponent instanceof UpdatableWorkspaceComponent)){ + LOG.warn("The obtained workspace component for notation (" + notationIdentifier + ") doesn't implement the UpdatableWorkspaceComponent inytercae. " + + "Any methods of this interface won't be never invoked for this workspace component."); + } + + addMainWindowPane(notationIdentifier, workspaceComponent); + } + + /** + * Deploys buttons. + * + * @param notationIdentifier is the notation identifier. + */ + private void deployButtons( final String notationIdentifier ){ + final NotationGuiHolder spec = model.getNotationGuiHolder(notationIdentifier); + + addSidePane(notationIdentifier, rightSidePane, spec.getListOfButtons( + NotationGuiHolder.Position.RIGHT), true); + + addSidePane(notationIdentifier, leftSidePane, spec.getListOfButtons( + NotationGuiHolder.Position.LEFT), true); + + addSidePane(notationIdentifier, bottomSidePane, spec.getListOfButtons( + NotationGuiHolder.Position.BOTTOM), false); + + addSidePane(notationIdentifier, topSidePane, spec.getListOfButtons( + NotationGuiHolder.Position.TOP), false); + } + + /** + * Initializes the common settings dialog. + */ + public void initSettingsDialog() { + LOG.info("Initializing settings dialog."); + + for(final Notation notation : ModelerSession.getNotationService().getNotations()){ + final NotationSpecificPlugins notationSpecificPlugins = + ModelerSession.getNotationService().getNotationSpecificPlugins(notation.getIdentifier()); + + // init notation's settings screens + List pages = notationSpecificPlugins.getNotation().getSettingPages(); + + if(pages == null){ + LOG.info("Notation " + notation.getIdentifier() + " provides nullary setting pages list."); + pages = new LinkedList(); + } + + + pages.add(0, new BasicSettingPage(notation.getFullName())); + + final AbstractDialogPage parentPage = pages.get(0); + + installPagesParent(pages, parentPage); + + model.addSettingPages(pages); + + // init module's settings screens + for(final Module module : notationSpecificPlugins.getModules()){ + pages = module.getSettingPages(); + + if(pages != null){ + installPagesParent(pages, parentPage); + + model.addSettingPages(pages); + + } else { + LOG.info("Module " + module.getIdentifier() + " provides nullary setting pages list."); + } + } + } + + // init extension's settings screens + for(final Extension extension : ModelerSession.getExtensionService().getExtensions()){ + List pages = extension.getSettingPages(); + + if(pages == null){ + LOG.info("Extension " + extension.getIdentifier() + " provides nullary setting pages list."); + pages = new LinkedList(); + } + + + pages.add(0, new BasicSettingPage(extension.getName())); + + final AbstractDialogPage parentPage = pages.get(0); + + installPagesParent(pages, parentPage); + + model.addSettingPages(pages); + } + } + + /** + * Sets the proper parent to all settings pages. If the parent of the page is already set then nothing is changed. + * + * @param pages is the page + * @param parentDialogPage is the parent of the page + */ + private void installPagesParent(final List pages, final AbstractDialogPage parentDialogPage) { + if(pages.size() > 1){ + pages.get(1).setParentPage(parentDialogPage); + } + + for(final AbstractDialogPage page : pages){ + if(page.getParent() == null && page != parentDialogPage){ + page.setParentPage(parentDialogPage); + } + } + } + + /** + * Performs dockable frame moves. + */ + private class MenuItemMoveListener implements ActionListener{ + + private final NotationGuiHolder notationGuiHolder; + private final DockableFrame dockableFrame; + private final NotationGuiHolder.Position directionOfMovement; + + public MenuItemMoveListener( final NotationGuiHolder notationGuiHolder, + final DockableFrame correspondingFrame, + final NotationGuiHolder.Position directionOfMovement){ + this.notationGuiHolder = notationGuiHolder; + this.dockableFrame = correspondingFrame; + this.directionOfMovement = directionOfMovement; + } + + public void actionPerformed( ActionEvent e ){ + try{ + final String notationIdentifier = notationGuiHolder.getNotationIdentifier(); + final String dockableFrameName = dockableFrame.getName(); + + NotationGuiHolder.Position oldPosition = notationGuiHolder.getPosition(dockableFrameName); + + notationGuiHolder.moveButtonAndFrame(dockableFrameName, directionOfMovement); + + final JPanel oldPanel; + final CardLayout oldCardLayout; + boolean isVertical; + switch (oldPosition){ + case LEFT: + oldPanel = leftSidePane; + oldCardLayout = cardLayoutLeftSidePane; + isVertical = true; + break; + case RIGHT: + oldPanel = rightSidePane; + oldCardLayout = cardLayoutRightSidePane; + isVertical = true; + break; + case TOP: + oldPanel = topSidePane; + oldCardLayout = cardLayoutTopSidePane; + isVertical = false; + break; + case BOTTOM: + oldPanel = bottomSidePane; + oldCardLayout = cardLayoutBottomSidePane; + isVertical = false; + break; + default: + oldPanel = null; + isVertical = true; + oldCardLayout = null; + LOG.error("No such a position for dockable frame."); + } + + addSidePane(notationIdentifier, oldPanel, notationGuiHolder.getListOfButtons(oldPosition), isVertical); + oldCardLayout.show(oldPanel, notationIdentifier); + + + final JPanel newPanel; + final NotationGuiHolder.Position newPosition; + final CardLayout newCardLayout; + switch(directionOfMovement){ + case LEFT: + newPanel = leftSidePane; + newPosition = NotationGuiHolder.Position.LEFT; + isVertical = true; + newCardLayout = cardLayoutLeftSidePane; + break; + case RIGHT: + newPanel = rightSidePane; + newPosition = NotationGuiHolder.Position.RIGHT; + isVertical = true; + newCardLayout = cardLayoutRightSidePane; + break; + case BOTTOM: + newPanel = bottomSidePane; + newPosition = NotationGuiHolder.Position.BOTTOM; + isVertical = false; + newCardLayout = cardLayoutBottomSidePane; + break; + case TOP: + newPanel = topSidePane; + newPosition = NotationGuiHolder.Position.TOP; + isVertical = false; + newCardLayout = cardLayoutTopSidePane; + break; + default: + newPanel = null; + newPosition = null; + isVertical = true; + newCardLayout = null; + LOG.error("No such a position for dockable frame."); + } + + addSidePane(notationIdentifier, newPanel, notationGuiHolder.getListOfButtons(newPosition), isVertical); + newCardLayout.show(newPanel, notationIdentifier); + + } catch(IllegalArgumentException exception){ + LOG.error("Illegal position or unknown frame during low level navigation movement.", exception); + } + } + + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/ModelerModel.java b/IndependentModeler/src/cz/cvut/promod/gui/ModelerModel.java index 802b605..e57f617 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/ModelerModel.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/ModelerModel.java @@ -1,88 +1,88 @@ -package cz.cvut.promod.gui; - -import cz.cvut.promod.gui.support.utils.NotationGuiHolder; - -import java.util.Collection; -import java.util.Map; -import java.util.HashMap; -import java.util.List; - -import com.jidesoft.dialog.AbstractDialogPage; -import com.jidesoft.dialog.PageList; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:09:51, 10.10.2009 - */ - -/** - * Data holder for the Modeler class. - */ -public class ModelerModel { - - public static final String APPLICATION_NAME = "ProMod"; - - public static final String MODELER_IDENTIFIER = "modeler"; - - private String selectedNotation = null; //must be null due to initial view update invoked by Modeler class constructor - - private Map notationGuiHolders = new HashMap(); - - private final PageList settingPagesModel = new PageList(); - - /** - * @return NotationGuiHolder collection - */ - public Collection getNotationGuiHolders(){ - return notationGuiHolders.values(); - } - - /** - * @param notationIdentifier is the notation identifier - * @return required NotationGuiHolder - */ - public NotationGuiHolder getNotationGuiHolder( final String notationIdentifier ){ - return notationGuiHolders.get(notationIdentifier); - } - - /** - * Adds a new NotationGuiHolder. - * @param notationGuiHolder is the new NotationGuiHolder - */ - public void addNotationGuiHolder( final NotationGuiHolder notationGuiHolder){ - notationGuiHolders.put(notationGuiHolder.getNotationIdentifier(), notationGuiHolder); - } - - /** - * @return selected notation identifier - */ - public String getSelectedNotation() { - return selectedNotation; - } - - /** - * Sets selected notation identifier - * @param selectedNotation newly selected identifier - */ - public void setSelectedNotation(final String selectedNotation) { - this.selectedNotation = selectedNotation; - } - - /** - * Adds settings pages to the common settings dialog. - * @param pages are the pages to be added - */ - public void addSettingPages(final List pages) { - for(final AbstractDialogPage page : pages){ - settingPagesModel.append(page); - } - } - - /** - * @return returns the model holding all settings pages - */ - public PageList getSettingPagesModel() { - return settingPagesModel; - } -} +package cz.cvut.promod.gui; + +import cz.cvut.promod.gui.support.utils.NotationGuiHolder; + +import java.util.Collection; +import java.util.Map; +import java.util.HashMap; +import java.util.List; + +import com.jidesoft.dialog.AbstractDialogPage; +import com.jidesoft.dialog.PageList; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:09:51, 10.10.2009 + */ + +/** + * Data holder for the Modeler class. + */ +public class ModelerModel { + + public static final String APPLICATION_NAME = "ProMod"; + + public static final String MODELER_IDENTIFIER = "modeler"; + + private String selectedNotation = null; //must be null due to initial view update invoked by Modeler class constructor + + private Map notationGuiHolders = new HashMap(); + + private final PageList settingPagesModel = new PageList(); + + /** + * @return NotationGuiHolder collection + */ + public Collection getNotationGuiHolders(){ + return notationGuiHolders.values(); + } + + /** + * @param notationIdentifier is the notation identifier + * @return required NotationGuiHolder + */ + public NotationGuiHolder getNotationGuiHolder( final String notationIdentifier ){ + return notationGuiHolders.get(notationIdentifier); + } + + /** + * Adds a new NotationGuiHolder. + * @param notationGuiHolder is the new NotationGuiHolder + */ + public void addNotationGuiHolder( final NotationGuiHolder notationGuiHolder){ + notationGuiHolders.put(notationGuiHolder.getNotationIdentifier(), notationGuiHolder); + } + + /** + * @return selected notation identifier + */ + public String getSelectedNotation() { + return selectedNotation; + } + + /** + * Sets selected notation identifier + * @param selectedNotation newly selected identifier + */ + public void setSelectedNotation(final String selectedNotation) { + this.selectedNotation = selectedNotation; + } + + /** + * Adds settings pages to the common settings dialog. + * @param pages are the pages to be added + */ + public void addSettingPages(final List pages) { + for(final AbstractDialogPage page : pages){ + settingPagesModel.append(page); + } + } + + /** + * @return returns the model holding all settings pages + */ + public PageList getSettingPagesModel() { + return settingPagesModel; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/ModelerView.java b/IndependentModeler/src/cz/cvut/promod/gui/ModelerView.java index 27b9c08..de698b2 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/ModelerView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/ModelerView.java @@ -1,334 +1,334 @@ -package cz.cvut.promod.gui; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.gui.projectNavigation.ProjectNavigation; -import cz.cvut.promod.gui.support.utils.NotationGuiHolder; -import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; - -import com.jidesoft.docking.*; -import com.jidesoft.swing.JideTabbedPane; -import com.jidesoft.swing.JideButton; -import com.jidesoft.swing.JideBoxLayout; -import com.jidesoft.action.CommandBar; -import com.jidesoft.status.StatusBar; -import com.jidesoft.status.LabelStatusBarItem; -import com.jidesoft.status.ButtonStatusBarItem; -import com.jgoodies.forms.factories.Borders; - -import javax.swing.*; -import java.util.List; -import java.awt.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:10:00, 10.10.2009 - */ - -/** - * GUI definition for the Modeler class. - */ -public class ModelerView extends JFrame { - - /** Dimension for layout of side buttons. */ - private final Dimension BOX_VERTICAL_GAP = new Dimension(0, 5); - private final Dimension BOX_HORIZONTAL_GAP = new Dimension(5, 0); - - /** NO other DockableFrame is allowed to have this index */ - private static final int PROJECT_NAVIGATION_INDEX = 0; - - /** Each instance of DockableFrame is supposed to have unique index. */ - public static int dockingFrameCounter = PROJECT_NAVIGATION_INDEX + 1; - - /** Represents the dockable frame ID counter. */ - private static int dockableFrameIDcounter = 1; - - protected ProjectNavigation projectNavigationDockableFrame; - - protected DefaultDockingManager dockingManager; - - private JPanel dockableArea; - - protected final CardLayout cardLayoutRightSidePane = new CardLayout(); - protected final JPanel rightSidePane = new JPanel(cardLayoutRightSidePane); - - private final JPanel leftSideBottomLayerPane = new JPanel(new BorderLayout()); - protected final JButton projectNavigatorButton = ModelerSession.getComponentFactoryService().createJideButton( - ModelerSession.getCommonResourceBundle().getString("modeler.action.navigation"), null, 1); - - protected final CardLayout cardLayoutLeftSidePane = new CardLayout(); - protected final JPanel leftSidePane = new JPanel(cardLayoutLeftSidePane); - - protected final CardLayout cardLayoutBottomSidePane = new CardLayout(); - protected final JPanel bottomSidePane = new JPanel(cardLayoutBottomSidePane); - - protected final CardLayout cardLayoutTopSidePane = new CardLayout(); - protected final JPanel topSidePane = new JPanel(cardLayoutTopSidePane); - - protected final CardLayout cardLayoutWorkspacePane = new CardLayout(); - protected final JPanel workspacePane = new JPanel(cardLayoutWorkspacePane); - - private Workspace workspace; - - protected final StatusBar statusBar = ModelerSession.getComponentFactoryService().createStatusBar(); - protected final LabelStatusBarItem statusUserTitleLabel = ModelerSession.getComponentFactoryService().createLabelStatusBarItem(); - protected final LabelStatusBarItem loggedUserLabel = ModelerSession.getComponentFactoryService().createLabelStatusBarItem(); - protected final ButtonStatusBarItem switchUserButton = ModelerSession.getComponentFactoryService().createButtonStatusBarItem(); - - protected final CardLayout cardLayoutToolBar = new CardLayout(); - protected final JPanel toolBarPane = new JPanel(cardLayoutToolBar); - - private static final Dimension DEFAULT_SIZE = new Dimension(1024, 768); - - private static final Dimension DEFAULT_SIZE_LOW_LEVEL = new Dimension(300, 500); - - private static final Dimension DEFAULT_SIZE_CONSOLE = new Dimension(500, 200); - - private static final Point DEFAULT_UNDOCKED_FRAME_POSITION = new Point(-1, -1); - - private static final String USER_TITLE_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.user.title"); - private static final String USER_SWITCH_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.user.switch"); - - protected final CardLayout cardLayoutStatusBar = new CardLayout(); - protected final JPanel statusBarPane = new JPanel(cardLayoutStatusBar); - - - public ModelerView(){ - setTitle(ModelerModel.APPLICATION_NAME); - - initializeDockingManager(); - - initLayout(); - - initStatusBar(); - - setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - setPreferredSize(DEFAULT_SIZE); - setSize(DEFAULT_SIZE); - setLocationRelativeTo(null); - } - - /** - * Initialize status bar items. - */ - private void initStatusBar() { - statusUserTitleLabel.setAlignment(JLabel.LEFT); - statusUserTitleLabel.setText(USER_TITLE_LABEL); - statusBar.add(statusUserTitleLabel, JideBoxLayout.FIX); - - loggedUserLabel.setAlignment(JLabel.LEFT); - loggedUserLabel.setText(ModelerSession.getUserService().getUser()); - statusBar.add(loggedUserLabel, JideBoxLayout.FIX); - - switchUserButton.setText(USER_SWITCH_LABEL); - statusBar.add(switchUserButton, JideBoxLayout.FIX); - - statusBar.add(statusBarPane, JideBoxLayout.VARY); - } - - private void initLayout(){ - workspace.add(workspacePane); // add panel with CardLayout on the workspace - - final JPanel basisPanel = ModelerSession.getComponentFactoryService().createPanel(); - basisPanel.setLayout(new BorderLayout()); - - basisPanel.add(dockableArea, BorderLayout.CENTER); - basisPanel.add(rightSidePane, BorderLayout.EAST); - basisPanel.add(leftSideBottomLayerPane, BorderLayout.WEST); - basisPanel.add(topSidePane, BorderLayout.NORTH); - basisPanel.add(bottomSidePane, BorderLayout.SOUTH); - - add(basisPanel, BorderLayout.CENTER); - add(toolBarPane, BorderLayout.PAGE_START); - add(statusBar, BorderLayout.PAGE_END); - - //init high level navigation hide/show button - leftSideBottomLayerPane.add(leftSidePane, BorderLayout.CENTER); - - final JPanel panelProjectNavigationButton = new JPanel(new BorderLayout()); - panelProjectNavigationButton.setBorder(Borders.DLU2_BORDER); - panelProjectNavigationButton.setOpaque(false); - panelProjectNavigationButton.add(projectNavigatorButton, BorderLayout.CENTER); - - leftSideBottomLayerPane.add(panelProjectNavigationButton, BorderLayout.NORTH); - - //ads empty panels to all of card layouts with special key defined by ModelerModel.MODELER_IDENTIFIER - initEmptyModelerView(); - } - - /** - * Initialize buttons panels, workspace and tool bar that are visible if no notation is selected. - */ - private void initEmptyModelerView() { - rightSidePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); - leftSidePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); - bottomSidePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); - topSidePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); - - workspacePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); - - toolBarPane.add(ModelerSession.getToolBarControlService().getCommandBar(ModelerModel.MODELER_IDENTIFIER), ModelerModel.MODELER_IDENTIFIER); - statusBarPane.add(ModelerSession.getStatusBarControlService().getStatusBar(ModelerModel.MODELER_IDENTIFIER), ModelerModel.MODELER_IDENTIFIER); - } - - /** - * Initialization project navigation. - */ - protected void initProjectNavigation(){ - projectNavigationDockableFrame = new ProjectNavigation(PROJECT_NAVIGATION_INDEX); - dockingManager.addFrame(projectNavigationDockableFrame); - } - - private void initializeDockingManager(){ - dockableArea = new JPanel(); - - dockingManager = new DefaultDockingManager(this, dockableArea); - - workspace = dockingManager.getWorkspace(); - - dockingManager.setSideDockAllowed(false); - - dockingManager.setInitSplitPriority(DockingManager.SPLIT_EAST_WEST_SOUTH_NORTH); - - dockingManager.setTabbedPaneCustomizer(new - DockingManager.TabbedPaneCustomizer(){ - public void customize( JideTabbedPane tabbedPane ){ - tabbedPane.setHideOneTab(true); - } - }); - } - - /** - * Adds a new main windows to the workplace card layout. - * - * @param key is a key for the card layout - * @param component is the component to be displayed - */ - protected void addMainWindowPane( final String key, final Component component ){ - workspacePane.add(key, component); - } - - /** - * Adds a new tool bar to the tool bar card layout. - * - * @param notationIdentifier is a key for the card layout - * @param commandBar is the component to be displayed - */ - protected void addToolBarPane(final String notationIdentifier, final CommandBar commandBar){ - toolBarPane.add(commandBar, notationIdentifier); - } - - /** - * Adds a new status bar. - * - * @param notationIdentifier is a key for the card layout - * @param statusBar is the notation specific status bar - */ - protected void addStatusBar(final String notationIdentifier, final StatusBar statusBar){ - statusBarPane.add(statusBar, notationIdentifier); - } - - /** - * Adds a new side panel onto the specified base layer using CardLayout. - * - * @param key to be used by the CardLayout. - * @param baseLayer is base layer onto that should be the new panel added. - * @param buttonList is list of buttons to be shown on the new layer. - * @param isVertical true = vertical (for low level navigation), false = horizontal (consoles). - */ - protected void addSidePane( final String key, - final JPanel baseLayer, - final List buttonList, - final boolean isVertical ){ - final JPanel panel = new JPanel(); - panel.setBorder(Borders.DLU2_BORDER); - - final Dimension dimension; - if( isVertical ){ - panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); - dimension = BOX_VERTICAL_GAP; - } else{ - panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); - dimension = BOX_HORIZONTAL_GAP; - } - - for( JideButton but : buttonList ){ - panel.add(but); - panel.add(Box.createRigidArea(dimension)); - } - - baseLayer.add(panel, key); - } - - /** - * Creates the dockable frame. - * - * @param component is the component to be added on the dockable frame. - * @param position is the position specification. - * @param title is the dockable frame id - * @param isMaximizable true if the frame is supposed to be maximizable - * @param initialState is the initial state of the frame - * @return the instance of required dockable frame - */ - protected DockableFrame createDockableFrame(final JComponent component, - final NotationGuiHolder.Position position, - final String title, - final boolean isMaximizable, - final DockableFrameData.InitialState initialState){ - - final DockableFrame dockableFrame = new DockableFrame(String.valueOf(dockableFrameIDcounter++)); - dockableFrame.setTitle(title); - - dockableFrame.setShowContextMenu(false); - - if(DockableFrameData.InitialState.FLOATED.equals(initialState)){ - dockableFrame.getContext().setInitMode(DockContext.STATE_FLOATING); - } else { - dockableFrame.getContext().setInitMode(DockContext.STATE_FRAMEDOCKED); - } - - dockableFrame.getContext().setInitIndex(dockingFrameCounter++); - dockableFrame.setAutohidable(false); - dockableFrame.setDockable(true); - dockableFrame.setSideDockAllowed(false); - dockableFrame.setRearrangable(false); - dockableFrame.setTabDockAllowed(false); - - // make this dockable frame maximizable or not - int availableButtons = DockableFrame.BUTTON_FLOATING | DockableFrame.BUTTON_CLOSE; - if(isMaximizable){ - availableButtons |= DockableFrame.BUTTON_MAXIMIZE; - } - dockableFrame.setAvailableButtons(availableButtons); - - switch( position ){ - case RIGHT: - dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_EAST); - dockableFrame.setUndockedBounds(new Rectangle(DEFAULT_UNDOCKED_FRAME_POSITION, DEFAULT_SIZE_LOW_LEVEL)); - dockableFrame.setPreferredSize(DEFAULT_SIZE_LOW_LEVEL); - break; - case LEFT: - dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_WEST); - dockableFrame.setUndockedBounds(new Rectangle(DEFAULT_UNDOCKED_FRAME_POSITION, DEFAULT_SIZE_LOW_LEVEL)); - dockableFrame.setPreferredSize(DEFAULT_SIZE_LOW_LEVEL); - break; - case BOTTOM: - dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_SOUTH); - dockableFrame.setUndockedBounds(new Rectangle(DEFAULT_UNDOCKED_FRAME_POSITION, DEFAULT_SIZE_CONSOLE)); - dockableFrame.setPreferredSize(DEFAULT_SIZE_CONSOLE); - break; - case TOP: - dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_NORTH); - dockableFrame.setUndockedBounds(new Rectangle(DEFAULT_UNDOCKED_FRAME_POSITION, DEFAULT_SIZE_CONSOLE)); - dockableFrame.setPreferredSize(DEFAULT_SIZE_CONSOLE); - break; - default: - dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_WEST); - } - - dockableFrame.add(component); - - return dockableFrame; - } - -} +package cz.cvut.promod.gui; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.gui.projectNavigation.ProjectNavigation; +import cz.cvut.promod.gui.support.utils.NotationGuiHolder; +import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; + +import com.jidesoft.docking.*; +import com.jidesoft.swing.JideTabbedPane; +import com.jidesoft.swing.JideButton; +import com.jidesoft.swing.JideBoxLayout; +import com.jidesoft.action.CommandBar; +import com.jidesoft.status.StatusBar; +import com.jidesoft.status.LabelStatusBarItem; +import com.jidesoft.status.ButtonStatusBarItem; +import com.jgoodies.forms.factories.Borders; + +import javax.swing.*; +import java.util.List; +import java.awt.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:10:00, 10.10.2009 + */ + +/** + * GUI definition for the Modeler class. + */ +public class ModelerView extends JFrame { + + /** Dimension for layout of side buttons. */ + private final Dimension BOX_VERTICAL_GAP = new Dimension(0, 5); + private final Dimension BOX_HORIZONTAL_GAP = new Dimension(5, 0); + + /** NO other DockableFrame is allowed to have this index */ + private static final int PROJECT_NAVIGATION_INDEX = 0; + + /** Each instance of DockableFrame is supposed to have unique index. */ + public static int dockingFrameCounter = PROJECT_NAVIGATION_INDEX + 1; + + /** Represents the dockable frame ID counter. */ + private static int dockableFrameIDcounter = 1; + + protected ProjectNavigation projectNavigationDockableFrame; + + protected DefaultDockingManager dockingManager; + + private JPanel dockableArea; + + protected final CardLayout cardLayoutRightSidePane = new CardLayout(); + protected final JPanel rightSidePane = new JPanel(cardLayoutRightSidePane); + + private final JPanel leftSideBottomLayerPane = new JPanel(new BorderLayout()); + protected final JButton projectNavigatorButton = ModelerSession.getComponentFactoryService().createJideButton( + ModelerSession.getCommonResourceBundle().getString("modeler.action.navigation"), null, 1); + + protected final CardLayout cardLayoutLeftSidePane = new CardLayout(); + protected final JPanel leftSidePane = new JPanel(cardLayoutLeftSidePane); + + protected final CardLayout cardLayoutBottomSidePane = new CardLayout(); + protected final JPanel bottomSidePane = new JPanel(cardLayoutBottomSidePane); + + protected final CardLayout cardLayoutTopSidePane = new CardLayout(); + protected final JPanel topSidePane = new JPanel(cardLayoutTopSidePane); + + protected final CardLayout cardLayoutWorkspacePane = new CardLayout(); + protected final JPanel workspacePane = new JPanel(cardLayoutWorkspacePane); + + private Workspace workspace; + + protected final StatusBar statusBar = ModelerSession.getComponentFactoryService().createStatusBar(); + protected final LabelStatusBarItem statusUserTitleLabel = ModelerSession.getComponentFactoryService().createLabelStatusBarItem(); + protected final LabelStatusBarItem loggedUserLabel = ModelerSession.getComponentFactoryService().createLabelStatusBarItem(); + protected final ButtonStatusBarItem switchUserButton = ModelerSession.getComponentFactoryService().createButtonStatusBarItem(); + + protected final CardLayout cardLayoutToolBar = new CardLayout(); + protected final JPanel toolBarPane = new JPanel(cardLayoutToolBar); + + private static final Dimension DEFAULT_SIZE = new Dimension(1024, 768); + + private static final Dimension DEFAULT_SIZE_LOW_LEVEL = new Dimension(300, 500); + + private static final Dimension DEFAULT_SIZE_CONSOLE = new Dimension(500, 200); + + private static final Point DEFAULT_UNDOCKED_FRAME_POSITION = new Point(-1, -1); + + private static final String USER_TITLE_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.user.title"); + private static final String USER_SWITCH_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.user.switch"); + + protected final CardLayout cardLayoutStatusBar = new CardLayout(); + protected final JPanel statusBarPane = new JPanel(cardLayoutStatusBar); + + + public ModelerView(){ + setTitle(ModelerModel.APPLICATION_NAME); + + initializeDockingManager(); + + initLayout(); + + initStatusBar(); + + setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + setPreferredSize(DEFAULT_SIZE); + setSize(DEFAULT_SIZE); + setLocationRelativeTo(null); + } + + /** + * Initialize status bar items. + */ + private void initStatusBar() { + statusUserTitleLabel.setAlignment(JLabel.LEFT); + statusUserTitleLabel.setText(USER_TITLE_LABEL); + statusBar.add(statusUserTitleLabel, JideBoxLayout.FIX); + + loggedUserLabel.setAlignment(JLabel.LEFT); + loggedUserLabel.setText(ModelerSession.getUserService().getUser()); + statusBar.add(loggedUserLabel, JideBoxLayout.FIX); + + switchUserButton.setText(USER_SWITCH_LABEL); + statusBar.add(switchUserButton, JideBoxLayout.FIX); + + statusBar.add(statusBarPane, JideBoxLayout.VARY); + } + + private void initLayout(){ + workspace.add(workspacePane); // add panel with CardLayout on the workspace + + final JPanel basisPanel = ModelerSession.getComponentFactoryService().createPanel(); + basisPanel.setLayout(new BorderLayout()); + + basisPanel.add(dockableArea, BorderLayout.CENTER); + basisPanel.add(rightSidePane, BorderLayout.EAST); + basisPanel.add(leftSideBottomLayerPane, BorderLayout.WEST); + basisPanel.add(topSidePane, BorderLayout.NORTH); + basisPanel.add(bottomSidePane, BorderLayout.SOUTH); + + add(basisPanel, BorderLayout.CENTER); + add(toolBarPane, BorderLayout.PAGE_START); + add(statusBar, BorderLayout.PAGE_END); + + //init high level navigation hide/show button + leftSideBottomLayerPane.add(leftSidePane, BorderLayout.CENTER); + + final JPanel panelProjectNavigationButton = new JPanel(new BorderLayout()); + panelProjectNavigationButton.setBorder(Borders.DLU2_BORDER); + panelProjectNavigationButton.setOpaque(false); + panelProjectNavigationButton.add(projectNavigatorButton, BorderLayout.CENTER); + + leftSideBottomLayerPane.add(panelProjectNavigationButton, BorderLayout.NORTH); + + //ads empty panels to all of card layouts with special key defined by ModelerModel.MODELER_IDENTIFIER + initEmptyModelerView(); + } + + /** + * Initialize buttons panels, workspace and tool bar that are visible if no notation is selected. + */ + private void initEmptyModelerView() { + rightSidePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); + leftSidePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); + bottomSidePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); + topSidePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); + + workspacePane.add(ModelerSession.getComponentFactoryService().createPanel(), ModelerModel.MODELER_IDENTIFIER); + + toolBarPane.add(ModelerSession.getToolBarControlService().getCommandBar(ModelerModel.MODELER_IDENTIFIER), ModelerModel.MODELER_IDENTIFIER); + statusBarPane.add(ModelerSession.getStatusBarControlService().getStatusBar(ModelerModel.MODELER_IDENTIFIER), ModelerModel.MODELER_IDENTIFIER); + } + + /** + * Initialization project navigation. + */ + protected void initProjectNavigation(){ + projectNavigationDockableFrame = new ProjectNavigation(PROJECT_NAVIGATION_INDEX); + dockingManager.addFrame(projectNavigationDockableFrame); + } + + private void initializeDockingManager(){ + dockableArea = new JPanel(); + + dockingManager = new DefaultDockingManager(this, dockableArea); + + workspace = dockingManager.getWorkspace(); + + dockingManager.setSideDockAllowed(false); + + dockingManager.setInitSplitPriority(DockingManager.SPLIT_EAST_WEST_SOUTH_NORTH); + + dockingManager.setTabbedPaneCustomizer(new + DockingManager.TabbedPaneCustomizer(){ + public void customize( JideTabbedPane tabbedPane ){ + tabbedPane.setHideOneTab(true); + } + }); + } + + /** + * Adds a new main windows to the workplace card layout. + * + * @param key is a key for the card layout + * @param component is the component to be displayed + */ + protected void addMainWindowPane( final String key, final Component component ){ + workspacePane.add(key, component); + } + + /** + * Adds a new tool bar to the tool bar card layout. + * + * @param notationIdentifier is a key for the card layout + * @param commandBar is the component to be displayed + */ + protected void addToolBarPane(final String notationIdentifier, final CommandBar commandBar){ + toolBarPane.add(commandBar, notationIdentifier); + } + + /** + * Adds a new status bar. + * + * @param notationIdentifier is a key for the card layout + * @param statusBar is the notation specific status bar + */ + protected void addStatusBar(final String notationIdentifier, final StatusBar statusBar){ + statusBarPane.add(statusBar, notationIdentifier); + } + + /** + * Adds a new side panel onto the specified base layer using CardLayout. + * + * @param key to be used by the CardLayout. + * @param baseLayer is base layer onto that should be the new panel added. + * @param buttonList is list of buttons to be shown on the new layer. + * @param isVertical true = vertical (for low level navigation), false = horizontal (consoles). + */ + protected void addSidePane( final String key, + final JPanel baseLayer, + final List buttonList, + final boolean isVertical ){ + final JPanel panel = new JPanel(); + panel.setBorder(Borders.DLU2_BORDER); + + final Dimension dimension; + if( isVertical ){ + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + dimension = BOX_VERTICAL_GAP; + } else{ + panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); + dimension = BOX_HORIZONTAL_GAP; + } + + for( JideButton but : buttonList ){ + panel.add(but); + panel.add(Box.createRigidArea(dimension)); + } + + baseLayer.add(panel, key); + } + + /** + * Creates the dockable frame. + * + * @param component is the component to be added on the dockable frame. + * @param position is the position specification. + * @param title is the dockable frame id + * @param isMaximizable true if the frame is supposed to be maximizable + * @param initialState is the initial state of the frame + * @return the instance of required dockable frame + */ + protected DockableFrame createDockableFrame(final JComponent component, + final NotationGuiHolder.Position position, + final String title, + final boolean isMaximizable, + final DockableFrameData.InitialState initialState){ + + final DockableFrame dockableFrame = new DockableFrame(String.valueOf(dockableFrameIDcounter++)); + dockableFrame.setTitle(title); + + dockableFrame.setShowContextMenu(false); + + if(DockableFrameData.InitialState.FLOATED.equals(initialState)){ + dockableFrame.getContext().setInitMode(DockContext.STATE_FLOATING); + } else { + dockableFrame.getContext().setInitMode(DockContext.STATE_FRAMEDOCKED); + } + + dockableFrame.getContext().setInitIndex(dockingFrameCounter++); + dockableFrame.setAutohidable(false); + dockableFrame.setDockable(true); + dockableFrame.setSideDockAllowed(false); + dockableFrame.setRearrangable(false); + dockableFrame.setTabDockAllowed(false); + + // make this dockable frame maximizable or not + int availableButtons = DockableFrame.BUTTON_FLOATING | DockableFrame.BUTTON_CLOSE; + if(isMaximizable){ + availableButtons |= DockableFrame.BUTTON_MAXIMIZE; + } + dockableFrame.setAvailableButtons(availableButtons); + + switch( position ){ + case RIGHT: + dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_EAST); + dockableFrame.setUndockedBounds(new Rectangle(DEFAULT_UNDOCKED_FRAME_POSITION, DEFAULT_SIZE_LOW_LEVEL)); + dockableFrame.setPreferredSize(DEFAULT_SIZE_LOW_LEVEL); + break; + case LEFT: + dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_WEST); + dockableFrame.setUndockedBounds(new Rectangle(DEFAULT_UNDOCKED_FRAME_POSITION, DEFAULT_SIZE_LOW_LEVEL)); + dockableFrame.setPreferredSize(DEFAULT_SIZE_LOW_LEVEL); + break; + case BOTTOM: + dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_SOUTH); + dockableFrame.setUndockedBounds(new Rectangle(DEFAULT_UNDOCKED_FRAME_POSITION, DEFAULT_SIZE_CONSOLE)); + dockableFrame.setPreferredSize(DEFAULT_SIZE_CONSOLE); + break; + case TOP: + dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_NORTH); + dockableFrame.setUndockedBounds(new Rectangle(DEFAULT_UNDOCKED_FRAME_POSITION, DEFAULT_SIZE_CONSOLE)); + dockableFrame.setPreferredSize(DEFAULT_SIZE_CONSOLE); + break; + default: + dockableFrame.getContext().setInitSide(DockContext.DOCK_SIDE_WEST); + } + + dockableFrame.add(component); + + return dockableFrame; + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialog.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialog.java index 530f6c4..905af00 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialog.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialog.java @@ -1,221 +1,221 @@ -package cz.cvut.promod.gui.dialogs.addNewDiagramDialog; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.results.AddProjectItemResult; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; - -import javax.swing.event.ListSelectionListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.*; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.util.Map; -import java.util.HashMap; -import java.util.UUID; - -import org.apache.log4j.Logger; -import com.jgoodies.binding.adapter.Bindings; -import com.jgoodies.binding.PresentationModel; - - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 15:58:45, 24.10.2009 - * - * The dialog for adding new diagrams into a project. - */ -public class AddNewDiagramDialog extends AddNewDiagramDialogView { - - private final Logger LOG = Logger.getLogger(AddNewDiagramDialog.class); - - private static final String ILLEGAL_PARENT_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.illegalParent"); - private static final String DUPLICITY_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.duplicity"); - private static final String ILLEGAL_NOTATION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.illegalNotation"); - private static final String ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error"); - private static final String INVALID_NAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.disallowed"); - - private AddNewDiagramDialogModel model; - - private Map images; - - private PresentationModel presentation; - - - public AddNewDiagramDialog(){ - final JFrame frame = ModelerSession.getFrame(); - if(frame != null){ - setLocationRelativeTo(frame); - } - - setTitle(ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.title")); - - model = new AddNewDiagramDialogModel(); - presentation = new PresentationModel(model); - - images = new HashMap(); - - initList(); - - initBinding(); - - initEventHandling(); - - if(model.getSize() == 0){ - confirmButton.setEnabled(false); - } else { - notationsList.setSelectedIndex(0); - } - - getRootPane().setDefaultButton(confirmButton); - - setVisible(true); - } - - /** - * Initialize bindings. - */ - private void initBinding() { - Bindings.bind(newDiagramNameTextField, presentation.getModel(AddNewDiagramDialogModel.PROPERTY_NEW_DIAGRAM_NAME)); - } - - /** - * Initialize list of notations. - */ - private void initList() { - notationsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - - notationsList.setModel(model); - } - - /** - * Initialize event handling. - */ - private void initEventHandling() { - notationsList.addListSelectionListener(new ListSelectionListener(){ - public void valueChanged(ListSelectionEvent e) { - final String notationIdentifier = - ((AddNewDiagramDialogModel.NotationLabelWrapper)model.getElementAt(notationsList.getSelectedIndex())).getIdentifier(); - - updateDialogView(notationIdentifier); - model.setSelectedNotationIdentifier(notationIdentifier); - } - }); - - cancelButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - disposeDialog(); - } - }); - - confirmButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - addDiagram(); - } - }); - - getRootPane().registerKeyboardAction(new ActionListener(){ - public void actionPerformed(ActionEvent actionEvent) { - disposeDialog(); - } - }, - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - } - - /** - * Adds the diagram. - */ - private void addDiagram() { - final String notationIdentifier = model.getSelectedNotationIdentifier(); - final String diagramName = model.getNewDiagramName(); - - final UUID uuid = UUID.randomUUID(); - - final ProjectDiagram projectDiagram = new ProjectDiagram( - diagramName, - notationIdentifier, - uuid, - ModelerSession.getNotationService().getNotation(notationIdentifier).getDiagramModelFactory().createEmptyDiagramModel() - ); - - AddProjectItemResult result = ModelerSession.getProjectControlService().addDiagram(projectDiagram, true); - - switch(result.getStatus()){ - case SUCCESS: - disposeDialog(); - - ModelerSession.getProjectControlService().synchronize( - result.getTreePath(), - true, true, false, false - ); - - break; - case ILLEGAL_PARENT: - errorLabel.setText(ILLEGAL_PARENT_LABEL); - break; - case NAME_DUPLICITY: - errorLabel.setText(DUPLICITY_LABEL); - break; - case INVALID_NAME: - publicInvalidNameError(diagramName); - break; - case ILLEGAL_NOTATION: - errorLabel.setText(ILLEGAL_NOTATION_LABEL); - break; - default: - errorLabel.setText(ERROR_LABEL); - LOG.error("No such a choice for add diagram result messages."); - } - } - - /** - * Updates the dialog view when a notation is selected. - * @param notationIdentifier is the identifier of selected notation. - */ - private void updateDialogView(final String notationIdentifier) { - final String text = ModelerSession.getNotationService().getNotation(notationIdentifier).getNotationPreviewText(); - - if(text != null){ - notationInfoTextArea.setText(text); - } else { - notationInfoTextArea.setText(""); - } - - if(images.containsKey(notationIdentifier)){ - imagePanel.setImage(images.get(notationIdentifier)); - } else { - final ImageIcon image = ModelerSession.getNotationService().getNotation(notationIdentifier).getNotationPreviewImage(); - - images.put(notationIdentifier, image); - imagePanel.setImage(image); - } - } - - /** - * Hides the dialog. - */ - private void disposeDialog(){ - setVisible(false); - dispose(); - } - - /** - * Publish invalid name error. - * - * @param projectName is the project name - */ - private void publicInvalidNameError(final String projectName) { - if(!ProjectServiceUtils.isSyntacticallyCorrectName(projectName)){ - errorLabel.setText(INVALID_NAME_LABEL + ProjectServiceUtils.getDisallowedNameSymbols(',')); - } - } - +package cz.cvut.promod.gui.dialogs.addNewDiagramDialog; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.results.AddProjectItemResult; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; + +import javax.swing.event.ListSelectionListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.*; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.util.Map; +import java.util.HashMap; +import java.util.UUID; + +import org.apache.log4j.Logger; +import com.jgoodies.binding.adapter.Bindings; +import com.jgoodies.binding.PresentationModel; + + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 15:58:45, 24.10.2009 + * + * The dialog for adding new diagrams into a project. + */ +public class AddNewDiagramDialog extends AddNewDiagramDialogView { + + private final Logger LOG = Logger.getLogger(AddNewDiagramDialog.class); + + private static final String ILLEGAL_PARENT_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.illegalParent"); + private static final String DUPLICITY_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.duplicity"); + private static final String ILLEGAL_NOTATION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.illegalNotation"); + private static final String ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error"); + private static final String INVALID_NAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.disallowed"); + + private AddNewDiagramDialogModel model; + + private Map images; + + private PresentationModel presentation; + + + public AddNewDiagramDialog(){ + final JFrame frame = ModelerSession.getFrame(); + if(frame != null){ + setLocationRelativeTo(frame); + } + + setTitle(ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.title")); + + model = new AddNewDiagramDialogModel(); + presentation = new PresentationModel(model); + + images = new HashMap(); + + initList(); + + initBinding(); + + initEventHandling(); + + if(model.getSize() == 0){ + confirmButton.setEnabled(false); + } else { + notationsList.setSelectedIndex(0); + } + + getRootPane().setDefaultButton(confirmButton); + + setVisible(true); + } + + /** + * Initialize bindings. + */ + private void initBinding() { + Bindings.bind(newDiagramNameTextField, presentation.getModel(AddNewDiagramDialogModel.PROPERTY_NEW_DIAGRAM_NAME)); + } + + /** + * Initialize list of notations. + */ + private void initList() { + notationsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + + notationsList.setModel(model); + } + + /** + * Initialize event handling. + */ + private void initEventHandling() { + notationsList.addListSelectionListener(new ListSelectionListener(){ + public void valueChanged(ListSelectionEvent e) { + final String notationIdentifier = + ((AddNewDiagramDialogModel.NotationLabelWrapper)model.getElementAt(notationsList.getSelectedIndex())).getIdentifier(); + + updateDialogView(notationIdentifier); + model.setSelectedNotationIdentifier(notationIdentifier); + } + }); + + cancelButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + + confirmButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + addDiagram(); + } + }); + + getRootPane().registerKeyboardAction(new ActionListener(){ + public void actionPerformed(ActionEvent actionEvent) { + disposeDialog(); + } + }, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + } + + /** + * Adds the diagram. + */ + private void addDiagram() { + final String notationIdentifier = model.getSelectedNotationIdentifier(); + final String diagramName = model.getNewDiagramName(); + + final UUID uuid = UUID.randomUUID(); + + final ProjectDiagram projectDiagram = new ProjectDiagram( + diagramName, + notationIdentifier, + uuid, + ModelerSession.getNotationService().getNotation(notationIdentifier).getDiagramModelFactory().createEmptyDiagramModel() + ); + + AddProjectItemResult result = ModelerSession.getProjectControlService().addDiagram(projectDiagram, true); + + switch(result.getStatus()){ + case SUCCESS: + disposeDialog(); + + ModelerSession.getProjectControlService().synchronize( + result.getTreePath(), + true, true, false, false + ); + + break; + case ILLEGAL_PARENT: + errorLabel.setText(ILLEGAL_PARENT_LABEL); + break; + case NAME_DUPLICITY: + errorLabel.setText(DUPLICITY_LABEL); + break; + case INVALID_NAME: + publicInvalidNameError(diagramName); + break; + case ILLEGAL_NOTATION: + errorLabel.setText(ILLEGAL_NOTATION_LABEL); + break; + default: + errorLabel.setText(ERROR_LABEL); + LOG.error("No such a choice for add diagram result messages."); + } + } + + /** + * Updates the dialog view when a notation is selected. + * @param notationIdentifier is the identifier of selected notation. + */ + private void updateDialogView(final String notationIdentifier) { + final String text = ModelerSession.getNotationService().getNotation(notationIdentifier).getNotationPreviewText(); + + if(text != null){ + notationInfoTextArea.setText(text); + } else { + notationInfoTextArea.setText(""); + } + + if(images.containsKey(notationIdentifier)){ + imagePanel.setImage(images.get(notationIdentifier)); + } else { + final ImageIcon image = ModelerSession.getNotationService().getNotation(notationIdentifier).getNotationPreviewImage(); + + images.put(notationIdentifier, image); + imagePanel.setImage(image); + } + } + + /** + * Hides the dialog. + */ + private void disposeDialog(){ + setVisible(false); + dispose(); + } + + /** + * Publish invalid name error. + * + * @param projectName is the project name + */ + private void publicInvalidNameError(final String projectName) { + if(!ProjectServiceUtils.isSyntacticallyCorrectName(projectName)){ + errorLabel.setText(INVALID_NAME_LABEL + ProjectServiceUtils.getDisallowedNameSymbols(',')); + } + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialogModel.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialogModel.java index cdc7d4a..e4498e8 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialogModel.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialogModel.java @@ -1,92 +1,92 @@ -package cz.cvut.promod.gui.dialogs.addNewDiagramDialog; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; - -import javax.swing.event.ListDataListener; -import javax.swing.*; -import java.util.List; -import java.util.LinkedList; - -import com.jgoodies.binding.beans.Model; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 15:59:01, 24.10.2009 - * - * A Model component for AddNewDiagramDialog. - */ -public class AddNewDiagramDialogModel extends Model implements ListModel { - - public static final String PROPERTY_NEW_DIAGRAM_NAME = "newDiagramName"; - private String newDiagramName; - - public static final String PROPERTY_SELECTED_NOTATION_IDENTIFIER = "selectedNotationIdentifier"; - private String selectedNotationIdentifier; - - private final List notationNames; - - public AddNewDiagramDialogModel() { - notationNames = new LinkedList(); - - for(final Notation notation : ModelerSession.getNotationService().getNotations()){ - notationNames.add(new NotationLabelWrapper(notation.getIdentifier(), notation.getFullName())); - } - } - - public int getSize() { - return notationNames.size(); - } - - public Object getElementAt(int index) { - return notationNames.get(index); - } - - public void addListDataListener(ListDataListener l) {} - - public void removeListDataListener(ListDataListener l) {} - - public String getNewDiagramName() { - return newDiagramName; - } - - public void setNewDiagramName(final String newDiagramName) { - final String oldNewDiagramName = this.newDiagramName; - this.newDiagramName = newDiagramName; - firePropertyChange(PROPERTY_NEW_DIAGRAM_NAME, oldNewDiagramName, newDiagramName); - } - - public String getSelectedNotationIdentifier() { - return selectedNotationIdentifier; - } - - public void setSelectedNotationIdentifier(final String selectedNotationIdentifier) { - final String oldSelectedNotationIdentifier = this.selectedNotationIdentifier; - this.selectedNotationIdentifier = selectedNotationIdentifier; - firePropertyChange(PROPERTY_SELECTED_NOTATION_IDENTIFIER, oldSelectedNotationIdentifier, selectedNotationIdentifier); - } - - /** - * Represents an item in the list of notations. - */ - protected static class NotationLabelWrapper{ - - private final String identifier; - private final String displayName; - - private NotationLabelWrapper(final String identifier, final String displayName) { - this.identifier = identifier; - this.displayName = displayName; - } - - public String getIdentifier() { - return identifier; - } - - @Override - public String toString() { - return displayName; - } - } -} +package cz.cvut.promod.gui.dialogs.addNewDiagramDialog; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; + +import javax.swing.event.ListDataListener; +import javax.swing.*; +import java.util.List; +import java.util.LinkedList; + +import com.jgoodies.binding.beans.Model; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 15:59:01, 24.10.2009 + * + * A Model component for AddNewDiagramDialog. + */ +public class AddNewDiagramDialogModel extends Model implements ListModel { + + public static final String PROPERTY_NEW_DIAGRAM_NAME = "newDiagramName"; + private String newDiagramName; + + public static final String PROPERTY_SELECTED_NOTATION_IDENTIFIER = "selectedNotationIdentifier"; + private String selectedNotationIdentifier; + + private final List notationNames; + + public AddNewDiagramDialogModel() { + notationNames = new LinkedList(); + + for(final Notation notation : ModelerSession.getNotationService().getNotations()){ + notationNames.add(new NotationLabelWrapper(notation.getIdentifier(), notation.getFullName())); + } + } + + public int getSize() { + return notationNames.size(); + } + + public Object getElementAt(int index) { + return notationNames.get(index); + } + + public void addListDataListener(ListDataListener l) {} + + public void removeListDataListener(ListDataListener l) {} + + public String getNewDiagramName() { + return newDiagramName; + } + + public void setNewDiagramName(final String newDiagramName) { + final String oldNewDiagramName = this.newDiagramName; + this.newDiagramName = newDiagramName; + firePropertyChange(PROPERTY_NEW_DIAGRAM_NAME, oldNewDiagramName, newDiagramName); + } + + public String getSelectedNotationIdentifier() { + return selectedNotationIdentifier; + } + + public void setSelectedNotationIdentifier(final String selectedNotationIdentifier) { + final String oldSelectedNotationIdentifier = this.selectedNotationIdentifier; + this.selectedNotationIdentifier = selectedNotationIdentifier; + firePropertyChange(PROPERTY_SELECTED_NOTATION_IDENTIFIER, oldSelectedNotationIdentifier, selectedNotationIdentifier); + } + + /** + * Represents an item in the list of notations. + */ + protected static class NotationLabelWrapper{ + + private final String identifier; + private final String displayName; + + private NotationLabelWrapper(final String identifier, final String displayName) { + this.identifier = identifier; + this.displayName = displayName; + } + + public String getIdentifier() { + return identifier; + } + + @Override + public String toString() { + return displayName; + } + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialogView.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialogView.java index 1a5d042..ba06485 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialogView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/addNewDiagramDialog/AddNewDiagramDialogView.java @@ -1,167 +1,167 @@ -package cz.cvut.promod.gui.dialogs.addNewDiagramDialog; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; - -import javax.swing.*; -import java.awt.*; - -import com.jgoodies.forms.factories.Borders; -import com.jgoodies.forms.layout.FormLayout; -import com.jgoodies.forms.layout.CellConstraints; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 15:58:50, 24.10.2009 - * - * The view component for AddNewDiagramDialog. - */ -public class AddNewDiagramDialogView extends JDialog { - - private static final Dimension INIT_IMAGE_SIZE = new Dimension(400, 201); - private static final Dimension INIT_SIZE = new Dimension(750, 470); - - private static final int BORDER_LAYOUT_HGAP = 0; - private static final int BORDER_LAYOUT_VGAP = 10; - - protected final JLabel notationsListLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.tableTitle")); - - protected final JList notationsList = ModelerSession.getComponentFactoryService().createList(); - - private final JLabel newDiagramNameLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.nameTitle")); - - protected final JTextField newDiagramNameTextField = ModelerSession.getComponentFactoryService().createTextField(); - - protected final JTextArea notationInfoTextArea = ModelerSession.getComponentFactoryService().createTextArea(); - - protected JButton confirmButton = ModelerSession.getComponentFactoryService().createButton( - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.confirm"), null); - - protected JButton cancelButton = ModelerSession.getComponentFactoryService().createButton( - ModelerSession.getCommonResourceBundle().getString("modeler.cancel"), null); - - protected final JLabel errorLabel = ModelerSession.getComponentFactoryService().createLabel(""); - - protected final ImagePanel imagePanel = new ImagePanel(); - - - protected AddNewDiagramDialogView(){ - setModal(true); - - errorLabel.setForeground(Color.RED); - - notationInfoTextArea.setLineWrap(true); - notationInfoTextArea.setEditable(false); - - notationsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - - initLayout(); - } - - private void initLayout() { - setSize(INIT_SIZE); - - final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); - centerPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - centerPanel.setLayout(new BorderLayout()); - - final JPanel centerWestPanel = ModelerSession.getComponentFactoryService().createPanel(); - centerWestPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - centerWestPanel.setLayout(new BorderLayout()); - - final JPanel centerSouthPanel = ModelerSession.getComponentFactoryService().createPanel(); - centerSouthPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - centerSouthPanel.setLayout(new FormLayout("max(pref; 100dlu):grow", "pref, 3dlu, pref")); - - final CellConstraints cellConstraints = new CellConstraints(); - - centerSouthPanel.add(newDiagramNameLabel, cellConstraints.xy(1,1)); - centerSouthPanel.add(newDiagramNameTextField, cellConstraints.xy(1,3)); - - centerWestPanel.add(notationsListLabel, BorderLayout.NORTH); - centerWestPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(notationsList), BorderLayout.CENTER); - centerWestPanel.add(centerSouthPanel, BorderLayout.SOUTH); - - final JPanel centerCenterPanel = ModelerSession.getComponentFactoryService().createPanel(); - centerCenterPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - centerCenterPanel.setLayout(new BorderLayout(BORDER_LAYOUT_HGAP, BORDER_LAYOUT_VGAP)); - - centerCenterPanel.add(imagePanel, BorderLayout.NORTH); - centerCenterPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(notationInfoTextArea), BorderLayout.CENTER); - - centerPanel.add(centerWestPanel, BorderLayout.WEST); - centerPanel.add(centerCenterPanel, BorderLayout.CENTER); - - final JPanel southPanel = ModelerSession.getComponentFactoryService().createPanel(); - southPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - southPanel.setLayout(new FormLayout( - "pref:grow, pref, 3dlu, pref, pref:grow", - "pref, 5dlu, pref")); - - southPanel.add(errorLabel, cellConstraints.xyw(1,1,5)); - - southPanel.add(confirmButton, cellConstraints.xy(2, 3)); - southPanel.add(cancelButton, cellConstraints.xy(4, 3)); - - setLayout(new BorderLayout()); - add(centerPanel, BorderLayout.CENTER); - add(southPanel, BorderLayout.SOUTH); - } - - protected static class ImagePanel extends JPanel{ - - private final int POSITION_Y = 0; - - private int position_x = 0; - - private ImageIcon image = null; - - public ImagePanel(){ - setPreferredSize(INIT_IMAGE_SIZE); - } - - protected void paintComponent(Graphics g) { - super.paintComponent(g); - - int recWidth; - int recHeight; - - if(image != null){ - position_x = this.getWidth() - image.getIconWidth(); - position_x = position_x > 0 ? position_x / 2 : 0; - position_x = Math.max(1, position_x); - - recWidth = image.getIconWidth(); - recHeight = image.getIconHeight(); - - g.drawImage(image.getImage(), position_x, POSITION_Y, null); - - } else { - position_x = this.getWidth() - (int)INIT_IMAGE_SIZE.getWidth(); - position_x = position_x > 0 ? position_x / 2 : 0; - position_x = Math.max(1, position_x); - - recWidth = (int)INIT_IMAGE_SIZE.getWidth(); - recHeight = (int)INIT_IMAGE_SIZE.getHeight() - 1; - - //over-paint the old image - g.setColor(Color.WHITE); - g.fillRect(position_x, POSITION_Y, recWidth, recHeight); - } - - g.setColor(Color.BLACK); - g.drawRect(position_x, POSITION_Y, recWidth, recHeight); - } - - public void setImage(final ImageIcon image){ - this.image = image; - repaint(); - } - } - - -} +package cz.cvut.promod.gui.dialogs.addNewDiagramDialog; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; + +import javax.swing.*; +import java.awt.*; + +import com.jgoodies.forms.factories.Borders; +import com.jgoodies.forms.layout.FormLayout; +import com.jgoodies.forms.layout.CellConstraints; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 15:58:50, 24.10.2009 + * + * The view component for AddNewDiagramDialog. + */ +public class AddNewDiagramDialogView extends JDialog { + + private static final Dimension INIT_IMAGE_SIZE = new Dimension(400, 201); + private static final Dimension INIT_SIZE = new Dimension(750, 470); + + private static final int BORDER_LAYOUT_HGAP = 0; + private static final int BORDER_LAYOUT_VGAP = 10; + + protected final JLabel notationsListLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.tableTitle")); + + protected final JList notationsList = ModelerSession.getComponentFactoryService().createList(); + + private final JLabel newDiagramNameLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.nameTitle")); + + protected final JTextField newDiagramNameTextField = ModelerSession.getComponentFactoryService().createTextField(); + + protected final JTextArea notationInfoTextArea = ModelerSession.getComponentFactoryService().createTextArea(); + + protected JButton confirmButton = ModelerSession.getComponentFactoryService().createButton( + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.confirm"), null); + + protected JButton cancelButton = ModelerSession.getComponentFactoryService().createButton( + ModelerSession.getCommonResourceBundle().getString("modeler.cancel"), null); + + protected final JLabel errorLabel = ModelerSession.getComponentFactoryService().createLabel(""); + + protected final ImagePanel imagePanel = new ImagePanel(); + + + protected AddNewDiagramDialogView(){ + setModal(true); + + errorLabel.setForeground(Color.RED); + + notationInfoTextArea.setLineWrap(true); + notationInfoTextArea.setEditable(false); + + notationsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + + initLayout(); + } + + private void initLayout() { + setSize(INIT_SIZE); + + final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); + centerPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + centerPanel.setLayout(new BorderLayout()); + + final JPanel centerWestPanel = ModelerSession.getComponentFactoryService().createPanel(); + centerWestPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + centerWestPanel.setLayout(new BorderLayout()); + + final JPanel centerSouthPanel = ModelerSession.getComponentFactoryService().createPanel(); + centerSouthPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + centerSouthPanel.setLayout(new FormLayout("max(pref; 100dlu):grow", "pref, 3dlu, pref")); + + final CellConstraints cellConstraints = new CellConstraints(); + + centerSouthPanel.add(newDiagramNameLabel, cellConstraints.xy(1,1)); + centerSouthPanel.add(newDiagramNameTextField, cellConstraints.xy(1,3)); + + centerWestPanel.add(notationsListLabel, BorderLayout.NORTH); + centerWestPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(notationsList), BorderLayout.CENTER); + centerWestPanel.add(centerSouthPanel, BorderLayout.SOUTH); + + final JPanel centerCenterPanel = ModelerSession.getComponentFactoryService().createPanel(); + centerCenterPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + centerCenterPanel.setLayout(new BorderLayout(BORDER_LAYOUT_HGAP, BORDER_LAYOUT_VGAP)); + + centerCenterPanel.add(imagePanel, BorderLayout.NORTH); + centerCenterPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(notationInfoTextArea), BorderLayout.CENTER); + + centerPanel.add(centerWestPanel, BorderLayout.WEST); + centerPanel.add(centerCenterPanel, BorderLayout.CENTER); + + final JPanel southPanel = ModelerSession.getComponentFactoryService().createPanel(); + southPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + southPanel.setLayout(new FormLayout( + "pref:grow, pref, 3dlu, pref, pref:grow", + "pref, 5dlu, pref")); + + southPanel.add(errorLabel, cellConstraints.xyw(1,1,5)); + + southPanel.add(confirmButton, cellConstraints.xy(2, 3)); + southPanel.add(cancelButton, cellConstraints.xy(4, 3)); + + setLayout(new BorderLayout()); + add(centerPanel, BorderLayout.CENTER); + add(southPanel, BorderLayout.SOUTH); + } + + protected static class ImagePanel extends JPanel{ + + private final int POSITION_Y = 0; + + private int position_x = 0; + + private ImageIcon image = null; + + public ImagePanel(){ + setPreferredSize(INIT_IMAGE_SIZE); + } + + protected void paintComponent(Graphics g) { + super.paintComponent(g); + + int recWidth; + int recHeight; + + if(image != null){ + position_x = this.getWidth() - image.getIconWidth(); + position_x = position_x > 0 ? position_x / 2 : 0; + position_x = Math.max(1, position_x); + + recWidth = image.getIconWidth(); + recHeight = image.getIconHeight(); + + g.drawImage(image.getImage(), position_x, POSITION_Y, null); + + } else { + position_x = this.getWidth() - (int)INIT_IMAGE_SIZE.getWidth(); + position_x = position_x > 0 ? position_x / 2 : 0; + position_x = Math.max(1, position_x); + + recWidth = (int)INIT_IMAGE_SIZE.getWidth(); + recHeight = (int)INIT_IMAGE_SIZE.getHeight() - 1; + + //over-paint the old image + g.setColor(Color.WHITE); + g.fillRect(position_x, POSITION_Y, recWidth, recHeight); + } + + g.setColor(Color.BLACK); + g.drawRect(position_x, POSITION_Y, recWidth, recHeight); + } + + public void setImage(final ImageIcon image){ + this.image = image; + repaint(); + } + } + + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/configurationChangeDialog/ConfigurationDiffDialog.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/configurationChangeDialog/ConfigurationDiffDialog.java index dfd75c6..aeaa0aa 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/configurationChangeDialog/ConfigurationDiffDialog.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/configurationChangeDialog/ConfigurationDiffDialog.java @@ -1,217 +1,217 @@ -package cz.cvut.promod.gui.dialogs.configurationChangeDialog; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.projectService.results.ConfigurationDifference; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; - -import java.util.List; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; - -import org.apache.log4j.Logger; - -import javax.swing.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:55:32, 12.12.2009 - * - * Dialog displaying differences between actual ProMod configuration and the ProMod configuration that - * was actual at the time, when the project, that is now being loaded, was saved. - */ -public class ConfigurationDiffDialog extends ConfigurationDiffDialogView{ - - private static final Logger LOG = Logger.getLogger(ConfigurationDiffDialog.class); - - private static final String TITLE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.title"); - private static final String MISSING_NOTATION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.missing.notation"); - private static final String LOADED_VALUE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.loaded.value"); - private static final String ACTUAL_VALUE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.actual.value"); - private static final String MISSING_MODULE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.missing.module"); - private static final String RELATED_IDENTIFIER_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.related.notation"); - private static final String MISSING_EXTENSION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.missing.extension"); - private static final String DIFF_EXTENSION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.different.extension"); - private static final String DIFF_ABBREVIATION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.different.abbreviation"); - private static final String DIFF_NAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.different.name"); - - public final String NEW_LINE = "\n"; - - - /** - * Constructs a new ConfigurationDiffDialog class. - * - * @param differences is the list containing all configuration differences - */ - public ConfigurationDiffDialog(final List differences){ - setTitle(TITLE_LABEL); - - initEventHandling(); - - initReport(differences); - - setModal(true); - - getRootPane().setDefaultButton(hideButton); - - setVisible(true); - } - - /** - * Initialize event handling. - */ - private void initEventHandling() { - hideButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - disposeDialog(); - } - }); - - getRootPane().registerKeyboardAction(new ActionListener(){ - public void actionPerformed(ActionEvent actionEvent) { - disposeDialog(); - } - }, - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - } - - /** - * Hides the dialog. - */ - private void disposeDialog(){ - setVisible(false); - dispose(); - } - - /** - * Initialize messages about configuration differences. - * - * @param differences all configuration differences - */ - private void initReport(final List differences) { - for(final ConfigurationDifference difference : differences){ - switch (difference.getChangeType()){ - case MISSING_NOTATION: - publishMissingNotationDiff(difference); - break; - case MISSING_MODULE: - publishMissingModuleDiff(difference); - break; - case MISSING_EXTENSION: - publishMissingExtensionDiff(difference); - break; - case DIFFERENT_FULL_NAME: - publishDiffName(difference); - break; - case DIFFERENT_ABBREVIATION: - publishDiffAbbreviation(difference); - break; - case DIFFERENT_EXTENSION: - publishDiffExtension(difference); - break; - default: - LOG.error("No such a configuration change option."); - } - - diffTextArea.append(NEW_LINE); - diffTextArea.append(NEW_LINE); - } - } - - /** - * Publishes different full name. - * - * @param difference is the difference detail - */ - private void publishDiffName(final ConfigurationDifference difference) { - diffTextArea.append(DIFF_NAME_LABEL); - diffTextArea.append(NEW_LINE); - diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); - diffTextArea.append(NEW_LINE); - diffTextArea.append(ACTUAL_VALUE_LABEL + " " + ModelerSession.getNotationService().getNotation(difference.getIdentifier()).getFullName()); - } - - /** - * Publishes different abbreviation. - * - * @param difference is the difference detail - */ - private void publishDiffAbbreviation(final ConfigurationDifference difference) { - diffTextArea.append(DIFF_ABBREVIATION_LABEL); - diffTextArea.append(NEW_LINE); - diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); - diffTextArea.append(NEW_LINE); - diffTextArea.append(ACTUAL_VALUE_LABEL + " " + ModelerSession.getNotationService().getNotation(difference.getIdentifier()).getAbbreviation()); - } - - /** - * Publishes different extension. - * - * @param difference is the difference detail - */ - private void publishDiffExtension(final ConfigurationDifference difference) { - diffTextArea.append(DIFF_EXTENSION_LABEL); - diffTextArea.append(NEW_LINE); - diffTextArea.append(LOADED_VALUE_LABEL +" " + difference.getMessage()); - diffTextArea.append(NEW_LINE); - diffTextArea.append( - ACTUAL_VALUE_LABEL + " " + ModelerSession.getNotationService().getNotation( - difference.getIdentifier() - ).getLocalIOController().getNotationFileExtension()); - } - - /** - * Publishes missing extension difference. - * - * @param difference is the difference detail - */ - private void publishMissingExtensionDiff(final ConfigurationDifference difference) { - diffTextArea.append(MISSING_EXTENSION_LABEL); - diffTextArea.append(NEW_LINE); - diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); - } - - /** - * Publishes missing module difference. - * - * @param difference is the difference detail - */ - private void publishMissingModuleDiff(final ConfigurationDifference difference) { - diffTextArea.append(MISSING_MODULE_LABEL); - diffTextArea.append(NEW_LINE); - - final Notation notation = ModelerSession.getNotationService().getNotation(difference.getIdentifier()); - if(notation != null){ - diffTextArea.append(RELATED_IDENTIFIER_LABEL + "" + notation.getFullName() + " (" + notation.getIdentifier() + ")."); - diffTextArea.append(NEW_LINE); - } else { - LOG.error("Unavailable notation for given identifier: " + difference.getIdentifier()); - } - - diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); - } - - /** - * Publishes missing notation difference. - * - * @param difference is the difference detail - */ - private void publishMissingNotationDiff(final ConfigurationDifference difference) { - diffTextArea.append(MISSING_NOTATION_LABEL); - diffTextArea.append(NEW_LINE); - diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); - } - +package cz.cvut.promod.gui.dialogs.configurationChangeDialog; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.projectService.results.ConfigurationDifference; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; + +import java.util.List; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; + +import org.apache.log4j.Logger; + +import javax.swing.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:55:32, 12.12.2009 + * + * Dialog displaying differences between actual ProMod configuration and the ProMod configuration that + * was actual at the time, when the project, that is now being loaded, was saved. + */ +public class ConfigurationDiffDialog extends ConfigurationDiffDialogView{ + + private static final Logger LOG = Logger.getLogger(ConfigurationDiffDialog.class); + + private static final String TITLE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.title"); + private static final String MISSING_NOTATION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.missing.notation"); + private static final String LOADED_VALUE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.loaded.value"); + private static final String ACTUAL_VALUE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.actual.value"); + private static final String MISSING_MODULE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.missing.module"); + private static final String RELATED_IDENTIFIER_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.related.notation"); + private static final String MISSING_EXTENSION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.missing.extension"); + private static final String DIFF_EXTENSION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.different.extension"); + private static final String DIFF_ABBREVIATION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.different.abbreviation"); + private static final String DIFF_NAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.different.name"); + + public final String NEW_LINE = "\n"; + + + /** + * Constructs a new ConfigurationDiffDialog class. + * + * @param differences is the list containing all configuration differences + */ + public ConfigurationDiffDialog(final List differences){ + setTitle(TITLE_LABEL); + + initEventHandling(); + + initReport(differences); + + setModal(true); + + getRootPane().setDefaultButton(hideButton); + + setVisible(true); + } + + /** + * Initialize event handling. + */ + private void initEventHandling() { + hideButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + + getRootPane().registerKeyboardAction(new ActionListener(){ + public void actionPerformed(ActionEvent actionEvent) { + disposeDialog(); + } + }, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + } + + /** + * Hides the dialog. + */ + private void disposeDialog(){ + setVisible(false); + dispose(); + } + + /** + * Initialize messages about configuration differences. + * + * @param differences all configuration differences + */ + private void initReport(final List differences) { + for(final ConfigurationDifference difference : differences){ + switch (difference.getChangeType()){ + case MISSING_NOTATION: + publishMissingNotationDiff(difference); + break; + case MISSING_MODULE: + publishMissingModuleDiff(difference); + break; + case MISSING_EXTENSION: + publishMissingExtensionDiff(difference); + break; + case DIFFERENT_FULL_NAME: + publishDiffName(difference); + break; + case DIFFERENT_ABBREVIATION: + publishDiffAbbreviation(difference); + break; + case DIFFERENT_EXTENSION: + publishDiffExtension(difference); + break; + default: + LOG.error("No such a configuration change option."); + } + + diffTextArea.append(NEW_LINE); + diffTextArea.append(NEW_LINE); + } + } + + /** + * Publishes different full name. + * + * @param difference is the difference detail + */ + private void publishDiffName(final ConfigurationDifference difference) { + diffTextArea.append(DIFF_NAME_LABEL); + diffTextArea.append(NEW_LINE); + diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); + diffTextArea.append(NEW_LINE); + diffTextArea.append(ACTUAL_VALUE_LABEL + " " + ModelerSession.getNotationService().getNotation(difference.getIdentifier()).getFullName()); + } + + /** + * Publishes different abbreviation. + * + * @param difference is the difference detail + */ + private void publishDiffAbbreviation(final ConfigurationDifference difference) { + diffTextArea.append(DIFF_ABBREVIATION_LABEL); + diffTextArea.append(NEW_LINE); + diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); + diffTextArea.append(NEW_LINE); + diffTextArea.append(ACTUAL_VALUE_LABEL + " " + ModelerSession.getNotationService().getNotation(difference.getIdentifier()).getAbbreviation()); + } + + /** + * Publishes different extension. + * + * @param difference is the difference detail + */ + private void publishDiffExtension(final ConfigurationDifference difference) { + diffTextArea.append(DIFF_EXTENSION_LABEL); + diffTextArea.append(NEW_LINE); + diffTextArea.append(LOADED_VALUE_LABEL +" " + difference.getMessage()); + diffTextArea.append(NEW_LINE); + diffTextArea.append( + ACTUAL_VALUE_LABEL + " " + ModelerSession.getNotationService().getNotation( + difference.getIdentifier() + ).getLocalIOController().getNotationFileExtension()); + } + + /** + * Publishes missing extension difference. + * + * @param difference is the difference detail + */ + private void publishMissingExtensionDiff(final ConfigurationDifference difference) { + diffTextArea.append(MISSING_EXTENSION_LABEL); + diffTextArea.append(NEW_LINE); + diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); + } + + /** + * Publishes missing module difference. + * + * @param difference is the difference detail + */ + private void publishMissingModuleDiff(final ConfigurationDifference difference) { + diffTextArea.append(MISSING_MODULE_LABEL); + diffTextArea.append(NEW_LINE); + + final Notation notation = ModelerSession.getNotationService().getNotation(difference.getIdentifier()); + if(notation != null){ + diffTextArea.append(RELATED_IDENTIFIER_LABEL + "" + notation.getFullName() + " (" + notation.getIdentifier() + ")."); + diffTextArea.append(NEW_LINE); + } else { + LOG.error("Unavailable notation for given identifier: " + difference.getIdentifier()); + } + + diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); + } + + /** + * Publishes missing notation difference. + * + * @param difference is the difference detail + */ + private void publishMissingNotationDiff(final ConfigurationDifference difference) { + diffTextArea.append(MISSING_NOTATION_LABEL); + diffTextArea.append(NEW_LINE); + diffTextArea.append(LOADED_VALUE_LABEL + " " + difference.getMessage()); + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/configurationChangeDialog/ConfigurationDiffDialogView.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/configurationChangeDialog/ConfigurationDiffDialogView.java index fe7de88..ff1a06b 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/configurationChangeDialog/ConfigurationDiffDialogView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/configurationChangeDialog/ConfigurationDiffDialogView.java @@ -1,68 +1,68 @@ -package cz.cvut.promod.gui.dialogs.configurationChangeDialog; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; - -import javax.swing.*; -import java.awt.*; - -import com.jgoodies.forms.factories.Borders; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:55:41, 12.12.2009 - * - * Represents the view component for ConfigurationDiffDialog. - */ -public class ConfigurationDiffDialogView extends JDialog { - - private static final Dimension DIMENSION = new Dimension(500, 450); - - private final JLabel titleLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.message") - ); - private final JLabel messageLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.message.detail") - ); - - protected final JTextArea diffTextArea = ModelerSession.getComponentFactoryService().createTextArea(); - - protected final JButton hideButton = ModelerSession.getComponentFactoryService().createButton( - ModelerSession.getCommonResourceBundle().getString("modeler.configuration.hideButton"), null - ); - - public ConfigurationDiffDialogView(){ - initLayout(); - - diffTextArea.setLineWrap(true); - diffTextArea.setWrapStyleWord(true); - - diffTextArea.setEditable(false); - - setSize(DIMENSION); - } - - private void initLayout() { - final JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); - - panel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - panel.setLayout(new BorderLayout()); - - final JPanel northPanel = ModelerSession.getComponentFactoryService().createPanel(); - northPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - northPanel.setLayout(new BorderLayout()); - - northPanel.add(titleLabel, BorderLayout.NORTH); - northPanel.add(messageLabel, BorderLayout.SOUTH); - - panel.add(northPanel, BorderLayout.NORTH); - panel.add(ModelerSession.getComponentFactoryService().createScrollPane(diffTextArea), BorderLayout.CENTER); - panel.add(hideButton, BorderLayout.SOUTH); - - setLayout(new BorderLayout()); - add(panel, BorderLayout.CENTER); - } - +package cz.cvut.promod.gui.dialogs.configurationChangeDialog; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; + +import javax.swing.*; +import java.awt.*; + +import com.jgoodies.forms.factories.Borders; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:55:41, 12.12.2009 + * + * Represents the view component for ConfigurationDiffDialog. + */ +public class ConfigurationDiffDialogView extends JDialog { + + private static final Dimension DIMENSION = new Dimension(500, 450); + + private final JLabel titleLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.message") + ); + private final JLabel messageLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.message.detail") + ); + + protected final JTextArea diffTextArea = ModelerSession.getComponentFactoryService().createTextArea(); + + protected final JButton hideButton = ModelerSession.getComponentFactoryService().createButton( + ModelerSession.getCommonResourceBundle().getString("modeler.configuration.hideButton"), null + ); + + public ConfigurationDiffDialogView(){ + initLayout(); + + diffTextArea.setLineWrap(true); + diffTextArea.setWrapStyleWord(true); + + diffTextArea.setEditable(false); + + setSize(DIMENSION); + } + + private void initLayout() { + final JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); + + panel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + panel.setLayout(new BorderLayout()); + + final JPanel northPanel = ModelerSession.getComponentFactoryService().createPanel(); + northPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + northPanel.setLayout(new BorderLayout()); + + northPanel.add(titleLabel, BorderLayout.NORTH); + northPanel.add(messageLabel, BorderLayout.SOUTH); + + panel.add(northPanel, BorderLayout.NORTH); + panel.add(ModelerSession.getComponentFactoryService().createScrollPane(diffTextArea), BorderLayout.CENTER); + panel.add(hideButton, BorderLayout.SOUTH); + + setLayout(new BorderLayout()); + add(panel, BorderLayout.CENTER); + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialog.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialog.java index 6d16a14..d4d78cb 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialog.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialog.java @@ -1,96 +1,96 @@ -package cz.cvut.promod.gui.dialogs.loadErrors; - -import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.*; -import java.util.List; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:55:32, 12.12.2009 - * - * Dialog displaying errors and error reasons that have occurred at load time. - */ -public class LoadErrorsDialog extends LoadErrorsDialogView{ - - public final String NEW_LINE = "\n"; - - private final LoadErrorsDialogModel model; - - public LoadErrorsDialog(final List errors){ - setTitle( - ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.title") - ); - - model = new LoadErrorsDialogModel(errors); - - initEventHandling(); - - initErrorReport(); - - setModal(true); - - getRootPane().setDefaultButton(hideButton); - - setVisible(true); - } - - /** - * Initialize event handling. - */ - private void initEventHandling() { - hideButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - disposeDialog(); - } - }); - - getRootPane().registerKeyboardAction(new ActionListener(){ - public void actionPerformed(ActionEvent actionEvent) { - disposeDialog(); - } - }, - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - } - - /** - * Hides the dialog. - */ - private void disposeDialog(){ - setVisible(false); - dispose(); - } - - /** - * Initialize error report. - */ - private void initErrorReport() { - for(final PluginLoadErrors pluginLoadErrors : model.getErrors()){ - - errorTextArea.append(LoadErrorsDialogModel.PROPERTY_NAME + " " + pluginLoadErrors.getAlias()); - errorTextArea.append(NEW_LINE); - - if(pluginLoadErrors.getFullClassName() != null){ - errorTextArea.append(LoadErrorsDialogModel.FULL_CLASS_NAME + " " + pluginLoadErrors.getFullClassName()); - errorTextArea.append(NEW_LINE); - } - - errorTextArea. append(LoadErrorsDialogModel.ERROR + " " + pluginLoadErrors.getTranslatedError()); - errorTextArea.append(NEW_LINE); - - if(pluginLoadErrors.getMessage() != null){ - errorTextArea.append(LoadErrorsDialogModel.MESSAGE + " " + pluginLoadErrors.getMessage()); - errorTextArea.append(NEW_LINE); - } - - errorTextArea.append(NEW_LINE); - } - } - -} +package cz.cvut.promod.gui.dialogs.loadErrors; + +import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.*; +import java.util.List; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:55:32, 12.12.2009 + * + * Dialog displaying errors and error reasons that have occurred at load time. + */ +public class LoadErrorsDialog extends LoadErrorsDialogView{ + + public final String NEW_LINE = "\n"; + + private final LoadErrorsDialogModel model; + + public LoadErrorsDialog(final List errors){ + setTitle( + ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.title") + ); + + model = new LoadErrorsDialogModel(errors); + + initEventHandling(); + + initErrorReport(); + + setModal(true); + + getRootPane().setDefaultButton(hideButton); + + setVisible(true); + } + + /** + * Initialize event handling. + */ + private void initEventHandling() { + hideButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + + getRootPane().registerKeyboardAction(new ActionListener(){ + public void actionPerformed(ActionEvent actionEvent) { + disposeDialog(); + } + }, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + } + + /** + * Hides the dialog. + */ + private void disposeDialog(){ + setVisible(false); + dispose(); + } + + /** + * Initialize error report. + */ + private void initErrorReport() { + for(final PluginLoadErrors pluginLoadErrors : model.getErrors()){ + + errorTextArea.append(LoadErrorsDialogModel.PROPERTY_NAME + " " + pluginLoadErrors.getAlias()); + errorTextArea.append(NEW_LINE); + + if(pluginLoadErrors.getFullClassName() != null){ + errorTextArea.append(LoadErrorsDialogModel.FULL_CLASS_NAME + " " + pluginLoadErrors.getFullClassName()); + errorTextArea.append(NEW_LINE); + } + + errorTextArea. append(LoadErrorsDialogModel.ERROR + " " + pluginLoadErrors.getTranslatedError()); + errorTextArea.append(NEW_LINE); + + if(pluginLoadErrors.getMessage() != null){ + errorTextArea.append(LoadErrorsDialogModel.MESSAGE + " " + pluginLoadErrors.getMessage()); + errorTextArea.append(NEW_LINE); + } + + errorTextArea.append(NEW_LINE); + } + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialogModel.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialogModel.java index a233a1b..cfd3cf5 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialogModel.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialogModel.java @@ -1,39 +1,39 @@ -package cz.cvut.promod.gui.dialogs.loadErrors; - -import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; -import cz.cvut.promod.services.ModelerSession; - -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:55:46, 12.12.2009 - * - * The model component for LoadErrorsDialog. - */ -public class LoadErrorsDialogModel { - - private final List errors; - - public static final String PROPERTY_NAME = - ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.propertyName"); - - public static final String FULL_CLASS_NAME = - ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.fullClassName"); - - public static final String ERROR = - ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.error"); - - public static final String MESSAGE = - ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.error.message"); - - - public LoadErrorsDialogModel(final List errors) { - this.errors = errors; - } - - public List getErrors() { - return errors; - } -} +package cz.cvut.promod.gui.dialogs.loadErrors; + +import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; +import cz.cvut.promod.services.ModelerSession; + +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:55:46, 12.12.2009 + * + * The model component for LoadErrorsDialog. + */ +public class LoadErrorsDialogModel { + + private final List errors; + + public static final String PROPERTY_NAME = + ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.propertyName"); + + public static final String FULL_CLASS_NAME = + ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.fullClassName"); + + public static final String ERROR = + ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.error"); + + public static final String MESSAGE = + ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.error.message"); + + + public LoadErrorsDialogModel(final List errors) { + this.errors = errors; + } + + public List getErrors() { + return errors; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialogView.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialogView.java index 5add994..312fd66 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialogView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/loadErrors/LoadErrorsDialogView.java @@ -1,69 +1,69 @@ -package cz.cvut.promod.gui.dialogs.loadErrors; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; - -import javax.swing.*; -import java.awt.*; - -import com.jgoodies.forms.factories.Borders; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:55:41, 12.12.2009 - * - * The view component for LoadErrorsDialog. - */ -public class LoadErrorsDialogView extends JDialog { - - private static final Dimension DIMENSION = new Dimension(500, 350); - - private final JLabel errorLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.message") - ); - - private final JLabel checkLogLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.log") - ); - - protected final JTextArea errorTextArea = ModelerSession.getComponentFactoryService().createTextArea(); - - protected final JButton hideButton = ModelerSession.getComponentFactoryService().createButton( - ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.hideButton"), null - ); - - public LoadErrorsDialogView(){ - initLayout(); - - errorTextArea.setLineWrap(true); - errorTextArea.setWrapStyleWord(true); - - errorTextArea.setEditable(false); - - setSize(DIMENSION); - } - - private void initLayout() { - final JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); - - panel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - panel.setLayout(new BorderLayout()); - - final JPanel northPanel = ModelerSession.getComponentFactoryService().createPanel(); - northPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - northPanel.setLayout(new BorderLayout()); - - northPanel.add(errorLabel, BorderLayout.NORTH); - northPanel.add(checkLogLabel, BorderLayout.SOUTH); - - panel.add(northPanel, BorderLayout.NORTH); - panel.add(ModelerSession.getComponentFactoryService().createScrollPane(errorTextArea), BorderLayout.CENTER); - panel.add(hideButton, BorderLayout.SOUTH); - - setLayout(new BorderLayout()); - add(panel, BorderLayout.CENTER); - } - -} +package cz.cvut.promod.gui.dialogs.loadErrors; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; + +import javax.swing.*; +import java.awt.*; + +import com.jgoodies.forms.factories.Borders; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:55:41, 12.12.2009 + * + * The view component for LoadErrorsDialog. + */ +public class LoadErrorsDialogView extends JDialog { + + private static final Dimension DIMENSION = new Dimension(500, 350); + + private final JLabel errorLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.message") + ); + + private final JLabel checkLogLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.log") + ); + + protected final JTextArea errorTextArea = ModelerSession.getComponentFactoryService().createTextArea(); + + protected final JButton hideButton = ModelerSession.getComponentFactoryService().createButton( + ModelerSession.getCommonResourceBundle().getString("modeler.loadErrorsDialog.hideButton"), null + ); + + public LoadErrorsDialogView(){ + initLayout(); + + errorTextArea.setLineWrap(true); + errorTextArea.setWrapStyleWord(true); + + errorTextArea.setEditable(false); + + setSize(DIMENSION); + } + + private void initLayout() { + final JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); + + panel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + panel.setLayout(new BorderLayout()); + + final JPanel northPanel = ModelerSession.getComponentFactoryService().createPanel(); + northPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + northPanel.setLayout(new BorderLayout()); + + northPanel.add(errorLabel, BorderLayout.NORTH); + northPanel.add(checkLogLabel, BorderLayout.SOUTH); + + panel.add(northPanel, BorderLayout.NORTH); + panel.add(ModelerSession.getComponentFactoryService().createScrollPane(errorTextArea), BorderLayout.CENTER); + panel.add(hideButton, BorderLayout.SOUTH); + + setLayout(new BorderLayout()); + add(panel, BorderLayout.CENTER); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialog.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialog.java index cb3dee1..c50b692 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialog.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialog.java @@ -1,203 +1,203 @@ -package cz.cvut.promod.gui.dialogs.newProject; - -import com.jgoodies.binding.adapter.Bindings; -import com.jgoodies.binding.PresentationModel; -import com.jgoodies.binding.value.ValueModel; - -import javax.swing.*; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.io.File; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeEvent; - -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.ProjectService; -import cz.cvut.promod.services.projectService.results.AddProjectItemResult; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.ModelerSession; -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:39:54, 20.10.2009 - * - * The new project dialog. - */ -public class NewProjectDialog extends NewProjectDialogView{ - - private final Logger LOG = Logger.getLogger(NewProjectDialog.class); - - private final NewProjectDialogModel model = new NewProjectDialogModel(); - private final PresentationModel presentation = new PresentationModel(model); - - final ValueModel projectNameModel = presentation.getModel(NewProjectDialogModel.PROPERTY_PROJECT_NAME); - final ValueModel projectLocationModel = presentation.getModel(NewProjectDialogModel.PROPERTY_PROJECT_LOCATION); - - public static String DUPLICITY_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.duplicity"); - public static String EXISTING_PROJECT_FILE_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.existing.file"); - public static String GENERAL_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.general"); - public static String RELATIVE_PATH_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.relative"); - - - public NewProjectDialog(){ - final JFrame frame = ModelerSession.getFrame(); - if(frame != null){ - setLocationRelativeTo(frame); - } - - setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - - initBinding(); - initEventHandling(); - - model.generateInitialProjectName(); - model.generateInitialProjectLocation(); - - getRootPane().setDefaultButton(createProjectButton); - - setVisible(true); - } - - /** - * Initialize bindings. - */ - private void initBinding() { - Bindings.bind(projectNameTextField, projectNameModel); - Bindings.bind(projectLocationTextField, projectLocationModel); - } - - /** - * Initialize event handling. - */ - private void initEventHandling() { - projectLocationButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - - final JFileChooser directoryChooser = new JFileChooser(); - directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - directoryChooser.setCurrentDirectory(new File(model.getProjectLocation())); - directoryChooser.setMultiSelectionEnabled(false); - - final int returnVal = directoryChooser.showDialog(centerPanel, "create a new project here"); - - if(returnVal == directoryChooser.getApproveButtonMnemonic()){ - model.setProjectLocation(directoryChooser.getSelectedFile().getAbsolutePath()); - } - - } - }); - - cancelButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - closeDialog(); - } - }); - - createProjectButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - final String projectName = model.getProjectName(); - - /** - * Test, whether there is no other files with ProMod project file extension. - */ - final File projectLocation = new File(model.getProjectLocation()); - - // do not take relative paths - if(!projectLocation.isAbsolute()){ - errorLabel.setText(RELATIVE_PATH_ERROR_LABEL); - return; - } - - if(projectLocation.exists()){ - for(final File file : projectLocation.listFiles()){ - if(file.getAbsolutePath().endsWith(ProjectService.PROJECT_FILE_EXTENSION)){ - LOG.error("Not possible to insert a new project file to an folder, where is already an existing file with project file extension."); - errorLabel.setText(EXISTING_PROJECT_FILE_ERROR_LABEL); - return; - } - } - } - - AddProjectItemResult addProjectItemResult = ModelerSession.getProjectControlService().addProject( - new ProjectRoot(projectName, model.getProjectLocation()), true - ); - - switch (addProjectItemResult.getStatus()){ - case SUCCESS: - LOG.info("New project has been created, project name: " + model.getProjectName() + ", project location: " + model.getProjectLocation() + "."); - closeDialog(); - - ModelerSession.getProjectControlService().synchronize( - addProjectItemResult.getTreePath(), - true, false, false, false - ); - - return; - case NAME_DUPLICITY: - LOG.error("Name duplicity error has occurred, " + projectName + ", " + model.getProjectLocation() + "."); - errorLabel.setText(DUPLICITY_ERROR_LABEL); - break; - case INVALID_NAME: - publicInvalidNameError(projectName); - break; - default: - LOG.error("Unknown AddProjectItemStatus return value."); - errorLabel.setText(GENERAL_ERROR_LABEL); - } - } - }); - - projectNameModel.addValueChangeListener(new PropertyChangeListener(){ - public void propertyChange(PropertyChangeEvent evt) { - final String projectLocation = (String) projectLocationModel.getValue(); - final String newProjectName = (String) evt.getNewValue(); - final String oldProjectName = (String) evt.getOldValue(); - - if(projectLocation != null && projectLocation.endsWith(System.getProperty("file.separator") + oldProjectName)){ - final String newProjectLocation = projectLocation.substring(0, projectLocation.length() - oldProjectName.length()) + newProjectName; - projectLocationModel.setValue(newProjectLocation); - } - } - }); - - getRootPane().registerKeyboardAction(new ActionListener(){ - public void actionPerformed(ActionEvent actionEvent) { - setVisible(false); - dispose(); - } - }, - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - } - - /** - * Shows the invalid name error - * @param projectName is the project name - */ - private void publicInvalidNameError(final String projectName) { - if(!ProjectServiceUtils.isSyntacticallyCorrectName(projectName)){ - errorLabel.setText( - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.disallowed") + - ProjectServiceUtils.getDisallowedNameSymbols(',') - ); - } else { - errorLabel.setText(ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.shortName")); - } - } - - /** - * Hides the dialog. - */ - private void closeDialog() { - setVisible(false); - dispose(); - } - -} +package cz.cvut.promod.gui.dialogs.newProject; + +import com.jgoodies.binding.adapter.Bindings; +import com.jgoodies.binding.PresentationModel; +import com.jgoodies.binding.value.ValueModel; + +import javax.swing.*; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.io.File; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeEvent; + +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.ProjectService; +import cz.cvut.promod.services.projectService.results.AddProjectItemResult; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.ModelerSession; +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:39:54, 20.10.2009 + * + * The new project dialog. + */ +public class NewProjectDialog extends NewProjectDialogView{ + + private final Logger LOG = Logger.getLogger(NewProjectDialog.class); + + private final NewProjectDialogModel model = new NewProjectDialogModel(); + private final PresentationModel presentation = new PresentationModel(model); + + final ValueModel projectNameModel = presentation.getModel(NewProjectDialogModel.PROPERTY_PROJECT_NAME); + final ValueModel projectLocationModel = presentation.getModel(NewProjectDialogModel.PROPERTY_PROJECT_LOCATION); + + public static String DUPLICITY_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.duplicity"); + public static String EXISTING_PROJECT_FILE_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.existing.file"); + public static String GENERAL_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.general"); + public static String RELATIVE_PATH_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.relative"); + + + public NewProjectDialog(){ + final JFrame frame = ModelerSession.getFrame(); + if(frame != null){ + setLocationRelativeTo(frame); + } + + setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + initBinding(); + initEventHandling(); + + model.generateInitialProjectName(); + model.generateInitialProjectLocation(); + + getRootPane().setDefaultButton(createProjectButton); + + setVisible(true); + } + + /** + * Initialize bindings. + */ + private void initBinding() { + Bindings.bind(projectNameTextField, projectNameModel); + Bindings.bind(projectLocationTextField, projectLocationModel); + } + + /** + * Initialize event handling. + */ + private void initEventHandling() { + projectLocationButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + + final JFileChooser directoryChooser = new JFileChooser(); + directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + directoryChooser.setCurrentDirectory(new File(model.getProjectLocation())); + directoryChooser.setMultiSelectionEnabled(false); + + final int returnVal = directoryChooser.showDialog(centerPanel, "create a new project here"); + + if(returnVal == directoryChooser.getApproveButtonMnemonic()){ + model.setProjectLocation(directoryChooser.getSelectedFile().getAbsolutePath()); + } + + } + }); + + cancelButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + closeDialog(); + } + }); + + createProjectButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + final String projectName = model.getProjectName(); + + /** + * Test, whether there is no other files with ProMod project file extension. + */ + final File projectLocation = new File(model.getProjectLocation()); + + // do not take relative paths + if(!projectLocation.isAbsolute()){ + errorLabel.setText(RELATIVE_PATH_ERROR_LABEL); + return; + } + + if(projectLocation.exists()){ + for(final File file : projectLocation.listFiles()){ + if(file.getAbsolutePath().endsWith(ProjectService.PROJECT_FILE_EXTENSION)){ + LOG.error("Not possible to insert a new project file to an folder, where is already an existing file with project file extension."); + errorLabel.setText(EXISTING_PROJECT_FILE_ERROR_LABEL); + return; + } + } + } + + AddProjectItemResult addProjectItemResult = ModelerSession.getProjectControlService().addProject( + new ProjectRoot(projectName, model.getProjectLocation()), true + ); + + switch (addProjectItemResult.getStatus()){ + case SUCCESS: + LOG.info("New project has been created, project name: " + model.getProjectName() + ", project location: " + model.getProjectLocation() + "."); + closeDialog(); + + ModelerSession.getProjectControlService().synchronize( + addProjectItemResult.getTreePath(), + true, false, false, false + ); + + return; + case NAME_DUPLICITY: + LOG.error("Name duplicity error has occurred, " + projectName + ", " + model.getProjectLocation() + "."); + errorLabel.setText(DUPLICITY_ERROR_LABEL); + break; + case INVALID_NAME: + publicInvalidNameError(projectName); + break; + default: + LOG.error("Unknown AddProjectItemStatus return value."); + errorLabel.setText(GENERAL_ERROR_LABEL); + } + } + }); + + projectNameModel.addValueChangeListener(new PropertyChangeListener(){ + public void propertyChange(PropertyChangeEvent evt) { + final String projectLocation = (String) projectLocationModel.getValue(); + final String newProjectName = (String) evt.getNewValue(); + final String oldProjectName = (String) evt.getOldValue(); + + if(projectLocation != null && projectLocation.endsWith(System.getProperty("file.separator") + oldProjectName)){ + final String newProjectLocation = projectLocation.substring(0, projectLocation.length() - oldProjectName.length()) + newProjectName; + projectLocationModel.setValue(newProjectLocation); + } + } + }); + + getRootPane().registerKeyboardAction(new ActionListener(){ + public void actionPerformed(ActionEvent actionEvent) { + setVisible(false); + dispose(); + } + }, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + } + + /** + * Shows the invalid name error + * @param projectName is the project name + */ + private void publicInvalidNameError(final String projectName) { + if(!ProjectServiceUtils.isSyntacticallyCorrectName(projectName)){ + errorLabel.setText( + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.disallowed") + + ProjectServiceUtils.getDisallowedNameSymbols(',') + ); + } else { + errorLabel.setText(ModelerSession.getCommonResourceBundle().getString("modeler.add.new.project.dialog.error.shortName")); + } + } + + /** + * Hides the dialog. + */ + private void closeDialog() { + setVisible(false); + dispose(); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialogModel.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialogModel.java index 9b100de..0393172 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialogModel.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialogModel.java @@ -1,78 +1,78 @@ -package cz.cvut.promod.gui.dialogs.newProject; - -import com.jgoodies.binding.beans.Model; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; - - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:40:17, 20.10.2009 - * - * The model component for NewProjectDialog. - */ -public class NewProjectDialogModel extends Model{ - - public static final String PROPERTY_PROJECT_LOCATION = "projectLocation"; - private String projectLocation; - - public static final String PROPERTY_PROJECT_NAME = "projectName"; - private String projectName; - - private static final String DEFAULT_PROJECT_NAME = "Project"; - private int projectNumber = 1; - - private static final String DEFAULT_PROJECT_DIRECTORY = "ProMod"; - - - /** - * Generates the initial name for new project. - */ - public void generateInitialProjectName() { - String projectName = DEFAULT_PROJECT_NAME + projectNumber; - - // test whether the is no open project with the same name as the implicit one - boolean testName; - do{ - testName = false; - for(final ProjectRoot projectRoot : ModelerSession.getProjectService().getProjects()){ - if(projectRoot.getDisplayName().equals(projectName)){ - testName = true; - ++projectNumber; - projectName = DEFAULT_PROJECT_NAME + projectNumber; - } - } - } while (testName); - - setProjectName(DEFAULT_PROJECT_NAME + projectNumber); - } - - public String getProjectLocation() { - return projectLocation; - } - - public void setProjectLocation(final String projectLocation) { - final String oldProjectLocation = this.projectLocation; - this.projectLocation = projectLocation; - firePropertyChange(PROPERTY_PROJECT_LOCATION, oldProjectLocation, projectLocation); - } - - public String getProjectName() { - return projectName; - } - - public void setProjectName(final String projectName) { - final String oldProjectName = this.projectName; - this.projectName = projectName; - firePropertyChange(PROPERTY_PROJECT_NAME, oldProjectName, projectName); - } - - public void generateInitialProjectLocation() { - setProjectLocation(System.getProperty("user.home") + - System.getProperty("file.separator") + - DEFAULT_PROJECT_DIRECTORY + - System.getProperty("file.separator") + - getProjectName()); - } -} +package cz.cvut.promod.gui.dialogs.newProject; + +import com.jgoodies.binding.beans.Model; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; + + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:40:17, 20.10.2009 + * + * The model component for NewProjectDialog. + */ +public class NewProjectDialogModel extends Model{ + + public static final String PROPERTY_PROJECT_LOCATION = "projectLocation"; + private String projectLocation; + + public static final String PROPERTY_PROJECT_NAME = "projectName"; + private String projectName; + + private static final String DEFAULT_PROJECT_NAME = "Project"; + private int projectNumber = 1; + + private static final String DEFAULT_PROJECT_DIRECTORY = "ProMod"; + + + /** + * Generates the initial name for new project. + */ + public void generateInitialProjectName() { + String projectName = DEFAULT_PROJECT_NAME + projectNumber; + + // test whether the is no open project with the same name as the implicit one + boolean testName; + do{ + testName = false; + for(final ProjectRoot projectRoot : ModelerSession.getProjectService().getProjects()){ + if(projectRoot.getDisplayName().equals(projectName)){ + testName = true; + ++projectNumber; + projectName = DEFAULT_PROJECT_NAME + projectNumber; + } + } + } while (testName); + + setProjectName(DEFAULT_PROJECT_NAME + projectNumber); + } + + public String getProjectLocation() { + return projectLocation; + } + + public void setProjectLocation(final String projectLocation) { + final String oldProjectLocation = this.projectLocation; + this.projectLocation = projectLocation; + firePropertyChange(PROPERTY_PROJECT_LOCATION, oldProjectLocation, projectLocation); + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(final String projectName) { + final String oldProjectName = this.projectName; + this.projectName = projectName; + firePropertyChange(PROPERTY_PROJECT_NAME, oldProjectName, projectName); + } + + public void generateInitialProjectLocation() { + setProjectLocation(System.getProperty("user.home") + + System.getProperty("file.separator") + + DEFAULT_PROJECT_DIRECTORY + + System.getProperty("file.separator") + + getProjectName()); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialogView.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialogView.java index ac214f7..974b5fe 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialogView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/newProject/NewProjectDialogView.java @@ -1,88 +1,88 @@ -package cz.cvut.promod.gui.dialogs.newProject; - -import com.jgoodies.forms.layout.FormLayout; -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.factories.Borders; - -import javax.swing.*; -import java.awt.*; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:40:04, 20.10.2009 - * - * The view component for NewProjectDialog. - */ -public class NewProjectDialogView extends JDialog { - - private final JLabel projectNameLabel = ModelerSession.getComponentFactoryService().createLabel("project name"); - protected final JTextField projectNameTextField = ModelerSession.getComponentFactoryService().createTextField(); - - private final JLabel projectLocationLabel = ModelerSession.getComponentFactoryService().createLabel("project location"); - protected final JTextField projectLocationTextField = ModelerSession.getComponentFactoryService().createTextField(); - protected final JButton projectLocationButton = ModelerSession.getComponentFactoryService().createButton("...", null); - - protected final JButton createProjectButton = ModelerSession.getComponentFactoryService().createButton("create project", null); - protected final JButton cancelButton = ModelerSession.getComponentFactoryService().createButton("cancel", null); - - protected final JLabel errorLabel = ModelerSession.getComponentFactoryService().createLabel(""); - - protected final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); - - public static final String TITLE = - ModelerSession.getCommonResourceBundle().getString("modeler.action.new.project.dialog"); - - public NewProjectDialogView(){ - setTitle(TITLE); - - setModal(true); - - errorLabel.setForeground(Color.RED); - - initLayout(); - - pack(); - } - - private void initLayout() { - centerPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - centerPanel.setLayout(new FormLayout( - "pref, 3dlu, max(180dlu;pref):grow, 3dlu, pref", - "pref, 3dlu, pref, 3dlu, pref, 20dlu") - ); - - int row = 1; - final CellConstraints cellConstraints = new CellConstraints(); - - centerPanel.add(projectNameLabel, cellConstraints.xy(1, row)); - centerPanel.add(projectNameTextField, cellConstraints.xyw(3, row, 3)); - - row += 2; - centerPanel.add(projectLocationLabel, cellConstraints.xy(1, row)); - centerPanel.add(projectLocationTextField, cellConstraints.xy(3, row)); - centerPanel.add(projectLocationButton, cellConstraints.xy(5, row)); - - - final JPanel southPanel = ModelerSession.getComponentFactoryService().createPanel(); - southPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - southPanel.setLayout(new FormLayout( - "pref, 50dlu:grow, pref", - "pref, 3dlu, pref" - )); - - southPanel.add(errorLabel, cellConstraints.xyw(1, 1, 3)); - - southPanel.add(cancelButton, cellConstraints.xy(1, 3)); - southPanel.add(createProjectButton, cellConstraints.xy(3, 3)); - - - setLayout(new BorderLayout()); - add(centerPanel, BorderLayout.CENTER); - add(southPanel, BorderLayout.SOUTH); - } - +package cz.cvut.promod.gui.dialogs.newProject; + +import com.jgoodies.forms.layout.FormLayout; +import com.jgoodies.forms.layout.CellConstraints; +import com.jgoodies.forms.factories.Borders; + +import javax.swing.*; +import java.awt.*; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:40:04, 20.10.2009 + * + * The view component for NewProjectDialog. + */ +public class NewProjectDialogView extends JDialog { + + private final JLabel projectNameLabel = ModelerSession.getComponentFactoryService().createLabel("project name"); + protected final JTextField projectNameTextField = ModelerSession.getComponentFactoryService().createTextField(); + + private final JLabel projectLocationLabel = ModelerSession.getComponentFactoryService().createLabel("project location"); + protected final JTextField projectLocationTextField = ModelerSession.getComponentFactoryService().createTextField(); + protected final JButton projectLocationButton = ModelerSession.getComponentFactoryService().createButton("...", null); + + protected final JButton createProjectButton = ModelerSession.getComponentFactoryService().createButton("create project", null); + protected final JButton cancelButton = ModelerSession.getComponentFactoryService().createButton("cancel", null); + + protected final JLabel errorLabel = ModelerSession.getComponentFactoryService().createLabel(""); + + protected final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); + + public static final String TITLE = + ModelerSession.getCommonResourceBundle().getString("modeler.action.new.project.dialog"); + + public NewProjectDialogView(){ + setTitle(TITLE); + + setModal(true); + + errorLabel.setForeground(Color.RED); + + initLayout(); + + pack(); + } + + private void initLayout() { + centerPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + centerPanel.setLayout(new FormLayout( + "pref, 3dlu, max(180dlu;pref):grow, 3dlu, pref", + "pref, 3dlu, pref, 3dlu, pref, 20dlu") + ); + + int row = 1; + final CellConstraints cellConstraints = new CellConstraints(); + + centerPanel.add(projectNameLabel, cellConstraints.xy(1, row)); + centerPanel.add(projectNameTextField, cellConstraints.xyw(3, row, 3)); + + row += 2; + centerPanel.add(projectLocationLabel, cellConstraints.xy(1, row)); + centerPanel.add(projectLocationTextField, cellConstraints.xy(3, row)); + centerPanel.add(projectLocationButton, cellConstraints.xy(5, row)); + + + final JPanel southPanel = ModelerSession.getComponentFactoryService().createPanel(); + southPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + southPanel.setLayout(new FormLayout( + "pref, 50dlu:grow, pref", + "pref, 3dlu, pref" + )); + + southPanel.add(errorLabel, cellConstraints.xyw(1, 1, 3)); + + southPanel.add(cancelButton, cellConstraints.xy(1, 3)); + southPanel.add(createProjectButton, cellConstraints.xy(3, 3)); + + + setLayout(new BorderLayout()); + add(centerPanel, BorderLayout.CENTER); + add(southPanel, BorderLayout.SOUTH); + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/PluginsOverviewDialogDialog.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/PluginsOverviewDialogDialog.java index 50c15af..680a10f 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/PluginsOverviewDialogDialog.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/PluginsOverviewDialogDialog.java @@ -1,91 +1,91 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview; - -import cz.cvut.promod.gui.dialogs.pluginsOverview.notations.NotationOverviewTab; -import cz.cvut.promod.gui.dialogs.pluginsOverview.extensions.ExtensionOverviewTab; -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.*; -import java.awt.event.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:38:19, 11.2.2010 - * - * Dialog for plugin overview. - */ -public class PluginsOverviewDialogDialog extends PluginsOverviewDialogView { - - public static final String TITLE = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview"); - public static final String NOTATION_AND_MODULE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.notations.title"); - public static final String EXTENSIONS_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.extension.title"); - public static final String IDENTIFIER_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.identifier"); - public static final String NAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.name"); - public static final String DESCRIPTION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.description"); - public static final String ABBREVIATION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.abbreviation"); - public static final String FULL_NAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.full.name"); - public static final String TOOL_TIP_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.tool.tip"); - public static final String FILE_EXTENSION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.file.ext"); - public static final String EXTENSION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugin.extension"); - public static final String NOTATION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugin.notation"); - public static final String MODULE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.plugin.module"); - - public PluginsOverviewDialogDialog(){ - initTabbedPane(); - - setModal(true); - - setTitle(TITLE); - - setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - - setLocationRelativeTo(ModelerSession.getFrame()); - - initEventHandling(); - - setVisible(true); - } - - private void initEventHandling() { - addWindowListener(new WindowAdapter(){ - public void windowClosing(WindowEvent e){ - disposeDialog(); - } - }); - - getRootPane().registerKeyboardAction(new ActionListener(){ - public void actionPerformed(ActionEvent actionEvent) { - disposeDialog(); - } - }, - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - } - - /** - * Hides the dialog. - */ - private void disposeDialog(){ - setVisible(false); - dispose(); - } - - private void initTabbedPane() { - tabbedPane.addTab(NOTATION_AND_MODULE_LABEL, null, new NotationOverviewTab()); - tabbedPane.addTab(EXTENSIONS_LABEL, null, new ExtensionOverviewTab()); - } - -} +package cz.cvut.promod.gui.dialogs.pluginsOverview; + +import cz.cvut.promod.gui.dialogs.pluginsOverview.notations.NotationOverviewTab; +import cz.cvut.promod.gui.dialogs.pluginsOverview.extensions.ExtensionOverviewTab; +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.*; +import java.awt.event.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:38:19, 11.2.2010 + * + * Dialog for plugin overview. + */ +public class PluginsOverviewDialogDialog extends PluginsOverviewDialogView { + + public static final String TITLE = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview"); + public static final String NOTATION_AND_MODULE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.notations.title"); + public static final String EXTENSIONS_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.extension.title"); + public static final String IDENTIFIER_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.identifier"); + public static final String NAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.name"); + public static final String DESCRIPTION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.description"); + public static final String ABBREVIATION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.abbreviation"); + public static final String FULL_NAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.full.name"); + public static final String TOOL_TIP_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.tool.tip"); + public static final String FILE_EXTENSION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugins.overview.file.ext"); + public static final String EXTENSION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugin.extension"); + public static final String NOTATION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugin.notation"); + public static final String MODULE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.plugin.module"); + + public PluginsOverviewDialogDialog(){ + initTabbedPane(); + + setModal(true); + + setTitle(TITLE); + + setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + setLocationRelativeTo(ModelerSession.getFrame()); + + initEventHandling(); + + setVisible(true); + } + + private void initEventHandling() { + addWindowListener(new WindowAdapter(){ + public void windowClosing(WindowEvent e){ + disposeDialog(); + } + }); + + getRootPane().registerKeyboardAction(new ActionListener(){ + public void actionPerformed(ActionEvent actionEvent) { + disposeDialog(); + } + }, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + } + + /** + * Hides the dialog. + */ + private void disposeDialog(){ + setVisible(false); + dispose(); + } + + private void initTabbedPane() { + tabbedPane.addTab(NOTATION_AND_MODULE_LABEL, null, new NotationOverviewTab()); + tabbedPane.addTab(EXTENSIONS_LABEL, null, new ExtensionOverviewTab()); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/PluginsOverviewDialogView.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/PluginsOverviewDialogView.java index 3f06057..d701779 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/PluginsOverviewDialogView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/PluginsOverviewDialogView.java @@ -1,47 +1,47 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; - -import javax.swing.*; -import java.awt.*; - -import com.jgoodies.forms.factories.Borders; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:38:25, 11.2.2010 - * - * Implementation of the PluginsOverview dialog. - */ -public class PluginsOverviewDialogView extends JDialog { - - public static int HGAP = 10; - public static int VGAP = 10; - - public static int LIST_WIDTH = 200; - - private static final Dimension DIMENSION = new Dimension(900, 600); - - protected JTabbedPane tabbedPane = ModelerSession.getComponentFactoryService().createTabbedPane(); - - - public PluginsOverviewDialogView(){ - setSize(DIMENSION); - - initLayout(); - } - - private void initLayout() { - final JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); - panel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - setLayout(new BorderLayout()); - add(panel, BorderLayout.CENTER); - - panel.setLayout(new BorderLayout()); - panel.add(tabbedPane); - } - -} +package cz.cvut.promod.gui.dialogs.pluginsOverview; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; + +import javax.swing.*; +import java.awt.*; + +import com.jgoodies.forms.factories.Borders; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:38:25, 11.2.2010 + * + * Implementation of the PluginsOverview dialog. + */ +public class PluginsOverviewDialogView extends JDialog { + + public static int HGAP = 10; + public static int VGAP = 10; + + public static int LIST_WIDTH = 200; + + private static final Dimension DIMENSION = new Dimension(900, 600); + + protected JTabbedPane tabbedPane = ModelerSession.getComponentFactoryService().createTabbedPane(); + + + public PluginsOverviewDialogView(){ + setSize(DIMENSION); + + initLayout(); + } + + private void initLayout() { + final JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); + panel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + setLayout(new BorderLayout()); + add(panel, BorderLayout.CENTER); + + panel.setLayout(new BorderLayout()); + panel.add(tabbedPane); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTab.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTab.java index 429c012..36be3b5 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTab.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTab.java @@ -1,61 +1,61 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview.extensions; - -import cz.cvut.promod.plugin.extension.Extension; -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.*; -import javax.swing.event.ListSelectionListener; -import javax.swing.event.ListSelectionEvent; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:49:59, 11.2.2010 - * - * Implementation of ExtensionOverviewTab for PluginsOverviewDialog. - */ -public class ExtensionOverviewTab extends ExtensionOverviewTabView { - - private static final Logger LOG = Logger.getLogger(ExtensionOverviewTab.class); - - private final ExtensionOverviewTabModel model; - - public ExtensionOverviewTab(){ - model = new ExtensionOverviewTabModel(); - - initList(); - - initEventHandling(); - } - - private void initEventHandling() { - extensionList.addListSelectionListener(new ListSelectionListener(){ - public void valueChanged(ListSelectionEvent e) { - final String extensionIdentifier = - ((ExtensionOverviewTabModel.ExtensionLabelWrapper)model.getElementAt(extensionList.getSelectedIndex())).getIdentifier(); - - updateDialogView(extensionIdentifier); - } - }); - } - - private void updateDialogView(final String extensionIdentifier) { - final Extension extension = ModelerSession.getExtensionService().getExtension(extensionIdentifier); - - if(extension != null){ - identifierTextArea.setText(extension.getIdentifier()); - nameTextArea.setText(extension.getName()); - descriptionTextArea.setText(extension.getDescription()); - } else { - LOG.error("Missing notation."); - } - } - - private void initList() { - extensionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - extensionList.setModel(model); - } - +package cz.cvut.promod.gui.dialogs.pluginsOverview.extensions; + +import cz.cvut.promod.plugin.extension.Extension; +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.*; +import javax.swing.event.ListSelectionListener; +import javax.swing.event.ListSelectionEvent; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:49:59, 11.2.2010 + * + * Implementation of ExtensionOverviewTab for PluginsOverviewDialog. + */ +public class ExtensionOverviewTab extends ExtensionOverviewTabView { + + private static final Logger LOG = Logger.getLogger(ExtensionOverviewTab.class); + + private final ExtensionOverviewTabModel model; + + public ExtensionOverviewTab(){ + model = new ExtensionOverviewTabModel(); + + initList(); + + initEventHandling(); + } + + private void initEventHandling() { + extensionList.addListSelectionListener(new ListSelectionListener(){ + public void valueChanged(ListSelectionEvent e) { + final String extensionIdentifier = + ((ExtensionOverviewTabModel.ExtensionLabelWrapper)model.getElementAt(extensionList.getSelectedIndex())).getIdentifier(); + + updateDialogView(extensionIdentifier); + } + }); + } + + private void updateDialogView(final String extensionIdentifier) { + final Extension extension = ModelerSession.getExtensionService().getExtension(extensionIdentifier); + + if(extension != null){ + identifierTextArea.setText(extension.getIdentifier()); + nameTextArea.setText(extension.getName()); + descriptionTextArea.setText(extension.getDescription()); + } else { + LOG.error("Missing notation."); + } + } + + private void initList() { + extensionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + extensionList.setModel(model); + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTabModel.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTabModel.java index 7e7a3be..154f1be 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTabModel.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTabModel.java @@ -1,73 +1,73 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview.extensions; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.plugin.extension.Extension; - -import javax.swing.*; -import javax.swing.event.ListDataListener; -import java.util.List; -import java.util.LinkedList; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:20:11, 11.2.2010 - * - * A Model component of ExtensionOverviewTab. - */ -public class ExtensionOverviewTabModel implements ListModel { - - private final List extensionsList; - - - public ExtensionOverviewTabModel() { - extensionsList = new LinkedList(); - - initList(); - } - - private void initList() { - for(final Extension extension : ModelerSession.getExtensionService().getExtensions()){ - extensionsList.add(new ExtensionLabelWrapper(extension.getIdentifier(), extension.getName())); - } - } - - public int getSize() { - return extensionsList.size(); - } - - public Object getElementAt(int index) { - return extensionsList.get(index); - } - - public void addListDataListener(ListDataListener l) { - - } - - public void removeListDataListener(ListDataListener l) { - - } - - /** - * Represents a list in list of extensions. - */ - protected static class ExtensionLabelWrapper { - - private final String identifier; - private final String displayName; - - private ExtensionLabelWrapper(final String identifier, final String displayName) { - this.identifier = identifier; - this.displayName = displayName; - } - - public String getIdentifier() { - return identifier; - } - - @Override - public String toString() { - return displayName; - } - } -} +package cz.cvut.promod.gui.dialogs.pluginsOverview.extensions; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.plugin.extension.Extension; + +import javax.swing.*; +import javax.swing.event.ListDataListener; +import java.util.List; +import java.util.LinkedList; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:20:11, 11.2.2010 + * + * A Model component of ExtensionOverviewTab. + */ +public class ExtensionOverviewTabModel implements ListModel { + + private final List extensionsList; + + + public ExtensionOverviewTabModel() { + extensionsList = new LinkedList(); + + initList(); + } + + private void initList() { + for(final Extension extension : ModelerSession.getExtensionService().getExtensions()){ + extensionsList.add(new ExtensionLabelWrapper(extension.getIdentifier(), extension.getName())); + } + } + + public int getSize() { + return extensionsList.size(); + } + + public Object getElementAt(int index) { + return extensionsList.get(index); + } + + public void addListDataListener(ListDataListener l) { + + } + + public void removeListDataListener(ListDataListener l) { + + } + + /** + * Represents a list in list of extensions. + */ + protected static class ExtensionLabelWrapper { + + private final String identifier; + private final String displayName; + + private ExtensionLabelWrapper(final String identifier, final String displayName) { + this.identifier = identifier; + this.displayName = displayName; + } + + public String getIdentifier() { + return identifier; + } + + @Override + public String toString() { + return displayName; + } + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTabView.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTabView.java index d3fe17f..857d933 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTabView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/extensions/ExtensionOverviewTabView.java @@ -1,85 +1,85 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview.extensions; - -import com.jgoodies.forms.factories.Borders; -import com.jgoodies.forms.layout.FormLayout; -import com.jgoodies.forms.layout.CellConstraints; - -import javax.swing.*; - -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogView; -import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogDialog; - -import java.awt.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:50:08, 11.2.2010 - * - * Tab for basic information demonstration about the extensions. - */ -public class ExtensionOverviewTabView extends JPanel { - - protected final JList extensionList = ModelerSession.getComponentFactoryService().createList(); - - private final JLabel identifierLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.IDENTIFIER_LABEL); - private final JLabel nameLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.NAME_LABEL); - private final JLabel descriptionLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.DESCRIPTION_LABEL); - private final JLabel extensionLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.EXTENSION_LABEL); - - protected final JTextField identifierTextArea = - ModelerSession.getComponentFactoryService().createTextField(); - protected final JTextField nameTextArea = - ModelerSession.getComponentFactoryService().createTextField(); - protected final JTextArea descriptionTextArea = - ModelerSession.getComponentFactoryService().createTextArea(); - - public ExtensionOverviewTabView(){ - identifierTextArea.setEditable(false); - nameTextArea.setEditable(false); - descriptionTextArea.setEditable(false); - - descriptionTextArea.setLineWrap(true); - descriptionTextArea.setWrapStyleWord(true); - - extensionList.setFixedCellWidth(PluginsOverviewDialogView.LIST_WIDTH); - - initLayout(); - } - - private void initLayout() { - setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); - centerPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - centerPanel.setLayout(new FormLayout( - "pref:grow", - "pref, 3dlu, pref, 7dlu, pref, 3dlu, pref, 7dlu, pref, 3dlu, fill:pref:grow" - )); - final CellConstraints cellConstraints = new CellConstraints(); - - centerPanel.add(identifierLabel, cellConstraints.xy(1,1)); - centerPanel.add(identifierTextArea, cellConstraints.xy(1,3)); - centerPanel.add(nameLabel, cellConstraints.xy(1,5)); - centerPanel.add(nameTextArea, cellConstraints.xy(1,7)); - centerPanel.add(descriptionLabel, cellConstraints.xy(1,9)); - centerPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(descriptionTextArea), cellConstraints.xy(1,11)); - - JPanel listPanel = ModelerSession.getComponentFactoryService().createPanel(); - listPanel.setLayout(new BorderLayout()); - listPanel.add(extensionLabel, BorderLayout.NORTH); - listPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(extensionList), BorderLayout.CENTER); - - setLayout(new BorderLayout(PluginsOverviewDialogView.HGAP, PluginsOverviewDialogView.HGAP)); - add(centerPanel, BorderLayout.CENTER); - add(listPanel, BorderLayout.WEST); - } - +package cz.cvut.promod.gui.dialogs.pluginsOverview.extensions; + +import com.jgoodies.forms.factories.Borders; +import com.jgoodies.forms.layout.FormLayout; +import com.jgoodies.forms.layout.CellConstraints; + +import javax.swing.*; + +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogView; +import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogDialog; + +import java.awt.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:50:08, 11.2.2010 + * + * Tab for basic information demonstration about the extensions. + */ +public class ExtensionOverviewTabView extends JPanel { + + protected final JList extensionList = ModelerSession.getComponentFactoryService().createList(); + + private final JLabel identifierLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.IDENTIFIER_LABEL); + private final JLabel nameLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.NAME_LABEL); + private final JLabel descriptionLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.DESCRIPTION_LABEL); + private final JLabel extensionLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.EXTENSION_LABEL); + + protected final JTextField identifierTextArea = + ModelerSession.getComponentFactoryService().createTextField(); + protected final JTextField nameTextArea = + ModelerSession.getComponentFactoryService().createTextField(); + protected final JTextArea descriptionTextArea = + ModelerSession.getComponentFactoryService().createTextArea(); + + public ExtensionOverviewTabView(){ + identifierTextArea.setEditable(false); + nameTextArea.setEditable(false); + descriptionTextArea.setEditable(false); + + descriptionTextArea.setLineWrap(true); + descriptionTextArea.setWrapStyleWord(true); + + extensionList.setFixedCellWidth(PluginsOverviewDialogView.LIST_WIDTH); + + initLayout(); + } + + private void initLayout() { + setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); + centerPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + centerPanel.setLayout(new FormLayout( + "pref:grow", + "pref, 3dlu, pref, 7dlu, pref, 3dlu, pref, 7dlu, pref, 3dlu, fill:pref:grow" + )); + final CellConstraints cellConstraints = new CellConstraints(); + + centerPanel.add(identifierLabel, cellConstraints.xy(1,1)); + centerPanel.add(identifierTextArea, cellConstraints.xy(1,3)); + centerPanel.add(nameLabel, cellConstraints.xy(1,5)); + centerPanel.add(nameTextArea, cellConstraints.xy(1,7)); + centerPanel.add(descriptionLabel, cellConstraints.xy(1,9)); + centerPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(descriptionTextArea), cellConstraints.xy(1,11)); + + JPanel listPanel = ModelerSession.getComponentFactoryService().createPanel(); + listPanel.setLayout(new BorderLayout()); + listPanel.add(extensionLabel, BorderLayout.NORTH); + listPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(extensionList), BorderLayout.CENTER); + + setLayout(new BorderLayout(PluginsOverviewDialogView.HGAP, PluginsOverviewDialogView.HGAP)); + add(centerPanel, BorderLayout.CENTER); + add(listPanel, BorderLayout.WEST); + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/ModuleListModel.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/ModuleListModel.java index c083e88..a8878de 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/ModuleListModel.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/ModuleListModel.java @@ -1,61 +1,61 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview.notations; - -import javax.swing.*; -import javax.swing.event.ListDataListener; -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 4:36:19, 17.4.2010 - * - * Holder of loaded module's info for NotationOverviewTab. - */ -public class ModuleListModel implements ListModel { - - private final List modulesList; - - public ModuleListModel(final List modulesList){ - this.modulesList = modulesList; - } - - public int getSize() { - return modulesList.size(); - } - - public Object getElementAt(int index) { - try{ - return modulesList.get(index); - } catch (IndexOutOfBoundsException e){ - return null; - } - } - - public void addListDataListener(ListDataListener l) {} - - public void removeListDataListener(ListDataListener l) {} - - - /** - * Represents a list in list of extensions. - */ - public static class ModuleLabelWrapper { - - private final String identifier; - private final String displayName; - - public ModuleLabelWrapper(final String identifier, final String displayName) { - this.identifier = identifier; - this.displayName = displayName; - } - - public String getIdentifier() { - return identifier; - } - - @Override - public String toString() { - return displayName; - } - } -} +package cz.cvut.promod.gui.dialogs.pluginsOverview.notations; + +import javax.swing.*; +import javax.swing.event.ListDataListener; +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 4:36:19, 17.4.2010 + * + * Holder of loaded module's info for NotationOverviewTab. + */ +public class ModuleListModel implements ListModel { + + private final List modulesList; + + public ModuleListModel(final List modulesList){ + this.modulesList = modulesList; + } + + public int getSize() { + return modulesList.size(); + } + + public Object getElementAt(int index) { + try{ + return modulesList.get(index); + } catch (IndexOutOfBoundsException e){ + return null; + } + } + + public void addListDataListener(ListDataListener l) {} + + public void removeListDataListener(ListDataListener l) {} + + + /** + * Represents a list in list of extensions. + */ + public static class ModuleLabelWrapper { + + private final String identifier; + private final String displayName; + + public ModuleLabelWrapper(final String identifier, final String displayName) { + this.identifier = identifier; + this.displayName = displayName; + } + + public String getIdentifier() { + return identifier; + } + + @Override + public String toString() { + return displayName; + } + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTab.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTab.java index c0a8168..8713038 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTab.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTab.java @@ -1,123 +1,123 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview.notations; - -import org.apache.log4j.Logger; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.event.ListSelectionListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:49:59, 11.2.2010 - * - * Implementation of NotationOverviewTab. - */ -public class NotationOverviewTab extends NotationOverviewTabView { - - private static final Logger LOG = Logger.getLogger(NotationOverviewTab.class); - - private final NotationOverviewTabModel model; - - /** holds the selected notation list item */ - private int selectedNotation = -1; - - - public NotationOverviewTab(){ - model = new NotationOverviewTabModel(); - - initList(); - - initEventHandling(); - } - - private void initEventHandling() { - notationsList.addListSelectionListener(new ListSelectionListener(){ - public void valueChanged(ListSelectionEvent e) { - if(notationsList.getSelectedIndex() > -1){ - final String notationIdentifier = - ((NotationOverviewTabModel.NotationLabelWrapper)model.getElementAt(notationsList.getSelectedIndex())).getIdentifier(); - - selectedNotation = notationsList.getSelectedIndex(); - - updateDialogView(notationIdentifier); - - modulesList.setModel( ((NotationOverviewTabModel.NotationLabelWrapper)model.getElementAt(notationsList.getSelectedIndex())).getModuleListModel()); - modulesList.setEnabled(true); - - notationsList.setSelectedIndex(selectedNotation); - } - } - }); - - modulesList.addListSelectionListener(new ListSelectionListener(){ - public void valueChanged(ListSelectionEvent e) { - final NotationOverviewTabModel.NotationLabelWrapper notationWrapper = - (NotationOverviewTabModel.NotationLabelWrapper) model.getElementAt(selectedNotation); - - notationsList.clearSelection(); - - final String notationIdentifier = notationWrapper.getIdentifier(); - - final ModuleListModel.ModuleLabelWrapper moduleWrapper = - (ModuleListModel.ModuleLabelWrapper) notationWrapper.getModuleListModel().getElementAt(modulesList.getSelectedIndex()); - - if(moduleWrapper != null){ - updateDialogView(notationIdentifier, moduleWrapper.getIdentifier()); - } - } - }); - } - - private void updateDialogView(final String notationIdentifier, final String moduleIdentifier) { - Module module = null; - try{ - module = ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier).getModule(moduleIdentifier); - } catch (Exception e){ - LOG.error("Not valid identifier data"); - identifierTextArea.setText(null); - nameTextArea.setText(null); - descriptionTextArea.setText(null); - } - - if(module != null){ - identifierTextArea.setText(module.getIdentifier()); - fullNameTextArea.setText(null); - nameTextArea.setText(module.getName()); - abbreviationTextArea.setText(null); - toolTipTextArea.setText(null); - fileExtensionTextArea.setText(null); - descriptionTextArea.setText(module.getDescription()); - - } else { - LOG.error("Missing module."); - } - } - - private void updateDialogView(final String notationIdentifier) { - final Notation notation = ModelerSession.getNotationService().getNotation(notationIdentifier); - - if(notation != null){ - identifierTextArea.setText(notation.getIdentifier()); - fullNameTextArea.setText(notation.getFullName()); - nameTextArea.setText(notation.getName()); - abbreviationTextArea.setText(notation.getAbbreviation()); - toolTipTextArea.setText(notation.getNotationToolTip()); - fileExtensionTextArea.setText(notation.getLocalIOController().getNotationFileExtension()); - descriptionTextArea.setText(notation.getDescription()); - - } else { - LOG.error("Missing notation."); - } - } - - private void initList() { - notationsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - notationsList.setModel(model); - - modulesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - } -} +package cz.cvut.promod.gui.dialogs.pluginsOverview.notations; + +import org.apache.log4j.Logger; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.event.ListSelectionListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:49:59, 11.2.2010 + * + * Implementation of NotationOverviewTab. + */ +public class NotationOverviewTab extends NotationOverviewTabView { + + private static final Logger LOG = Logger.getLogger(NotationOverviewTab.class); + + private final NotationOverviewTabModel model; + + /** holds the selected notation list item */ + private int selectedNotation = -1; + + + public NotationOverviewTab(){ + model = new NotationOverviewTabModel(); + + initList(); + + initEventHandling(); + } + + private void initEventHandling() { + notationsList.addListSelectionListener(new ListSelectionListener(){ + public void valueChanged(ListSelectionEvent e) { + if(notationsList.getSelectedIndex() > -1){ + final String notationIdentifier = + ((NotationOverviewTabModel.NotationLabelWrapper)model.getElementAt(notationsList.getSelectedIndex())).getIdentifier(); + + selectedNotation = notationsList.getSelectedIndex(); + + updateDialogView(notationIdentifier); + + modulesList.setModel( ((NotationOverviewTabModel.NotationLabelWrapper)model.getElementAt(notationsList.getSelectedIndex())).getModuleListModel()); + modulesList.setEnabled(true); + + notationsList.setSelectedIndex(selectedNotation); + } + } + }); + + modulesList.addListSelectionListener(new ListSelectionListener(){ + public void valueChanged(ListSelectionEvent e) { + final NotationOverviewTabModel.NotationLabelWrapper notationWrapper = + (NotationOverviewTabModel.NotationLabelWrapper) model.getElementAt(selectedNotation); + + notationsList.clearSelection(); + + final String notationIdentifier = notationWrapper.getIdentifier(); + + final ModuleListModel.ModuleLabelWrapper moduleWrapper = + (ModuleListModel.ModuleLabelWrapper) notationWrapper.getModuleListModel().getElementAt(modulesList.getSelectedIndex()); + + if(moduleWrapper != null){ + updateDialogView(notationIdentifier, moduleWrapper.getIdentifier()); + } + } + }); + } + + private void updateDialogView(final String notationIdentifier, final String moduleIdentifier) { + Module module = null; + try{ + module = ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier).getModule(moduleIdentifier); + } catch (Exception e){ + LOG.error("Not valid identifier data"); + identifierTextArea.setText(null); + nameTextArea.setText(null); + descriptionTextArea.setText(null); + } + + if(module != null){ + identifierTextArea.setText(module.getIdentifier()); + fullNameTextArea.setText(null); + nameTextArea.setText(module.getName()); + abbreviationTextArea.setText(null); + toolTipTextArea.setText(null); + fileExtensionTextArea.setText(null); + descriptionTextArea.setText(module.getDescription()); + + } else { + LOG.error("Missing module."); + } + } + + private void updateDialogView(final String notationIdentifier) { + final Notation notation = ModelerSession.getNotationService().getNotation(notationIdentifier); + + if(notation != null){ + identifierTextArea.setText(notation.getIdentifier()); + fullNameTextArea.setText(notation.getFullName()); + nameTextArea.setText(notation.getName()); + abbreviationTextArea.setText(notation.getAbbreviation()); + toolTipTextArea.setText(notation.getNotationToolTip()); + fileExtensionTextArea.setText(notation.getLocalIOController().getNotationFileExtension()); + descriptionTextArea.setText(notation.getDescription()); + + } else { + LOG.error("Missing notation."); + } + } + + private void initList() { + notationsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + notationsList.setModel(model); + + modulesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTabModel.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTabModel.java index 3168eaf..d1c4666 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTabModel.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTabModel.java @@ -1,94 +1,94 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview.notations; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; -import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; - -import javax.swing.event.ListDataListener; -import javax.swing.*; -import java.util.List; -import java.util.LinkedList; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 18:00:07, 11.2.2010 - * - * A Module component of NotationOverviewTab. - */ -public class NotationOverviewTabModel implements ListModel { - - private final List notationsList; - - - public NotationOverviewTabModel() { - notationsList = new LinkedList(); - - initList(); - } - - private void initList(){ - for(final String identifier : ModelerSession.getNotationService().getNotationsIdentifiers()){ - final NotationSpecificPlugins specificPlugins = ModelerSession.getNotationService().getNotationSpecificPlugins(identifier); - final List modulesList = new LinkedList(); - for(final Module module : specificPlugins.getModules()){ - modulesList.add(new ModuleListModel.ModuleLabelWrapper(module.getIdentifier(), module.getName())); - } - - notationsList.add(new NotationLabelWrapper( - specificPlugins.getNotation().getIdentifier(), specificPlugins.getNotation().getFullName(), new ModuleListModel(modulesList) - )); - } - } - - public int getSize() { - return notationsList.size(); - } - - public Object getElementAt(int index) { - return notationsList.get(index); - } - - public void addListDataListener(ListDataListener l) { - - } - - public void removeListDataListener(ListDataListener l) { - - } - - /** - * Represents a list in list of notations. - */ - protected static class NotationLabelWrapper { - - private final String identifier; - private final String displayName; - - private final ModuleListModel moduleListModel; - - private NotationLabelWrapper(final String identifier, - final String displayName, - final ModuleListModel moduleListModel) { - - this.identifier = identifier; - this.displayName = displayName; - this.moduleListModel = moduleListModel; - } - - public String getIdentifier() { - return identifier; - } - - @Override - public String toString() { - return displayName; - } - - public ModuleListModel getModuleListModel() { - return moduleListModel; - } - } - - -} +package cz.cvut.promod.gui.dialogs.pluginsOverview.notations; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; +import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; + +import javax.swing.event.ListDataListener; +import javax.swing.*; +import java.util.List; +import java.util.LinkedList; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 18:00:07, 11.2.2010 + * + * A Module component of NotationOverviewTab. + */ +public class NotationOverviewTabModel implements ListModel { + + private final List notationsList; + + + public NotationOverviewTabModel() { + notationsList = new LinkedList(); + + initList(); + } + + private void initList(){ + for(final String identifier : ModelerSession.getNotationService().getNotationsIdentifiers()){ + final NotationSpecificPlugins specificPlugins = ModelerSession.getNotationService().getNotationSpecificPlugins(identifier); + final List modulesList = new LinkedList(); + for(final Module module : specificPlugins.getModules()){ + modulesList.add(new ModuleListModel.ModuleLabelWrapper(module.getIdentifier(), module.getName())); + } + + notationsList.add(new NotationLabelWrapper( + specificPlugins.getNotation().getIdentifier(), specificPlugins.getNotation().getFullName(), new ModuleListModel(modulesList) + )); + } + } + + public int getSize() { + return notationsList.size(); + } + + public Object getElementAt(int index) { + return notationsList.get(index); + } + + public void addListDataListener(ListDataListener l) { + + } + + public void removeListDataListener(ListDataListener l) { + + } + + /** + * Represents a list in list of notations. + */ + protected static class NotationLabelWrapper { + + private final String identifier; + private final String displayName; + + private final ModuleListModel moduleListModel; + + private NotationLabelWrapper(final String identifier, + final String displayName, + final ModuleListModel moduleListModel) { + + this.identifier = identifier; + this.displayName = displayName; + this.moduleListModel = moduleListModel; + } + + public String getIdentifier() { + return identifier; + } + + @Override + public String toString() { + return displayName; + } + + public ModuleListModel getModuleListModel() { + return moduleListModel; + } + } + + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTabView.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTabView.java index 7717475..ae0b723 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTabView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/pluginsOverview/notations/NotationOverviewTabView.java @@ -1,150 +1,150 @@ -package cz.cvut.promod.gui.dialogs.pluginsOverview.notations; - -import com.jgoodies.forms.factories.Borders; -import com.jgoodies.forms.layout.FormLayout; -import com.jgoodies.forms.layout.CellConstraints; - -import javax.swing.*; - -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogView; -import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogDialog; - -import java.awt.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:50:08, 11.2.2010 - * - * A View component of NotationOverviewTab. - */ - -public class NotationOverviewTabView extends JPanel { - - - protected final JList notationsList = ModelerSession.getComponentFactoryService().createList(); - protected final JList modulesList = ModelerSession.getComponentFactoryService().createList(); - - private final JLabel identifierLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.IDENTIFIER_LABEL); - private final JLabel nameLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.NAME_LABEL); - private final JLabel descriptionLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.DESCRIPTION_LABEL); - private final JLabel abbreviationLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.ABBREVIATION_LABEL); - private final JLabel fullNameLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.FULL_NAME_LABEL); - private final JLabel toolTipLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.TOOL_TIP_LABEL); - private final JLabel fileExtensionLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.FILE_EXTENSION_LABEL); - private final JLabel notationLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.NOTATION_LABEL); - private final JLabel moduleLabel = - ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.MODULE_LABEL); - - protected final JTextField identifierTextArea = - ModelerSession.getComponentFactoryService().createTextField(); - protected final JTextField nameTextArea = - ModelerSession.getComponentFactoryService().createTextField(); - protected final JTextField fullNameTextArea = - ModelerSession.getComponentFactoryService().createTextField(); - protected final JTextArea descriptionTextArea = - ModelerSession.getComponentFactoryService().createTextArea(); - protected final JTextField abbreviationTextArea = - ModelerSession.getComponentFactoryService().createTextField(); - protected final JTextField toolTipTextArea = - ModelerSession.getComponentFactoryService().createTextField(); - protected final JTextField fileExtensionTextArea = - ModelerSession.getComponentFactoryService().createTextField(); - - - public NotationOverviewTabView(){ - identifierTextArea.setEditable(false); - fullNameTextArea.setEditable(false); - nameTextArea.setEditable(false); - abbreviationTextArea.setEditable(false); - toolTipTextArea.setEditable(false); - fileExtensionTextArea.setEditable(false); - descriptionTextArea.setEditable(false); - - descriptionTextArea.setLineWrap(true); - descriptionTextArea.setWrapStyleWord(true); - - notationsList.setFixedCellWidth(PluginsOverviewDialogView.LIST_WIDTH); - modulesList.setFixedCellWidth(PluginsOverviewDialogView.LIST_WIDTH); - - initLayout(); - } - - private void initLayout() { - setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - final JPanel topCenterPanel = ModelerSession.getComponentFactoryService().createPanel(); - topCenterPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - topCenterPanel.setLayout(new FormLayout( - "pref, 3dlu, pref:grow", - "pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 10dlu, pref" - )); - final CellConstraints cellConstraints = new CellConstraints(); - - int row = 1; - topCenterPanel.add(identifierLabel, cellConstraints.xy(1,row)); - topCenterPanel.add(identifierTextArea, cellConstraints.xy(3,row)); - - row += 2; - topCenterPanel.add(nameLabel, cellConstraints.xy(1,row)); - topCenterPanel.add(nameTextArea, cellConstraints.xy(3,row)); - - row += 2; - topCenterPanel.add(fullNameLabel, cellConstraints.xy(1,row)); - topCenterPanel.add(fullNameTextArea, cellConstraints.xy(3,row)); - - row += 2; - topCenterPanel.add(abbreviationLabel, cellConstraints.xy(1,row)); - topCenterPanel.add(abbreviationTextArea, cellConstraints.xy(3,row)); - - row += 2; - topCenterPanel.add(toolTipLabel, cellConstraints.xy(1,row)); - topCenterPanel.add(toolTipTextArea, cellConstraints.xy(3,row)); - - row += 2; - topCenterPanel.add(fileExtensionLabel, cellConstraints.xy(1,row)); - topCenterPanel.add(fileExtensionTextArea, cellConstraints.xy(3,row)); - - row += 2; - topCenterPanel.add(descriptionLabel, cellConstraints.xy(1,row)); - - final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); - centerPanel.setLayout(new BorderLayout()); - - centerPanel.add(topCenterPanel, BorderLayout.NORTH); - centerPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(descriptionTextArea)); - - setLayout(new BorderLayout(PluginsOverviewDialogView.HGAP, PluginsOverviewDialogView.HGAP)); - - final JPanel listsNotationPanel = ModelerSession.getComponentFactoryService().createPanel(); - listsNotationPanel.setLayout(new BorderLayout()); - listsNotationPanel.add(notationLabel, BorderLayout.NORTH); - listsNotationPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(notationsList), BorderLayout.CENTER); - - final JPanel listsModulePanel = ModelerSession.getComponentFactoryService().createPanel(); - listsModulePanel.setLayout(new BorderLayout()); - listsModulePanel.add(moduleLabel, BorderLayout.NORTH); - listsModulePanel.add(ModelerSession.getComponentFactoryService().createScrollPane(modulesList), BorderLayout.CENTER); - - final JPanel listsPanel = ModelerSession.getComponentFactoryService().createPanel(); - listsPanel.setLayout(new BorderLayout(PluginsOverviewDialogView.HGAP, PluginsOverviewDialogView.HGAP)); - listsPanel.add(listsNotationPanel, BorderLayout.WEST); - listsPanel.add(listsModulePanel, BorderLayout.EAST); - - add(centerPanel, BorderLayout.CENTER); - add(listsPanel, BorderLayout.WEST); - } - - -} +package cz.cvut.promod.gui.dialogs.pluginsOverview.notations; + +import com.jgoodies.forms.factories.Borders; +import com.jgoodies.forms.layout.FormLayout; +import com.jgoodies.forms.layout.CellConstraints; + +import javax.swing.*; + +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogView; +import cz.cvut.promod.gui.dialogs.pluginsOverview.PluginsOverviewDialogDialog; + +import java.awt.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:50:08, 11.2.2010 + * + * A View component of NotationOverviewTab. + */ + +public class NotationOverviewTabView extends JPanel { + + + protected final JList notationsList = ModelerSession.getComponentFactoryService().createList(); + protected final JList modulesList = ModelerSession.getComponentFactoryService().createList(); + + private final JLabel identifierLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.IDENTIFIER_LABEL); + private final JLabel nameLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.NAME_LABEL); + private final JLabel descriptionLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.DESCRIPTION_LABEL); + private final JLabel abbreviationLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.ABBREVIATION_LABEL); + private final JLabel fullNameLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.FULL_NAME_LABEL); + private final JLabel toolTipLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.TOOL_TIP_LABEL); + private final JLabel fileExtensionLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.FILE_EXTENSION_LABEL); + private final JLabel notationLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.NOTATION_LABEL); + private final JLabel moduleLabel = + ModelerSession.getComponentFactoryService().createLabel(PluginsOverviewDialogDialog.MODULE_LABEL); + + protected final JTextField identifierTextArea = + ModelerSession.getComponentFactoryService().createTextField(); + protected final JTextField nameTextArea = + ModelerSession.getComponentFactoryService().createTextField(); + protected final JTextField fullNameTextArea = + ModelerSession.getComponentFactoryService().createTextField(); + protected final JTextArea descriptionTextArea = + ModelerSession.getComponentFactoryService().createTextArea(); + protected final JTextField abbreviationTextArea = + ModelerSession.getComponentFactoryService().createTextField(); + protected final JTextField toolTipTextArea = + ModelerSession.getComponentFactoryService().createTextField(); + protected final JTextField fileExtensionTextArea = + ModelerSession.getComponentFactoryService().createTextField(); + + + public NotationOverviewTabView(){ + identifierTextArea.setEditable(false); + fullNameTextArea.setEditable(false); + nameTextArea.setEditable(false); + abbreviationTextArea.setEditable(false); + toolTipTextArea.setEditable(false); + fileExtensionTextArea.setEditable(false); + descriptionTextArea.setEditable(false); + + descriptionTextArea.setLineWrap(true); + descriptionTextArea.setWrapStyleWord(true); + + notationsList.setFixedCellWidth(PluginsOverviewDialogView.LIST_WIDTH); + modulesList.setFixedCellWidth(PluginsOverviewDialogView.LIST_WIDTH); + + initLayout(); + } + + private void initLayout() { + setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + final JPanel topCenterPanel = ModelerSession.getComponentFactoryService().createPanel(); + topCenterPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + topCenterPanel.setLayout(new FormLayout( + "pref, 3dlu, pref:grow", + "pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 10dlu, pref" + )); + final CellConstraints cellConstraints = new CellConstraints(); + + int row = 1; + topCenterPanel.add(identifierLabel, cellConstraints.xy(1,row)); + topCenterPanel.add(identifierTextArea, cellConstraints.xy(3,row)); + + row += 2; + topCenterPanel.add(nameLabel, cellConstraints.xy(1,row)); + topCenterPanel.add(nameTextArea, cellConstraints.xy(3,row)); + + row += 2; + topCenterPanel.add(fullNameLabel, cellConstraints.xy(1,row)); + topCenterPanel.add(fullNameTextArea, cellConstraints.xy(3,row)); + + row += 2; + topCenterPanel.add(abbreviationLabel, cellConstraints.xy(1,row)); + topCenterPanel.add(abbreviationTextArea, cellConstraints.xy(3,row)); + + row += 2; + topCenterPanel.add(toolTipLabel, cellConstraints.xy(1,row)); + topCenterPanel.add(toolTipTextArea, cellConstraints.xy(3,row)); + + row += 2; + topCenterPanel.add(fileExtensionLabel, cellConstraints.xy(1,row)); + topCenterPanel.add(fileExtensionTextArea, cellConstraints.xy(3,row)); + + row += 2; + topCenterPanel.add(descriptionLabel, cellConstraints.xy(1,row)); + + final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); + centerPanel.setLayout(new BorderLayout()); + + centerPanel.add(topCenterPanel, BorderLayout.NORTH); + centerPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(descriptionTextArea)); + + setLayout(new BorderLayout(PluginsOverviewDialogView.HGAP, PluginsOverviewDialogView.HGAP)); + + final JPanel listsNotationPanel = ModelerSession.getComponentFactoryService().createPanel(); + listsNotationPanel.setLayout(new BorderLayout()); + listsNotationPanel.add(notationLabel, BorderLayout.NORTH); + listsNotationPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(notationsList), BorderLayout.CENTER); + + final JPanel listsModulePanel = ModelerSession.getComponentFactoryService().createPanel(); + listsModulePanel.setLayout(new BorderLayout()); + listsModulePanel.add(moduleLabel, BorderLayout.NORTH); + listsModulePanel.add(ModelerSession.getComponentFactoryService().createScrollPane(modulesList), BorderLayout.CENTER); + + final JPanel listsPanel = ModelerSession.getComponentFactoryService().createPanel(); + listsPanel.setLayout(new BorderLayout(PluginsOverviewDialogView.HGAP, PluginsOverviewDialogView.HGAP)); + listsPanel.add(listsNotationPanel, BorderLayout.WEST); + listsPanel.add(listsModulePanel, BorderLayout.EAST); + + add(centerPanel, BorderLayout.CENTER); + add(listsPanel, BorderLayout.WEST); + } + + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialog.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialog.java index 4cf58ca..d4dc8ba 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialog.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialog.java @@ -1,100 +1,100 @@ -package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog; - -import com.jgoodies.binding.adapter.Bindings; -import com.jgoodies.binding.PresentationModel; - -import javax.swing.*; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.awt.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:49:43, 23.10.2009 - * - * A implementation of SimpleTextFieldDialog. - */ -public class SimpleTextFieldDialog extends SimpleTextFieldDialogView{ - - private final SimpleTextFieldDialogModel model = new SimpleTextFieldDialogModel(); - - private final PresentationModel presentation = new PresentationModel(model); - - private final SimpleTextFieldDialogExecutor executor; - - - public SimpleTextFieldDialog(final String title, - final String textLabelString, - final String inputTextFieldText, - final String confirmButtonText, - final String cancelButtonString, - final SimpleTextFieldDialogExecutor executor, - final Component locateRelativeToComponent, - final boolean modal){ - - if(locateRelativeToComponent != null){ - setLocationRelativeTo(locateRelativeToComponent); - } - - //init texts - setTitle(title); - - textLabel.setText(textLabelString); - confirmButton.setText(confirmButtonText); - cancelButton.setText(cancelButtonString); - - this.executor = executor; - - initBinding(); - - inputTextField.setText(inputTextFieldText); - - setModal(modal); - - initEventHandling(); - - getRootPane().setDefaultButton(confirmButton); - - setVisible(true); - } - - private void initBinding() { - Bindings.bind(inputTextField, presentation.getModel(SimpleTextFieldDialogModel.PROPERTY_SUBFOLDER_NAME)); - } - - private void initEventHandling() { - cancelButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - disposeDialog(); - } - }); - - confirmButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - final String result = executor.execute(model.getInputText()); - - if(result == null){ - disposeDialog(); - } else { - errorLabel.setText(result); - } - } - }); - - getRootPane().registerKeyboardAction(new ActionListener(){ - public void actionPerformed(ActionEvent actionEvent) { - disposeDialog(); - } - }, - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - } - - private void disposeDialog(){ - setVisible(false); - dispose(); - } - -} +package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog; + +import com.jgoodies.binding.adapter.Bindings; +import com.jgoodies.binding.PresentationModel; + +import javax.swing.*; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.awt.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:49:43, 23.10.2009 + * + * A implementation of SimpleTextFieldDialog. + */ +public class SimpleTextFieldDialog extends SimpleTextFieldDialogView{ + + private final SimpleTextFieldDialogModel model = new SimpleTextFieldDialogModel(); + + private final PresentationModel presentation = new PresentationModel(model); + + private final SimpleTextFieldDialogExecutor executor; + + + public SimpleTextFieldDialog(final String title, + final String textLabelString, + final String inputTextFieldText, + final String confirmButtonText, + final String cancelButtonString, + final SimpleTextFieldDialogExecutor executor, + final Component locateRelativeToComponent, + final boolean modal){ + + if(locateRelativeToComponent != null){ + setLocationRelativeTo(locateRelativeToComponent); + } + + //init texts + setTitle(title); + + textLabel.setText(textLabelString); + confirmButton.setText(confirmButtonText); + cancelButton.setText(cancelButtonString); + + this.executor = executor; + + initBinding(); + + inputTextField.setText(inputTextFieldText); + + setModal(modal); + + initEventHandling(); + + getRootPane().setDefaultButton(confirmButton); + + setVisible(true); + } + + private void initBinding() { + Bindings.bind(inputTextField, presentation.getModel(SimpleTextFieldDialogModel.PROPERTY_SUBFOLDER_NAME)); + } + + private void initEventHandling() { + cancelButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + + confirmButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + final String result = executor.execute(model.getInputText()); + + if(result == null){ + disposeDialog(); + } else { + errorLabel.setText(result); + } + } + }); + + getRootPane().registerKeyboardAction(new ActionListener(){ + public void actionPerformed(ActionEvent actionEvent) { + disposeDialog(); + } + }, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + } + + private void disposeDialog(){ + setVisible(false); + dispose(); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogExecutor.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogExecutor.java index 4b1b0d9..0161aff 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogExecutor.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogExecutor.java @@ -1,12 +1,12 @@ -package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 0:26:07, 24.10.2009 - */ -public interface SimpleTextFieldDialogExecutor { - - public String execute(final String text); - -} +package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 0:26:07, 24.10.2009 + */ +public interface SimpleTextFieldDialogExecutor { + + public String execute(final String text); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogModel.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogModel.java index b746f78..668f9c4 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogModel.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogModel.java @@ -1,26 +1,26 @@ -package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog; - -import com.jgoodies.binding.beans.Model; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:49:58, 23.10.2009 - * - * A Model component for SimpleTextFieldDialog. - */ -public class SimpleTextFieldDialogModel extends Model { - - public static final String PROPERTY_SUBFOLDER_NAME = "inputText"; - private String inputText; - - public String getInputText() { - return inputText; - } - - public void setInputText(final String inputText) { - final String oldSubFolderName = this.inputText; - this.inputText = inputText; - firePropertyChange(PROPERTY_SUBFOLDER_NAME, oldSubFolderName, inputText); - } -} +package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog; + +import com.jgoodies.binding.beans.Model; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:49:58, 23.10.2009 + * + * A Model component for SimpleTextFieldDialog. + */ +public class SimpleTextFieldDialogModel extends Model { + + public static final String PROPERTY_SUBFOLDER_NAME = "inputText"; + private String inputText; + + public String getInputText() { + return inputText; + } + + public void setInputText(final String inputText) { + final String oldSubFolderName = this.inputText; + this.inputText = inputText; + firePropertyChange(PROPERTY_SUBFOLDER_NAME, oldSubFolderName, inputText); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogView.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogView.java index 8407803..226b488 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/SimpleTextFieldDialogView.java @@ -1,70 +1,70 @@ -package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; - -import javax.swing.*; -import java.awt.*; - -import com.jgoodies.forms.factories.Borders; -import com.jgoodies.forms.layout.FormLayout; -import com.jgoodies.forms.layout.CellConstraints; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:49:51, 23.10.2009 - * - * A View component of SimpleTextFieldDialog. - */ -public class SimpleTextFieldDialogView extends JDialog{ - - private final Dimension INIT_SIZE = new Dimension(450, 170); - - protected JLabel textLabel = ModelerSession.getComponentFactoryService().createLabel(""); - protected JTextField inputTextField = ModelerSession.getComponentFactoryService().createTextField(); - - protected final JLabel errorLabel = ModelerSession.getComponentFactoryService().createLabel(""); - - protected JButton confirmButton = ModelerSession.getComponentFactoryService().createButton("", null); - protected JButton cancelButton = ModelerSession.getComponentFactoryService().createButton("", null); - - protected SimpleTextFieldDialogView(){ - initLayout(); - - errorLabel.setForeground(Color.RED); - } - - private void initLayout() { - setSize(INIT_SIZE); - - final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); - centerPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - centerPanel.setLayout(new FormLayout( - "min(pref;2000dlu):grow", - "pref, 3dlu, pref, 3dlu, pref, 7dlu" - )); - final CellConstraints cellConstraints = new CellConstraints(); - - centerPanel.add(textLabel, cellConstraints. xy(1, 1)); - centerPanel.add(inputTextField, cellConstraints.xy(1,3)); - - centerPanel.add(errorLabel, cellConstraints.xy(1, 5)); - - final JPanel southPanel = ModelerSession.getComponentFactoryService().createPanel(); - southPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - southPanel.setLayout(new FormLayout( - "pref:grow, pref, 3dlu, pref, pref:grow", - "pref")); - - southPanel.add(confirmButton, cellConstraints.xy(2, 1)); - southPanel.add(cancelButton, cellConstraints.xy(4, 1)); - - setLayout(new BorderLayout()); - add(centerPanel, BorderLayout.CENTER); - add(southPanel, BorderLayout.SOUTH); - } - -} +package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; + +import javax.swing.*; +import java.awt.*; + +import com.jgoodies.forms.factories.Borders; +import com.jgoodies.forms.layout.FormLayout; +import com.jgoodies.forms.layout.CellConstraints; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:49:51, 23.10.2009 + * + * A View component of SimpleTextFieldDialog. + */ +public class SimpleTextFieldDialogView extends JDialog{ + + private final Dimension INIT_SIZE = new Dimension(450, 170); + + protected JLabel textLabel = ModelerSession.getComponentFactoryService().createLabel(""); + protected JTextField inputTextField = ModelerSession.getComponentFactoryService().createTextField(); + + protected final JLabel errorLabel = ModelerSession.getComponentFactoryService().createLabel(""); + + protected JButton confirmButton = ModelerSession.getComponentFactoryService().createButton("", null); + protected JButton cancelButton = ModelerSession.getComponentFactoryService().createButton("", null); + + protected SimpleTextFieldDialogView(){ + initLayout(); + + errorLabel.setForeground(Color.RED); + } + + private void initLayout() { + setSize(INIT_SIZE); + + final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); + centerPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + centerPanel.setLayout(new FormLayout( + "min(pref;2000dlu):grow", + "pref, 3dlu, pref, 3dlu, pref, 7dlu" + )); + final CellConstraints cellConstraints = new CellConstraints(); + + centerPanel.add(textLabel, cellConstraints. xy(1, 1)); + centerPanel.add(inputTextField, cellConstraints.xy(1,3)); + + centerPanel.add(errorLabel, cellConstraints.xy(1, 5)); + + final JPanel southPanel = ModelerSession.getComponentFactoryService().createPanel(); + southPanel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + southPanel.setLayout(new FormLayout( + "pref:grow, pref, 3dlu, pref, pref:grow", + "pref")); + + southPanel.add(confirmButton, cellConstraints.xy(2, 1)); + southPanel.add(cancelButton, cellConstraints.xy(4, 1)); + + setLayout(new BorderLayout()); + add(centerPanel, BorderLayout.CENTER); + add(southPanel, BorderLayout.SOUTH); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/executors/AddProjectSubFolderExecutor.java b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/executors/AddProjectSubFolderExecutor.java index 064fc5b..2280504 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/executors/AddProjectSubFolderExecutor.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/dialogs/simpleTextFieldDialog/executors/AddProjectSubFolderExecutor.java @@ -1,57 +1,57 @@ -package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.executors; - -import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialogExecutor; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.results.AddProjectItemResult; -import org.apache.log4j.Logger; - -import javax.swing.tree.TreePath; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 0:38:55, 24.10.2009 - */ -public class AddProjectSubFolderExecutor implements SimpleTextFieldDialogExecutor { - - private final Logger LOG = Logger.getLogger(AddProjectSubFolderExecutor.class); - - private static final String ILLEGAL_NAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.error.disallowed"); - private static final String NAME_DUPLICATE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.error.nameduplicity"); - private static final String ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.error"); - - public String execute(final String text) { - final AddProjectItemResult result = ModelerSession.getProjectControlService().addSubFolder(text, true); - - switch (result.getStatus()){ - case SUCCESS: - mkdir(result.getTreePath()); - return null; - case INVALID_NAME: - return ILLEGAL_NAME_LABEL + ProjectServiceUtils.getDisallowedNameSymbols(','); - case NAME_DUPLICITY: - return NAME_DUPLICATE_LABEL; - default: - LOG.error("No such a result expected during project subfolder addition."); - return ERROR_LABEL; - } - } - - /** - * Make the dir structure. - * - * @param treePath is the tree path to the node to that is the dir structure supposed to make - */ - private void mkdir(final TreePath treePath) { - ModelerSession.getProjectControlService().synchronize( - treePath, - true, true, false, false - ); - - } - -} +package cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.executors; + +import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialogExecutor; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.results.AddProjectItemResult; +import org.apache.log4j.Logger; + +import javax.swing.tree.TreePath; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 0:38:55, 24.10.2009 + */ +public class AddProjectSubFolderExecutor implements SimpleTextFieldDialogExecutor { + + private final Logger LOG = Logger.getLogger(AddProjectSubFolderExecutor.class); + + private static final String ILLEGAL_NAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.error.disallowed"); + private static final String NAME_DUPLICATE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.error.nameduplicity"); + private static final String ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.error"); + + public String execute(final String text) { + final AddProjectItemResult result = ModelerSession.getProjectControlService().addSubFolder(text, true); + + switch (result.getStatus()){ + case SUCCESS: + mkdir(result.getTreePath()); + return null; + case INVALID_NAME: + return ILLEGAL_NAME_LABEL + ProjectServiceUtils.getDisallowedNameSymbols(','); + case NAME_DUPLICITY: + return NAME_DUPLICATE_LABEL; + default: + LOG.error("No such a result expected during project subfolder addition."); + return ERROR_LABEL; + } + } + + /** + * Make the dir structure. + * + * @param treePath is the tree path to the node to that is the dir structure supposed to make + */ + private void mkdir(final TreePath treePath) { + ModelerSession.getProjectControlService().synchronize( + treePath, + true, true, false, false + ); + + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/listeners/ButtonPopupAdapter.java b/IndependentModeler/src/cz/cvut/promod/gui/listeners/ButtonPopupAdapter.java index 2c79b9e..73f0b65 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/listeners/ButtonPopupAdapter.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/listeners/ButtonPopupAdapter.java @@ -1,39 +1,39 @@ -package cz.cvut.promod.gui.listeners; - -import com.jidesoft.swing.JideButton; - -import javax.swing.*; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 18:10:20, 19.10.2009 - * - * Is the listeners showing the popup menu on the buttons controlling the dockable frame visibility. - */ -public class ButtonPopupAdapter extends MouseAdapter { - - private final JideButton owner; - private final JPopupMenu menu; - - public ButtonPopupAdapter( final JideButton owner, final JPopupMenu menu ){ - this.owner = owner; - this.menu = menu; - } - - public void mousePressed( final MouseEvent e ){ - maybepopup(e); - } - - public void mouseReleased( final MouseEvent e ){ - maybepopup(e); - } - - private void maybepopup( final MouseEvent e ){ - if( e.isPopupTrigger() && owner.isEnabled() ){ - menu.show(owner, e.getX(), e.getY()); - } - } -} +package cz.cvut.promod.gui.listeners; + +import com.jidesoft.swing.JideButton; + +import javax.swing.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 18:10:20, 19.10.2009 + * + * Is the listeners showing the popup menu on the buttons controlling the dockable frame visibility. + */ +public class ButtonPopupAdapter extends MouseAdapter { + + private final JideButton owner; + private final JPopupMenu menu; + + public ButtonPopupAdapter( final JideButton owner, final JPopupMenu menu ){ + this.owner = owner; + this.menu = menu; + } + + public void mousePressed( final MouseEvent e ){ + maybepopup(e); + } + + public void mouseReleased( final MouseEvent e ){ + maybepopup(e); + } + + private void maybepopup( final MouseEvent e ){ + if( e.isPopupTrigger() && owner.isEnabled() ){ + menu.show(owner, e.getX(), e.getY()); + } + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/listeners/DockFrameListener.java b/IndependentModeler/src/cz/cvut/promod/gui/listeners/DockFrameListener.java index 566eb51..d28e42e 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/listeners/DockFrameListener.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/listeners/DockFrameListener.java @@ -1,99 +1,99 @@ -package cz.cvut.promod.gui.listeners; - -import com.jidesoft.docking.event.DockableFrameAdapter; -import com.jidesoft.docking.event.DockableFrameEvent; -import com.jidesoft.docking.DefaultDockingManager; -import com.jidesoft.docking.DockableFrame; -import com.jidesoft.swing.JideButton; -import cz.cvut.promod.gui.support.utils.NotationGuiHolder; -import cz.cvut.promod.gui.support.utils.DockableFrameWrapper; - -import java.util.List; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 18:20:52, 19.10.2009 - * - * Controls the dockable frame visibility on basis of their events. - */ -public class DockFrameListener extends DockableFrameAdapter { - - private final Logger LOG = Logger.getLogger(DockFrameListener.class); - - private final DefaultDockingManager dockingManager; - private final NotationGuiHolder specification; - - public DockFrameListener( final NotationGuiHolder specification, - final DefaultDockingManager dockingManager ){ - this.dockingManager = dockingManager; - this.specification = specification; - } - - /** - * Hides the dockable frame when user clicks the cross button. - * - * @param dockableFrameEvent is the dockable frame event - */ - @Override - public void dockableFrameHidden(DockableFrameEvent dockableFrameEvent) { - final DockableFrame dockableFrame = (DockableFrame)dockableFrameEvent.getSource(); - final String dockableFrameName = dockableFrame.getName(); - final DockableFrameWrapper facade = specification.getDockableFrameFacade(dockableFrameName); - - dockingManager.setFrameAvailable(dockableFrame.getName()); - dockingManager.showFrame(dockableFrame.getName()); - dockingManager.setFrameUnavailable(dockableFrame.getName()); - facade.setWasAvailable(false); - facade.getButton().setSelected(false); - } - - /** - * Main purpose of this is to hide other DockableFrames at the time the particular DockableFrame - * is docked (set available). - * - * @param dockableFrameEvent source. - */ - @Override - public void dockableFrameDocked( final DockableFrameEvent dockableFrameEvent ){ - final DockableFrame dockableFrame = (DockableFrame)dockableFrameEvent.getSource(); - NotationGuiHolder.Position position = specification.getPosition(dockableFrame.getName()); - - try{ - if( specification.isHideOtherFrames(dockableFrame.getName(), position) ){ - final List dockableFrameList = specification.getListOfFrames(position); - - if( !dockableFrame.isFloated() ){ - for( DockableFrame frame : dockableFrameList ){ - if( (!frame.isFloated()) && (frame != dockableFrame) && (dockableFrame.isAvailable()) ){ - dockingManager.setFrameUnavailable(frame.getName()); - final JideButton but = specification.getButton(frame.getName(), position); - but.setSelected(false); - } - } - } - } - specification.setButtonsMovementOptions(dockableFrame); - - } catch(IllegalArgumentException exception){ - LOG.error("Illegal position or unknown frame during frame docking.", exception); - } - } - - /** - * Hides the possibility to move button to the another side in the button's context menu when - * the DockableFrame appears in the floating state. - * - * @param dockableFrameEvent source. - */ - @Override - public void dockableFrameFloating( DockableFrameEvent dockableFrameEvent ){ - final DockableFrame dockableFrame = (DockableFrame)dockableFrameEvent.getSource(); - specification.setButtonsMovementOptions(dockableFrame); - - specification.getDockableFrameFacade(dockableFrame.getName()).setWasAvailable(true); - } -} - +package cz.cvut.promod.gui.listeners; + +import com.jidesoft.docking.event.DockableFrameAdapter; +import com.jidesoft.docking.event.DockableFrameEvent; +import com.jidesoft.docking.DefaultDockingManager; +import com.jidesoft.docking.DockableFrame; +import com.jidesoft.swing.JideButton; +import cz.cvut.promod.gui.support.utils.NotationGuiHolder; +import cz.cvut.promod.gui.support.utils.DockableFrameWrapper; + +import java.util.List; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 18:20:52, 19.10.2009 + * + * Controls the dockable frame visibility on basis of their events. + */ +public class DockFrameListener extends DockableFrameAdapter { + + private final Logger LOG = Logger.getLogger(DockFrameListener.class); + + private final DefaultDockingManager dockingManager; + private final NotationGuiHolder specification; + + public DockFrameListener( final NotationGuiHolder specification, + final DefaultDockingManager dockingManager ){ + this.dockingManager = dockingManager; + this.specification = specification; + } + + /** + * Hides the dockable frame when user clicks the cross button. + * + * @param dockableFrameEvent is the dockable frame event + */ + @Override + public void dockableFrameHidden(DockableFrameEvent dockableFrameEvent) { + final DockableFrame dockableFrame = (DockableFrame)dockableFrameEvent.getSource(); + final String dockableFrameName = dockableFrame.getName(); + final DockableFrameWrapper facade = specification.getDockableFrameFacade(dockableFrameName); + + dockingManager.setFrameAvailable(dockableFrame.getName()); + dockingManager.showFrame(dockableFrame.getName()); + dockingManager.setFrameUnavailable(dockableFrame.getName()); + facade.setWasAvailable(false); + facade.getButton().setSelected(false); + } + + /** + * Main purpose of this is to hide other DockableFrames at the time the particular DockableFrame + * is docked (set available). + * + * @param dockableFrameEvent source. + */ + @Override + public void dockableFrameDocked( final DockableFrameEvent dockableFrameEvent ){ + final DockableFrame dockableFrame = (DockableFrame)dockableFrameEvent.getSource(); + NotationGuiHolder.Position position = specification.getPosition(dockableFrame.getName()); + + try{ + if( specification.isHideOtherFrames(dockableFrame.getName(), position) ){ + final List dockableFrameList = specification.getListOfFrames(position); + + if( !dockableFrame.isFloated() ){ + for( DockableFrame frame : dockableFrameList ){ + if( (!frame.isFloated()) && (frame != dockableFrame) && (dockableFrame.isAvailable()) ){ + dockingManager.setFrameUnavailable(frame.getName()); + final JideButton but = specification.getButton(frame.getName(), position); + but.setSelected(false); + } + } + } + } + specification.setButtonsMovementOptions(dockableFrame); + + } catch(IllegalArgumentException exception){ + LOG.error("Illegal position or unknown frame during frame docking.", exception); + } + } + + /** + * Hides the possibility to move button to the another side in the button's context menu when + * the DockableFrame appears in the floating state. + * + * @param dockableFrameEvent source. + */ + @Override + public void dockableFrameFloating( DockableFrameEvent dockableFrameEvent ){ + final DockableFrame dockableFrame = (DockableFrame)dockableFrameEvent.getSource(); + specification.setButtonsMovementOptions(dockableFrame); + + specification.getDockableFrameFacade(dockableFrame.getName()).setWasAvailable(true); + } +} + diff --git a/IndependentModeler/src/cz/cvut/promod/gui/listeners/ProjectNavigationActionTarget.java b/IndependentModeler/src/cz/cvut/promod/gui/listeners/ProjectNavigationActionTarget.java index 8ce4847..e384812 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/listeners/ProjectNavigationActionTarget.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/listeners/ProjectNavigationActionTarget.java @@ -1,74 +1,74 @@ -package cz.cvut.promod.gui.listeners; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import cz.cvut.promod.gui.support.utils.NotationGuiHolder; -import cz.cvut.promod.gui.projectNavigation.ProjectNavigation; -import cz.cvut.promod.gui.ModelerModel; - -import java.awt.event.ActionEvent; -import java.util.List; -import java.util.LinkedList; - -import com.jidesoft.docking.DockableFrame; -import com.jidesoft.docking.DockingManager; - -import javax.swing.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 18:32:19, 19.10.2009 - * - * Action that controls the visibility of high level navigation. - */ -public class ProjectNavigationActionTarget extends ProModAction { - - private final DockingManager dockingManager; - private final ProjectNavigation projectNavigationDockableFrame; - private final ModelerModel model; - - public ProjectNavigationActionTarget(final String displayName, - final Icon icon, - final KeyStroke keyStroke, - final DockingManager dockingManager, - final ProjectNavigation projectNavigationDockableFrame, - final ModelerModel model){ - - super(displayName, icon, keyStroke); - - this.dockingManager = dockingManager; - this.projectNavigationDockableFrame = projectNavigationDockableFrame; - this.model = model; - } - - public void actionPerformed(ActionEvent event) { - if( projectNavigationDockableFrame.isAvailable() ){ - dockingManager.setFrameUnavailable(projectNavigationDockableFrame.getName()); - } else{ - final String currentNotation = ModelerSession.getProjectService().getSelectedProjectNotationIndentifier(); - - final NotationGuiHolder specification = model.getNotationGuiHolder(currentNotation); - - if( specification != null ){ - final List visibleDockableFrames = new LinkedList(); - - for( final DockableFrame dockableFrame : specification.getListOfFrames(NotationGuiHolder.Position.LEFT) ){ - if( dockableFrame.isAvailable() ){ - visibleDockableFrames.add((dockableFrame)); - specification.getButton(dockableFrame.getName(), NotationGuiHolder.Position.LEFT).doClick(); - } - } - - dockingManager.setFrameAvailable(projectNavigationDockableFrame.getName()); - - for( final DockableFrame dockableFrame : visibleDockableFrames ){ - specification.getButton(dockableFrame.getName(), NotationGuiHolder.Position.LEFT).doClick(); - } - } else{ - dockingManager.setFrameAvailable(projectNavigationDockableFrame.getName()); - } - } - } - +package cz.cvut.promod.gui.listeners; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import cz.cvut.promod.gui.support.utils.NotationGuiHolder; +import cz.cvut.promod.gui.projectNavigation.ProjectNavigation; +import cz.cvut.promod.gui.ModelerModel; + +import java.awt.event.ActionEvent; +import java.util.List; +import java.util.LinkedList; + +import com.jidesoft.docking.DockableFrame; +import com.jidesoft.docking.DockingManager; + +import javax.swing.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 18:32:19, 19.10.2009 + * + * Action that controls the visibility of high level navigation. + */ +public class ProjectNavigationActionTarget extends ProModAction { + + private final DockingManager dockingManager; + private final ProjectNavigation projectNavigationDockableFrame; + private final ModelerModel model; + + public ProjectNavigationActionTarget(final String displayName, + final Icon icon, + final KeyStroke keyStroke, + final DockingManager dockingManager, + final ProjectNavigation projectNavigationDockableFrame, + final ModelerModel model){ + + super(displayName, icon, keyStroke); + + this.dockingManager = dockingManager; + this.projectNavigationDockableFrame = projectNavigationDockableFrame; + this.model = model; + } + + public void actionPerformed(ActionEvent event) { + if( projectNavigationDockableFrame.isAvailable() ){ + dockingManager.setFrameUnavailable(projectNavigationDockableFrame.getName()); + } else{ + final String currentNotation = ModelerSession.getProjectService().getSelectedProjectNotationIndentifier(); + + final NotationGuiHolder specification = model.getNotationGuiHolder(currentNotation); + + if( specification != null ){ + final List visibleDockableFrames = new LinkedList(); + + for( final DockableFrame dockableFrame : specification.getListOfFrames(NotationGuiHolder.Position.LEFT) ){ + if( dockableFrame.isAvailable() ){ + visibleDockableFrames.add((dockableFrame)); + specification.getButton(dockableFrame.getName(), NotationGuiHolder.Position.LEFT).doClick(); + } + } + + dockingManager.setFrameAvailable(projectNavigationDockableFrame.getName()); + + for( final DockableFrame dockableFrame : visibleDockableFrames ){ + specification.getButton(dockableFrame.getName(), NotationGuiHolder.Position.LEFT).doClick(); + } + } else{ + dockingManager.setFrameAvailable(projectNavigationDockableFrame.getName()); + } + } + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/listeners/SideButtonListener.java b/IndependentModeler/src/cz/cvut/promod/gui/listeners/SideButtonListener.java index 3b8bb19..1277c28 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/listeners/SideButtonListener.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/listeners/SideButtonListener.java @@ -1,66 +1,66 @@ -package cz.cvut.promod.gui.listeners; - -import com.jidesoft.docking.DefaultDockingManager; -import com.jidesoft.docking.DockableFrame; -import com.jidesoft.swing.JideButton; - -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; -import java.util.List; - -import cz.cvut.promod.gui.support.utils.NotationGuiHolder; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 18:38:43, 19.10.2009 - * - * Implementation of an ActionListener that reacts on side panel buttons clicks. It set the - * corresponding DockableFrame available. - */ -public class SideButtonListener implements ActionListener { - - private final DefaultDockingManager dockingManager; - private final NotationGuiHolder specification; - private final DockableFrame dockableFrame; - - public SideButtonListener( final NotationGuiHolder specification, - final DefaultDockingManager dockingManager, - final DockableFrame frame ){ - - this.dockingManager = dockingManager; - this.dockableFrame = frame; - this.specification = specification; - } - - public void actionPerformed( ActionEvent e ){ - final List dockableFrameList; - final NotationGuiHolder.Position position = specification.getPosition(dockableFrame.getName()); - - dockableFrameList = specification.getListOfFrames(position); - - if( dockableFrame.isHidden()){ - dockingManager.setFrameAvailable(dockableFrame.getName()); - dockingManager.showFrame(dockableFrame.getName()); - dockingManager.setFrameUnavailable(dockableFrame.getName()); - } - - if( !dockableFrame.isFloated() ){ - for( DockableFrame frame : dockableFrameList ){ - if( (!frame.isFloated()) && (frame != dockableFrame) ){ - dockingManager.setFrameUnavailable(frame.getName()); - final JideButton but = specification.getButton(frame.getName(), position); - but.setSelected(false); - } - } - } - - if( dockableFrame.isAvailable() ){ - dockingManager.setFrameUnavailable(dockableFrame.getName()); - specification.getDockableFrameFacade(dockableFrame.getName()).setWasAvailable(false); - } else{ - dockingManager.setFrameAvailable(dockableFrame.getName()); - } - } - +package cz.cvut.promod.gui.listeners; + +import com.jidesoft.docking.DefaultDockingManager; +import com.jidesoft.docking.DockableFrame; +import com.jidesoft.swing.JideButton; + +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.util.List; + +import cz.cvut.promod.gui.support.utils.NotationGuiHolder; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 18:38:43, 19.10.2009 + * + * Implementation of an ActionListener that reacts on side panel buttons clicks. It set the + * corresponding DockableFrame available. + */ +public class SideButtonListener implements ActionListener { + + private final DefaultDockingManager dockingManager; + private final NotationGuiHolder specification; + private final DockableFrame dockableFrame; + + public SideButtonListener( final NotationGuiHolder specification, + final DefaultDockingManager dockingManager, + final DockableFrame frame ){ + + this.dockingManager = dockingManager; + this.dockableFrame = frame; + this.specification = specification; + } + + public void actionPerformed( ActionEvent e ){ + final List dockableFrameList; + final NotationGuiHolder.Position position = specification.getPosition(dockableFrame.getName()); + + dockableFrameList = specification.getListOfFrames(position); + + if( dockableFrame.isHidden()){ + dockingManager.setFrameAvailable(dockableFrame.getName()); + dockingManager.showFrame(dockableFrame.getName()); + dockingManager.setFrameUnavailable(dockableFrame.getName()); + } + + if( !dockableFrame.isFloated() ){ + for( DockableFrame frame : dockableFrameList ){ + if( (!frame.isFloated()) && (frame != dockableFrame) ){ + dockingManager.setFrameUnavailable(frame.getName()); + final JideButton but = specification.getButton(frame.getName(), position); + but.setSelected(false); + } + } + } + + if( dockableFrame.isAvailable() ){ + dockingManager.setFrameUnavailable(dockableFrame.getName()); + specification.getDockableFrameFacade(dockableFrame.getName()).setWasAvailable(false); + } else{ + dockingManager.setFrameAvailable(dockableFrame.getName()); + } + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/ProjectNavigation.java b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/ProjectNavigation.java index dece997..0427ed4 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/ProjectNavigation.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/ProjectNavigation.java @@ -1,681 +1,681 @@ -package cz.cvut.promod.gui.projectNavigation; - -import cz.cvut.promod.gui.Modeler; -import cz.cvut.promod.gui.ModelerModel; -import cz.cvut.promod.gui.dialogs.addNewDiagramDialog.AddNewDiagramDialog; -import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialog; -import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.executors.AddProjectSubFolderExecutor; -import cz.cvut.promod.gui.projectNavigation.events.ProjectTreeExpandEvent; -import cz.cvut.promod.gui.projectNavigation.listeners.MousePopup; -import cz.cvut.promod.gui.projectNavigation.renderer.ProjectNavigationCellRenderer; -import cz.cvut.promod.gui.projectNavigation.actions.executors.RenameExecutor; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import cz.cvut.promod.services.menuService.MenuControlService; -import cz.cvut.promod.services.menuService.MenuService; -import cz.cvut.promod.services.menuService.utils.MenuItemPosition; -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectItem; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; -import cz.cvut.promod.resources.Resources; -import org.apache.log4j.Logger; - -import javax.swing.*; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.Enumeration; - -import com.jidesoft.dialog.JideOptionPane; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 15:53:42, 11.10.2009 - */ - -/** - * Project navigation controller. - */ -public class ProjectNavigation extends ProjectNavigationView implements TreeSelectionListener{ - - private static final String EXPAND_TIP_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.expand.all"); - private static final String COLLAPSE_TIP_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.collapse.all"); - private static final String ADD_DIAGRAM_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.new.diagram"); - private static final String ADD_SUBFOLDER_TIP_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.new.subfolder"); - public static final String RENAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.rename"); - public static final String RENAME_DESCRIPTION_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.rename.description"); - public static final String INVALID_NAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.disallowed"); - public static final String DUPLICATE_NAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.rename.duplicity"); - public static final String RENAME_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.rename.error"); - public static final String RENAME_ERROR_TITLE_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.rename.error.title"); - - public static final String ACTION_EXPAND = "modeler.project.navigation.expand"; - public static final String ACTION_ADD_SUBFOLDER = "modeler.project.navigation.add.subfolder"; - public static final String ACTION_ADD_DIAGRAM = "modeler.project.navigation.add.diagram"; - public static final String ACTION_DELETE = "modeler.project.navigation.delete"; - public static final String ACTION_CLOSE_PROJECT = "modeler.project.navigation.close.project"; - public static final String ACTION_REFRESH = "modeler.project.navigation.refresh"; - public static final String ACTION_RENAME = "modeler.project.navigation.action.rename"; - - public static final String ADD_LABEL = - ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.add"); - - public static final String EXPAND_LABEL = ModelerSession.getCommonResourceBundle().getString(ACTION_EXPAND); - - - private final Logger LOG = Logger.getLogger(ProjectNavigation.class); - - public ProjectNavigation(final int dockableFrameIndex) { - super(dockableFrameIndex); - - setShowContextMenu(false); - - initActions(); - - initPopupMenu(); - - initMainMenu(); - - initProjectTree(); - - initEventHandling(); - - ToolTipManager.sharedInstance().registerComponent(projectTree); - - initToolTips(); - } - - private void initToolTips() { - addDiagramButton.setToolTipText(ADD_DIAGRAM_LABEL); - addSubfolderButton.setToolTipText(ADD_SUBFOLDER_TIP_LABEL); - expandButton.setToolTipText(EXPAND_TIP_LABEL); - collapseButton.setToolTipText(COLLAPSE_TIP_LABEL); - } - - /** - * Initialize the popup menu. - */ - private void initPopupMenu() { - ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_SUBFOLDER), - new MenuItemPosition(ADD_LABEL) - ); - - ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_DIAGRAM), - new MenuItemPosition( - ADD_LABEL, - MenuItemPosition.PlacementStyle.FIRST) - ); - - ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_RENAME), - new MenuItemPosition(""), - null - ); - - ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_DELETE), - new MenuItemPosition(""), - null - ); - - ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_CLOSE_PROJECT), - new MenuItemPosition(""), - null - ); - - ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_REFRESH), - new MenuItemPosition(""), - null - ); - - } - - /** - * Initialize the main menu. - */ - public void initMainMenu(){ - ModelerSession.getMenuService().insertMainMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_DIAGRAM), - new MenuItemPosition( - Modeler.PROJECT_LABEL + - MenuService.PLACEMENT_DELIMITER + - ADD_LABEL) - ); - - ModelerSession.getMenuService().insertMainMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_SUBFOLDER), - new MenuItemPosition( - Modeler.PROJECT_LABEL + - MenuService.PLACEMENT_DELIMITER + - ADD_LABEL) - ); - - ModelerSession.getMenuService().insertMainMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_CLOSE_PROJECT), - new MenuItemPosition(Modeler.PROJECT_LABEL + MenuService.PLACEMENT_DELIMITER, 4) - ); - - ModelerSession.getMenuService().insertMainMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_REFRESH), - new MenuItemPosition(Modeler.PROJECT_LABEL + MenuService.PLACEMENT_DELIMITER, MenuItemPosition.PlacementStyle.LAST) - ); - - ModelerSession.getMenuService().insertMainMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_RENAME), - new MenuItemPosition(Modeler.FILE_LABEL + MenuService.PLACEMENT_DELIMITER, 1) - ); - - ModelerSession.getMenuService().insertMainMenuItem( - ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_DELETE), - new MenuItemPosition(Modeler.FILE_LABEL + MenuService.PLACEMENT_DELIMITER, 1) - ); - } - - private void initActions() { - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - ACTION_RENAME, - new ProModAction( - RENAME_LABEL, - Resources.getIcon(Resources.MODELER + Resources.RENAME_ICON), - KeyStroke.getKeyStroke(KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK)){ - public void actionPerformed(ActionEvent event) { - final TreePath treePath = ModelerSession.getProjectService().getSelectedTreePath(); - - if(treePath != null){ - if(treePath.getLastPathComponent() instanceof DefaultMutableTreeNode){ - final DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - - if(node.getUserObject() instanceof ProjectItem){ - final ProjectItem projectItem = (ProjectItem) node.getUserObject(); - - new SimpleTextFieldDialog( - RENAME_LABEL, - RENAME_DESCRIPTION_LABEL, - projectItem.getDisplayName(), - Modeler.OK_LABEL, - Modeler.CANCEL_LABEL, - new RenameExecutor(treePath, projectItem, projectTree), - ModelerSession.getFrame(), - true - ); - } - } - } - } - } - ); - - ModelerSession.getActionService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - null, - ACTION_EXPAND, - new ProModAction(EXPAND_LABEL, null, null){ - public void actionPerformed(ActionEvent event) { - final ProjectTreeExpandEvent expandEvent; - try{ - expandEvent = (ProjectTreeExpandEvent) event; - } catch (ClassCastException exception){ - LOG.error("Invalid event for project tree expanding/collapsing", exception); - return; - } - - final TreePath treePath = expandEvent.getTreePath(); - - expandAll(treePath, expandEvent.isExpand(), expandEvent.getDepth()); - } - } - ); - - ModelerSession.getActionControlService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - null, - ACTION_ADD_SUBFOLDER, - new ProModAction( - ModelerSession.getCommonResourceBundle().getString(ACTION_ADD_SUBFOLDER), - Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.FOLDER_ADD_ICON), - KeyStroke.getKeyStroke( - KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ - - public void actionPerformed(ActionEvent event) { - if(ModelerSession.getProjectService().getSelectedProject() == null){ - LOG.warn("An attempt to insert new subfolder without project has occurred."); - - JOptionPane.showMessageDialog( - ModelerSession.getFrame(), - ModelerSession.getCommonResourceBundle().getString("modeler.add.dialog.error.noSelectedProject"), - ModelerSession.getCommonResourceBundle().getString("modeler.add.dialog.error.noSelProjectTitle"), - JOptionPane.ERROR_MESSAGE); - return; - } - - new SimpleTextFieldDialog( - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.title"), - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.label"), - "", - ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.confirm"), - ModelerSession.getCommonResourceBundle().getString("modeler.cancel"), - new AddProjectSubFolderExecutor(), - ModelerSession.getFrame(), - true - ); - } - }); - - ModelerSession.getActionControlService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - null, - ACTION_ADD_DIAGRAM, - new ProModAction( - ModelerSession.getCommonResourceBundle().getString(ACTION_ADD_DIAGRAM), - Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.DIAGRAM_ADD_ICON), - KeyStroke.getKeyStroke( - KeyEvent.VK_D, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ - - public void actionPerformed(ActionEvent event) { - if(ModelerSession.getProjectService().getSelectedProject() == null){ - LOG.warn("An attempt to insert new diagram without project has occurred."); - - JOptionPane.showMessageDialog( - ModelerSession.getFrame(), - ModelerSession.getCommonResourceBundle().getString("modeler.add.dialog.error.noSelectedProject"), - ModelerSession.getCommonResourceBundle().getString("modeler.add.dialog.error.noSelProjectTitle"), - JOptionPane.ERROR_MESSAGE); - - return; - } - - new AddNewDiagramDialog(); - } - }); - - ModelerSession.getActionControlService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - null, - ACTION_DELETE, - new ProModAction(ModelerSession.getCommonResourceBundle().getString( - ACTION_DELETE), - Resources.getIcon(Resources.MODELER + Resources.DELETE_ICON), - null){ - public void actionPerformed(ActionEvent event) { - removeItem(); - } - }); - - ModelerSession.getActionControlService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - null, - ACTION_CLOSE_PROJECT, - new ProModAction(ModelerSession.getCommonResourceBundle().getString(ACTION_CLOSE_PROJECT), null, null){ - public void actionPerformed(ActionEvent event) { - closeProject(); - } - }); - - ModelerSession.getActionControlService().registerAction( - ModelerModel.MODELER_IDENTIFIER, - null, - ACTION_REFRESH, - new ProModAction(ModelerSession.getCommonResourceBundle().getString( - ACTION_REFRESH), - null, - null){ - public void actionPerformed(ActionEvent event) { - refreshProject(); - } - }); - } - - /** - * Refresh the selected project with the file system structure. - */ - public void refreshProject(){ - final ProjectRoot selectedProjectRoot = ModelerSession.getProjectService().getSelectedProject(); - - if(selectedProjectRoot == null){ - LOG.warn("There is no selected project to be refreshed."); - return; - } - - ModelerSession.getProjectControlService().synchronize( - selectedProjectRoot.getProjectFile(), - null, - true, false, true, /*add, NOT over-write, delete */ - true - ); - } - - /** - * Closes the selected project = removes this project from the tree project model. - */ - private void closeProject() { - final TreePath treePath = ModelerSession.getProjectService().getSelectedProjectPath(); - - if(treePath != null){ - if(!Modeler.ExitDialogReturnValues.CANCEL.equals(checkForUnsavedChanges(treePath, treePath))){ - ModelerSession.getProjectControlService().removeProjectItem(treePath); - } - } - } - - /** - * Removed project selected item. - */ - private void removeItem() { - final TreePath selectedTreePath = ModelerSession.getProjectService().getSelectedTreePath(); - - if(selectedTreePath!= null){ - final DefaultMutableTreeNode node; - try{ - node = (DefaultMutableTreeNode) selectedTreePath.getLastPathComponent(); - } catch (ClassCastException exception){ - LOG.error("All project navigation nodes have to be an instance of DefaultMutableTreePath class."); - return; - } - - if(ProjectServiceUtils.isProjectDiagram(node)){ - final String title = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.diagram.title"); - final String message = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.diagram.message"); - - //show project dialog confirm. dialog - if(showRemoveConfirmDialog(title, message)){ - - final String fsPath = ModelerSession.getProjectControlService().removeProjectItem(selectedTreePath); - - if(fsPath == null){ - //should never happened, testing & debugging - LOG.error("Removal of project diagram has failed. Node: " + node.toString()); - } else { - //remove the file associated with the project diagram - if(!ProjectServiceUtils.deleteFSItem(selectedTreePath.getParentPath(), new File(fsPath).getName())){ - // file system deletion has failed - LOG.error("ProMod couldn't delete selected diagram from file system: " + fsPath); - } - } - } - - //show project subfolder confirm. dialog - } else if(ProjectServiceUtils.isProjectSubfolder(node)){ - final String title = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.diagram.title"); - final String message = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.subfolder.message"); - - if(showRemoveConfirmDialog(title, message)){ - - final String fsPath = ModelerSession.getProjectControlService().removeProjectItem(selectedTreePath); - - if(fsPath == null){ - //should never happened, testing & debugging - LOG.error("Removal of project subfolder has failed. Node: " + node.toString()); - } else { - //remove the file associated with the project diagram - if(!ProjectServiceUtils.deleteFSItem(selectedTreePath.getParentPath(), new File(fsPath).getName())){ - // file system deletion has failed - LOG.error("ProMod couldn't delete selected subfolder from file system: " + fsPath); - } - } - } - - // show !CLOSE! project dialog - } else if(ProjectServiceUtils.isProjectRoot(node)){ - final String title = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.project.title"); - final String message = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.project.message"); - - if(showRemoveConfirmDialog(title, message)){ - - final String fsPath = ModelerSession.getProjectControlService().removeProjectItem(selectedTreePath); - - if(fsPath == null){ - //should never happened, testing & debugging - LOG.error("Removal of project has failed."); - } - } - } else { - LOG.error("A user object of all nodes has to be an instance of ProjectRoot, ProjectSubFolder or ProjectDiagram class."); - } - } - - } - - /** - * Shows the confirm dialog before removing a project item. - * @param title is the title of the dialog. - * @param message is the text to be displayed - * @return true if the user's answer is YES - */ - private boolean showRemoveConfirmDialog(final String title, - final String message){ - final Object[] options = { - ModelerSession.getCommonResourceBundle().getString("modeler.ok"), - ModelerSession.getCommonResourceBundle().getString("modeler.cancel") - }; - - int dialogReturnValue = JOptionPane.showOptionDialog( - ModelerSession.getFrame(), - message, - title, - JOptionPane.YES_NO_OPTION, - JOptionPane.QUESTION_MESSAGE, - null, - options, - options[0]); - - return dialogReturnValue == JOptionPane.YES_OPTION; - } - - /** - * Initialize the event handling. - */ - private void initEventHandling() { - projectTree.addTreeSelectionListener(this); - - // - ModelerSession.getProjectService().getSelectedItem().addValueChangeListener(new PropertyChangeListener(){ - public void propertyChange(PropertyChangeEvent evt) { - TreePath treePath = (TreePath) evt.getNewValue(); - - // using JTree#setSelectionPath(null) has no effect only firing valueChange event holding old tree selection value - // so if null comes, the selection tree path is selected to the tree modelFactory's root node - if(treePath == null){ - treePath = new TreePath(ModelerSession.getProjectControlService().getProjectTreeModel().getRoot()); - } - - projectTree.setSelectionPath(treePath); - } - }); - - final MenuControlService menuControlService = (MenuControlService) ModelerSession.getMenuService(); - projectTree.addMouseListener(new MousePopup(menuControlService.getProjectTreePopupMenu(), projectTree)); - - expandButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - expandAll(true); - } - }); - - collapseButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - expandAll(false); - } - }); - - Action action = ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_DIAGRAM); - if(action != null){ - addDiagramButton.setAction(action); - addDiagramButton.setText(""); - } else { - LOG.error("Add diagram action is not available."); - } - - action = ModelerSession.getActionService().getAction( - ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_SUBFOLDER); - if(action != null){ - addSubfolderButton.setAction(action); - addSubfolderButton.setText(""); - } else { - LOG.error("Add subfolder action is not available."); - } - } - - /** - * Initialize the tree. - */ - private void initProjectTree() { - projectTree.setCellRenderer(new ProjectNavigationCellRenderer()); - - projectTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - - final TreeModel treeModel = ModelerSession.getProjectControlService().getProjectTreeModel(); - - if(treeModel == null){ - LOG.error("TreeModel is null."); - } else { - projectTree.setModel(treeModel); - } - - } - - /** - * Expands or collapses the entire project tree. - * - * @param expand true for expansion, false for collapse - */ - private void expandAll(boolean expand) { - final TreeNode root = (TreeNode) projectTree.getModel().getRoot(); - expandAll(new TreePath(root), expand, -1); - - projectTree.expandPath(new TreePath(root)); - } - - /** - * Expands/collapses project tree navigation subtree that is specified by it's root - parent parameter. - * - * @param parent is the root of subtree to be expanded/collapsed - * @param expand true for expanding, false for collapsing - * @param depth is depth for expanding, 0 means no expanding, -1 stands for expand all - */ - private void expandAll(final TreePath parent, boolean expand, final int depth) { - final TreeNode node = (TreeNode)parent.getLastPathComponent(); - - if(depth == 0){ // depth == 0 -> stop, if depth < 0 -> expand all - return; - } - - if (node.getChildCount() >= 0) { - for (final Enumeration enumeration = node.children(); enumeration.hasMoreElements(); ) { - final TreeNode treeNode = (TreeNode) enumeration.nextElement(); - final TreePath path = parent.pathByAddingChild(treeNode); - - expandAll(path, expand, depth - 1); - } - } - - if (expand) { - projectTree.expandPath(parent); - } else { - projectTree.collapsePath(parent); - } - } - - /** - * Updates the ProjectService data when the project item selection has changed. - * @param e is the tree selection change - */ - public void valueChanged(TreeSelectionEvent e) { - ModelerSession.getProjectControlService().setSelectedItem(e.getPath()); - } - - /** - * Goes though all projects and all it's diagrams and checks whether the 'changed' flag of this - * diagrams is not set to true. Then it gives the user list of options what to do. - * - * @param itemTreePath is the tree path to the currently tested project navigation tree item - * @param rootTreePath is the tree path to the the currently tested project - * - * @return CONTINUE if the test is supposed to continue in a ordinary way, STOP if all changes are supposed to - * be skipped and CANCEL for cancel ProMod existing - */ - public Modeler.ExitDialogReturnValues checkForUnsavedChanges(final TreePath itemTreePath, - final TreePath rootTreePath) { - - final Object lastPathComponent = itemTreePath.getLastPathComponent(); - final ProjectRoot projectRoot = - (ProjectRoot) ((DefaultMutableTreeNode)rootTreePath.getLastPathComponent()).getUserObject(); - - if(lastPathComponent != null){ - final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) lastPathComponent; - - if(treeNode.getUserObject() instanceof ProjectDiagram){ - final ProjectDiagram projectDiagram = (ProjectDiagram) treeNode.getUserObject(); - - if(projectDiagram.isChanged()){ - final int dialogResult = JideOptionPane.showOptionDialog(this, - "["+ projectDiagram.getDisplayName() + "] " + Modeler.UNSAVED_CHANGE_LABEL, - Modeler.PROMOD_EXIT_LABEL + " - [" + projectRoot.getDisplayName() + "]", - JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, - null, Modeler.EXIT_DIALOG_OPTIONS, Modeler.EXIT_DIALOG_OPTIONS[0]); - - switch (dialogResult){ - case 0: // yes - ModelerSession.getProjectControlService().synchronize( - itemTreePath, true, true, false, true - ); - break; - case 1: //no - break; - case 2: //save all - LOG.info("Saving all changes in project: " + projectRoot.getDisplayName() + "."); - ModelerSession.getProjectControlService().synchronize( - rootTreePath, true, true, false, true - ); - return Modeler.ExitDialogReturnValues.STOP; - case 3: // skip all - LOG.info("Skipping all changes in project: " + projectRoot.getDisplayName() + "."); - return Modeler.ExitDialogReturnValues.STOP; - case 4: - case -1: // user clicked the closing cross of the dialog - return Modeler.ExitDialogReturnValues.CANCEL; - } - } - - } else { - for(int i = 0; i < treeNode.getChildCount(); i++){ - final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) treeNode.getChildAt(i); - - final Modeler.ExitDialogReturnValues value = checkForUnsavedChanges(itemTreePath.pathByAddingChild(childNode), rootTreePath); - - switch (value){ - case CANCEL: - return Modeler.ExitDialogReturnValues.CANCEL; - case STOP: - return Modeler.ExitDialogReturnValues.STOP; - } - } - } - } - - return Modeler.ExitDialogReturnValues.CONTINUE; - } +package cz.cvut.promod.gui.projectNavigation; + +import cz.cvut.promod.gui.Modeler; +import cz.cvut.promod.gui.ModelerModel; +import cz.cvut.promod.gui.dialogs.addNewDiagramDialog.AddNewDiagramDialog; +import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialog; +import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.executors.AddProjectSubFolderExecutor; +import cz.cvut.promod.gui.projectNavigation.events.ProjectTreeExpandEvent; +import cz.cvut.promod.gui.projectNavigation.listeners.MousePopup; +import cz.cvut.promod.gui.projectNavigation.renderer.ProjectNavigationCellRenderer; +import cz.cvut.promod.gui.projectNavigation.actions.executors.RenameExecutor; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import cz.cvut.promod.services.menuService.MenuControlService; +import cz.cvut.promod.services.menuService.MenuService; +import cz.cvut.promod.services.menuService.utils.MenuItemPosition; +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectItem; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; +import cz.cvut.promod.resources.Resources; +import org.apache.log4j.Logger; + +import javax.swing.*; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.util.Enumeration; + +import com.jidesoft.dialog.JideOptionPane; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 15:53:42, 11.10.2009 + */ + +/** + * Project navigation controller. + */ +public class ProjectNavigation extends ProjectNavigationView implements TreeSelectionListener{ + + private static final String EXPAND_TIP_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.expand.all"); + private static final String COLLAPSE_TIP_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.collapse.all"); + private static final String ADD_DIAGRAM_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.new.diagram"); + private static final String ADD_SUBFOLDER_TIP_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.new.subfolder"); + public static final String RENAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.rename"); + public static final String RENAME_DESCRIPTION_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.rename.description"); + public static final String INVALID_NAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.diagram.dialog.error.disallowed"); + public static final String DUPLICATE_NAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.rename.duplicity"); + public static final String RENAME_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.rename.error"); + public static final String RENAME_ERROR_TITLE_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.rename.error.title"); + + public static final String ACTION_EXPAND = "modeler.project.navigation.expand"; + public static final String ACTION_ADD_SUBFOLDER = "modeler.project.navigation.add.subfolder"; + public static final String ACTION_ADD_DIAGRAM = "modeler.project.navigation.add.diagram"; + public static final String ACTION_DELETE = "modeler.project.navigation.delete"; + public static final String ACTION_CLOSE_PROJECT = "modeler.project.navigation.close.project"; + public static final String ACTION_REFRESH = "modeler.project.navigation.refresh"; + public static final String ACTION_RENAME = "modeler.project.navigation.action.rename"; + + public static final String ADD_LABEL = + ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.add"); + + public static final String EXPAND_LABEL = ModelerSession.getCommonResourceBundle().getString(ACTION_EXPAND); + + + private final Logger LOG = Logger.getLogger(ProjectNavigation.class); + + public ProjectNavigation(final int dockableFrameIndex) { + super(dockableFrameIndex); + + setShowContextMenu(false); + + initActions(); + + initPopupMenu(); + + initMainMenu(); + + initProjectTree(); + + initEventHandling(); + + ToolTipManager.sharedInstance().registerComponent(projectTree); + + initToolTips(); + } + + private void initToolTips() { + addDiagramButton.setToolTipText(ADD_DIAGRAM_LABEL); + addSubfolderButton.setToolTipText(ADD_SUBFOLDER_TIP_LABEL); + expandButton.setToolTipText(EXPAND_TIP_LABEL); + collapseButton.setToolTipText(COLLAPSE_TIP_LABEL); + } + + /** + * Initialize the popup menu. + */ + private void initPopupMenu() { + ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_SUBFOLDER), + new MenuItemPosition(ADD_LABEL) + ); + + ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_DIAGRAM), + new MenuItemPosition( + ADD_LABEL, + MenuItemPosition.PlacementStyle.FIRST) + ); + + ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_RENAME), + new MenuItemPosition(""), + null + ); + + ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_DELETE), + new MenuItemPosition(""), + null + ); + + ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_CLOSE_PROJECT), + new MenuItemPosition(""), + null + ); + + ModelerSession.getMenuService().insertProjectNavigationPopupMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_REFRESH), + new MenuItemPosition(""), + null + ); + + } + + /** + * Initialize the main menu. + */ + public void initMainMenu(){ + ModelerSession.getMenuService().insertMainMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_DIAGRAM), + new MenuItemPosition( + Modeler.PROJECT_LABEL + + MenuService.PLACEMENT_DELIMITER + + ADD_LABEL) + ); + + ModelerSession.getMenuService().insertMainMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_SUBFOLDER), + new MenuItemPosition( + Modeler.PROJECT_LABEL + + MenuService.PLACEMENT_DELIMITER + + ADD_LABEL) + ); + + ModelerSession.getMenuService().insertMainMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_CLOSE_PROJECT), + new MenuItemPosition(Modeler.PROJECT_LABEL + MenuService.PLACEMENT_DELIMITER, 4) + ); + + ModelerSession.getMenuService().insertMainMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_REFRESH), + new MenuItemPosition(Modeler.PROJECT_LABEL + MenuService.PLACEMENT_DELIMITER, MenuItemPosition.PlacementStyle.LAST) + ); + + ModelerSession.getMenuService().insertMainMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_RENAME), + new MenuItemPosition(Modeler.FILE_LABEL + MenuService.PLACEMENT_DELIMITER, 1) + ); + + ModelerSession.getMenuService().insertMainMenuItem( + ModelerSession.getActionService().getAction(ModelerModel.MODELER_IDENTIFIER, ACTION_DELETE), + new MenuItemPosition(Modeler.FILE_LABEL + MenuService.PLACEMENT_DELIMITER, 1) + ); + } + + private void initActions() { + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + ACTION_RENAME, + new ProModAction( + RENAME_LABEL, + Resources.getIcon(Resources.MODELER + Resources.RENAME_ICON), + KeyStroke.getKeyStroke(KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK)){ + public void actionPerformed(ActionEvent event) { + final TreePath treePath = ModelerSession.getProjectService().getSelectedTreePath(); + + if(treePath != null){ + if(treePath.getLastPathComponent() instanceof DefaultMutableTreeNode){ + final DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + + if(node.getUserObject() instanceof ProjectItem){ + final ProjectItem projectItem = (ProjectItem) node.getUserObject(); + + new SimpleTextFieldDialog( + RENAME_LABEL, + RENAME_DESCRIPTION_LABEL, + projectItem.getDisplayName(), + Modeler.OK_LABEL, + Modeler.CANCEL_LABEL, + new RenameExecutor(treePath, projectItem, projectTree), + ModelerSession.getFrame(), + true + ); + } + } + } + } + } + ); + + ModelerSession.getActionService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + null, + ACTION_EXPAND, + new ProModAction(EXPAND_LABEL, null, null){ + public void actionPerformed(ActionEvent event) { + final ProjectTreeExpandEvent expandEvent; + try{ + expandEvent = (ProjectTreeExpandEvent) event; + } catch (ClassCastException exception){ + LOG.error("Invalid event for project tree expanding/collapsing", exception); + return; + } + + final TreePath treePath = expandEvent.getTreePath(); + + expandAll(treePath, expandEvent.isExpand(), expandEvent.getDepth()); + } + } + ); + + ModelerSession.getActionControlService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + null, + ACTION_ADD_SUBFOLDER, + new ProModAction( + ModelerSession.getCommonResourceBundle().getString(ACTION_ADD_SUBFOLDER), + Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.FOLDER_ADD_ICON), + KeyStroke.getKeyStroke( + KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ + + public void actionPerformed(ActionEvent event) { + if(ModelerSession.getProjectService().getSelectedProject() == null){ + LOG.warn("An attempt to insert new subfolder without project has occurred."); + + JOptionPane.showMessageDialog( + ModelerSession.getFrame(), + ModelerSession.getCommonResourceBundle().getString("modeler.add.dialog.error.noSelectedProject"), + ModelerSession.getCommonResourceBundle().getString("modeler.add.dialog.error.noSelProjectTitle"), + JOptionPane.ERROR_MESSAGE); + return; + } + + new SimpleTextFieldDialog( + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.title"), + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.label"), + "", + ModelerSession.getCommonResourceBundle().getString("modeler.add.new.subfolder.dialog.confirm"), + ModelerSession.getCommonResourceBundle().getString("modeler.cancel"), + new AddProjectSubFolderExecutor(), + ModelerSession.getFrame(), + true + ); + } + }); + + ModelerSession.getActionControlService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + null, + ACTION_ADD_DIAGRAM, + new ProModAction( + ModelerSession.getCommonResourceBundle().getString(ACTION_ADD_DIAGRAM), + Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.DIAGRAM_ADD_ICON), + KeyStroke.getKeyStroke( + KeyEvent.VK_D, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)){ + + public void actionPerformed(ActionEvent event) { + if(ModelerSession.getProjectService().getSelectedProject() == null){ + LOG.warn("An attempt to insert new diagram without project has occurred."); + + JOptionPane.showMessageDialog( + ModelerSession.getFrame(), + ModelerSession.getCommonResourceBundle().getString("modeler.add.dialog.error.noSelectedProject"), + ModelerSession.getCommonResourceBundle().getString("modeler.add.dialog.error.noSelProjectTitle"), + JOptionPane.ERROR_MESSAGE); + + return; + } + + new AddNewDiagramDialog(); + } + }); + + ModelerSession.getActionControlService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + null, + ACTION_DELETE, + new ProModAction(ModelerSession.getCommonResourceBundle().getString( + ACTION_DELETE), + Resources.getIcon(Resources.MODELER + Resources.DELETE_ICON), + null){ + public void actionPerformed(ActionEvent event) { + removeItem(); + } + }); + + ModelerSession.getActionControlService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + null, + ACTION_CLOSE_PROJECT, + new ProModAction(ModelerSession.getCommonResourceBundle().getString(ACTION_CLOSE_PROJECT), null, null){ + public void actionPerformed(ActionEvent event) { + closeProject(); + } + }); + + ModelerSession.getActionControlService().registerAction( + ModelerModel.MODELER_IDENTIFIER, + null, + ACTION_REFRESH, + new ProModAction(ModelerSession.getCommonResourceBundle().getString( + ACTION_REFRESH), + null, + null){ + public void actionPerformed(ActionEvent event) { + refreshProject(); + } + }); + } + + /** + * Refresh the selected project with the file system structure. + */ + public void refreshProject(){ + final ProjectRoot selectedProjectRoot = ModelerSession.getProjectService().getSelectedProject(); + + if(selectedProjectRoot == null){ + LOG.warn("There is no selected project to be refreshed."); + return; + } + + ModelerSession.getProjectControlService().synchronize( + selectedProjectRoot.getProjectFile(), + null, + true, false, true, /*add, NOT over-write, delete */ + true + ); + } + + /** + * Closes the selected project = removes this project from the tree project model. + */ + private void closeProject() { + final TreePath treePath = ModelerSession.getProjectService().getSelectedProjectPath(); + + if(treePath != null){ + if(!Modeler.ExitDialogReturnValues.CANCEL.equals(checkForUnsavedChanges(treePath, treePath))){ + ModelerSession.getProjectControlService().removeProjectItem(treePath); + } + } + } + + /** + * Removed project selected item. + */ + private void removeItem() { + final TreePath selectedTreePath = ModelerSession.getProjectService().getSelectedTreePath(); + + if(selectedTreePath!= null){ + final DefaultMutableTreeNode node; + try{ + node = (DefaultMutableTreeNode) selectedTreePath.getLastPathComponent(); + } catch (ClassCastException exception){ + LOG.error("All project navigation nodes have to be an instance of DefaultMutableTreePath class."); + return; + } + + if(ProjectServiceUtils.isProjectDiagram(node)){ + final String title = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.diagram.title"); + final String message = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.diagram.message"); + + //show project dialog confirm. dialog + if(showRemoveConfirmDialog(title, message)){ + + final String fsPath = ModelerSession.getProjectControlService().removeProjectItem(selectedTreePath); + + if(fsPath == null){ + //should never happened, testing & debugging + LOG.error("Removal of project diagram has failed. Node: " + node.toString()); + } else { + //remove the file associated with the project diagram + if(!ProjectServiceUtils.deleteFSItem(selectedTreePath.getParentPath(), new File(fsPath).getName())){ + // file system deletion has failed + LOG.error("ProMod couldn't delete selected diagram from file system: " + fsPath); + } + } + } + + //show project subfolder confirm. dialog + } else if(ProjectServiceUtils.isProjectSubfolder(node)){ + final String title = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.diagram.title"); + final String message = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.subfolder.message"); + + if(showRemoveConfirmDialog(title, message)){ + + final String fsPath = ModelerSession.getProjectControlService().removeProjectItem(selectedTreePath); + + if(fsPath == null){ + //should never happened, testing & debugging + LOG.error("Removal of project subfolder has failed. Node: " + node.toString()); + } else { + //remove the file associated with the project diagram + if(!ProjectServiceUtils.deleteFSItem(selectedTreePath.getParentPath(), new File(fsPath).getName())){ + // file system deletion has failed + LOG.error("ProMod couldn't delete selected subfolder from file system: " + fsPath); + } + } + } + + // show !CLOSE! project dialog + } else if(ProjectServiceUtils.isProjectRoot(node)){ + final String title = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.project.title"); + final String message = ModelerSession.getCommonResourceBundle().getString("modeler.project.navigation.delete.project.message"); + + if(showRemoveConfirmDialog(title, message)){ + + final String fsPath = ModelerSession.getProjectControlService().removeProjectItem(selectedTreePath); + + if(fsPath == null){ + //should never happened, testing & debugging + LOG.error("Removal of project has failed."); + } + } + } else { + LOG.error("A user object of all nodes has to be an instance of ProjectRoot, ProjectSubFolder or ProjectDiagram class."); + } + } + + } + + /** + * Shows the confirm dialog before removing a project item. + * @param title is the title of the dialog. + * @param message is the text to be displayed + * @return true if the user's answer is YES + */ + private boolean showRemoveConfirmDialog(final String title, + final String message){ + final Object[] options = { + ModelerSession.getCommonResourceBundle().getString("modeler.ok"), + ModelerSession.getCommonResourceBundle().getString("modeler.cancel") + }; + + int dialogReturnValue = JOptionPane.showOptionDialog( + ModelerSession.getFrame(), + message, + title, + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, + options, + options[0]); + + return dialogReturnValue == JOptionPane.YES_OPTION; + } + + /** + * Initialize the event handling. + */ + private void initEventHandling() { + projectTree.addTreeSelectionListener(this); + + // + ModelerSession.getProjectService().getSelectedItem().addValueChangeListener(new PropertyChangeListener(){ + public void propertyChange(PropertyChangeEvent evt) { + TreePath treePath = (TreePath) evt.getNewValue(); + + // using JTree#setSelectionPath(null) has no effect only firing valueChange event holding old tree selection value + // so if null comes, the selection tree path is selected to the tree modelFactory's root node + if(treePath == null){ + treePath = new TreePath(ModelerSession.getProjectControlService().getProjectTreeModel().getRoot()); + } + + projectTree.setSelectionPath(treePath); + } + }); + + final MenuControlService menuControlService = (MenuControlService) ModelerSession.getMenuService(); + projectTree.addMouseListener(new MousePopup(menuControlService.getProjectTreePopupMenu(), projectTree)); + + expandButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + expandAll(true); + } + }); + + collapseButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + expandAll(false); + } + }); + + Action action = ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_DIAGRAM); + if(action != null){ + addDiagramButton.setAction(action); + addDiagramButton.setText(""); + } else { + LOG.error("Add diagram action is not available."); + } + + action = ModelerSession.getActionService().getAction( + ModelerModel.MODELER_IDENTIFIER, ACTION_ADD_SUBFOLDER); + if(action != null){ + addSubfolderButton.setAction(action); + addSubfolderButton.setText(""); + } else { + LOG.error("Add subfolder action is not available."); + } + } + + /** + * Initialize the tree. + */ + private void initProjectTree() { + projectTree.setCellRenderer(new ProjectNavigationCellRenderer()); + + projectTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + + final TreeModel treeModel = ModelerSession.getProjectControlService().getProjectTreeModel(); + + if(treeModel == null){ + LOG.error("TreeModel is null."); + } else { + projectTree.setModel(treeModel); + } + + } + + /** + * Expands or collapses the entire project tree. + * + * @param expand true for expansion, false for collapse + */ + private void expandAll(boolean expand) { + final TreeNode root = (TreeNode) projectTree.getModel().getRoot(); + expandAll(new TreePath(root), expand, -1); + + projectTree.expandPath(new TreePath(root)); + } + + /** + * Expands/collapses project tree navigation subtree that is specified by it's root - parent parameter. + * + * @param parent is the root of subtree to be expanded/collapsed + * @param expand true for expanding, false for collapsing + * @param depth is depth for expanding, 0 means no expanding, -1 stands for expand all + */ + private void expandAll(final TreePath parent, boolean expand, final int depth) { + final TreeNode node = (TreeNode)parent.getLastPathComponent(); + + if(depth == 0){ // depth == 0 -> stop, if depth < 0 -> expand all + return; + } + + if (node.getChildCount() >= 0) { + for (final Enumeration enumeration = node.children(); enumeration.hasMoreElements(); ) { + final TreeNode treeNode = (TreeNode) enumeration.nextElement(); + final TreePath path = parent.pathByAddingChild(treeNode); + + expandAll(path, expand, depth - 1); + } + } + + if (expand) { + projectTree.expandPath(parent); + } else { + projectTree.collapsePath(parent); + } + } + + /** + * Updates the ProjectService data when the project item selection has changed. + * @param e is the tree selection change + */ + public void valueChanged(TreeSelectionEvent e) { + ModelerSession.getProjectControlService().setSelectedItem(e.getPath()); + } + + /** + * Goes though all projects and all it's diagrams and checks whether the 'changed' flag of this + * diagrams is not set to true. Then it gives the user list of options what to do. + * + * @param itemTreePath is the tree path to the currently tested project navigation tree item + * @param rootTreePath is the tree path to the the currently tested project + * + * @return CONTINUE if the test is supposed to continue in a ordinary way, STOP if all changes are supposed to + * be skipped and CANCEL for cancel ProMod existing + */ + public Modeler.ExitDialogReturnValues checkForUnsavedChanges(final TreePath itemTreePath, + final TreePath rootTreePath) { + + final Object lastPathComponent = itemTreePath.getLastPathComponent(); + final ProjectRoot projectRoot = + (ProjectRoot) ((DefaultMutableTreeNode)rootTreePath.getLastPathComponent()).getUserObject(); + + if(lastPathComponent != null){ + final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) lastPathComponent; + + if(treeNode.getUserObject() instanceof ProjectDiagram){ + final ProjectDiagram projectDiagram = (ProjectDiagram) treeNode.getUserObject(); + + if(projectDiagram.isChanged()){ + final int dialogResult = JideOptionPane.showOptionDialog(this, + "["+ projectDiagram.getDisplayName() + "] " + Modeler.UNSAVED_CHANGE_LABEL, + Modeler.PROMOD_EXIT_LABEL + " - [" + projectRoot.getDisplayName() + "]", + JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, + null, Modeler.EXIT_DIALOG_OPTIONS, Modeler.EXIT_DIALOG_OPTIONS[0]); + + switch (dialogResult){ + case 0: // yes + ModelerSession.getProjectControlService().synchronize( + itemTreePath, true, true, false, true + ); + break; + case 1: //no + break; + case 2: //save all + LOG.info("Saving all changes in project: " + projectRoot.getDisplayName() + "."); + ModelerSession.getProjectControlService().synchronize( + rootTreePath, true, true, false, true + ); + return Modeler.ExitDialogReturnValues.STOP; + case 3: // skip all + LOG.info("Skipping all changes in project: " + projectRoot.getDisplayName() + "."); + return Modeler.ExitDialogReturnValues.STOP; + case 4: + case -1: // user clicked the closing cross of the dialog + return Modeler.ExitDialogReturnValues.CANCEL; + } + } + + } else { + for(int i = 0; i < treeNode.getChildCount(); i++){ + final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) treeNode.getChildAt(i); + + final Modeler.ExitDialogReturnValues value = checkForUnsavedChanges(itemTreePath.pathByAddingChild(childNode), rootTreePath); + + switch (value){ + case CANCEL: + return Modeler.ExitDialogReturnValues.CANCEL; + case STOP: + return Modeler.ExitDialogReturnValues.STOP; + } + } + } + } + + return Modeler.ExitDialogReturnValues.CONTINUE; + } } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/ProjectNavigationView.java b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/ProjectNavigationView.java index 5fec9a7..65240f5 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/ProjectNavigationView.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/ProjectNavigationView.java @@ -1,117 +1,117 @@ -package cz.cvut.promod.gui.projectNavigation; - -import com.jidesoft.docking.DockableFrame; -import com.jidesoft.docking.DockContext; -import com.jgoodies.forms.layout.FormLayout; -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.factories.Borders; - -import javax.swing.*; -import java.awt.*; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; -import cz.cvut.promod.resources.Resources; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 15:53:36, 11.10.2009 - */ - -/** - * * Project navigation view. - */ -public class ProjectNavigationView extends DockableFrame{ - - private static final Dimension DEFAULT_SIZE = new Dimension(300, 400); - - protected final JTree projectTree = ModelerSession.getComponentFactoryService().createTree(); - - private final JScrollPane scrollPane = ModelerSession.getComponentFactoryService().createScrollPane(projectTree); - - protected final JButton expandButton = ModelerSession.getComponentFactoryService().createButton(null, - Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.EXPAND_ALL_ICON)); - - protected final JButton collapseButton = ModelerSession.getComponentFactoryService().createButton(null, - Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.COLLAPSE_ICON)); - - protected final JButton addDiagramButton = ModelerSession.getComponentFactoryService().createButton(null, null); - - protected final JButton addSubfolderButton = ModelerSession.getComponentFactoryService().createButton(null, null); - - /** - * Constructs a new dockable frame representing the project navigation tree. - * - * @param dockableFrameIndex is the index of the dockable frame - */ - public ProjectNavigationView(final int dockableFrameIndex){ - super("project navigation"); - - initializeTree(); - - initializeDockableFrame(dockableFrameIndex); - } - - /** - * Initialize the tree. - */ - private void initializeTree() { - projectTree.setRootVisible(false); - } - - /** - * Initialize the navigation dockable frame. - */ - private void initializeDockableFrame(final int dockableFrameIndex) { - setPreferredSize(DEFAULT_SIZE); - - getContext().setInitMode(DockContext.STATE_FRAMEDOCKED); - getContext().setInitSide(DockContext.DOCK_SIDE_WEST); - getContext().setInitIndex(dockableFrameIndex); - getContext().setFloatable(false); - - setSideDockAllowed(false); - setAutohidable(false); - setHidable(false); - setRearrangable(false); - - add(createProjectNavigationPane()); - } - - /** - * Creates the dockable frame representing the project navigation. - * @return the project navigation dockable frame - */ - private JPanel createProjectNavigationPane() { - final JPanel projectNavigationPane = ModelerSession.getComponentFactoryService().createPanel(); - - projectNavigationPane.setLayout(new BorderLayout()); - projectNavigationPane.add(createNorthControlPane(), BorderLayout.NORTH); - projectNavigationPane.add(scrollPane, BorderLayout.CENTER); - - return projectNavigationPane; - } - - /** - * @return the control panel placed on the top of project navigation - */ - private JPanel createNorthControlPane() { - final JPanel northControlPane = ModelerSession.getComponentFactoryService().createPanel(); - - northControlPane.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - northControlPane.setLayout(new FormLayout( - "pref, 3dlu, pref, 3dlu, pref, 3dlu, pref", - "pref")); - final CellConstraints cellConstraints = new CellConstraints(); - - northControlPane.add(addDiagramButton, cellConstraints.xy(1,1)); - northControlPane.add(addSubfolderButton, cellConstraints.xy(3,1)); - northControlPane.add(expandButton, cellConstraints.xy(5,1)); - northControlPane.add(collapseButton, cellConstraints.xy(7,1)); - - return northControlPane; - } - -} +package cz.cvut.promod.gui.projectNavigation; + +import com.jidesoft.docking.DockableFrame; +import com.jidesoft.docking.DockContext; +import com.jgoodies.forms.layout.FormLayout; +import com.jgoodies.forms.layout.CellConstraints; +import com.jgoodies.forms.factories.Borders; + +import javax.swing.*; +import java.awt.*; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; +import cz.cvut.promod.resources.Resources; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 15:53:36, 11.10.2009 + */ + +/** + * * Project navigation view. + */ +public class ProjectNavigationView extends DockableFrame{ + + private static final Dimension DEFAULT_SIZE = new Dimension(300, 400); + + protected final JTree projectTree = ModelerSession.getComponentFactoryService().createTree(); + + private final JScrollPane scrollPane = ModelerSession.getComponentFactoryService().createScrollPane(projectTree); + + protected final JButton expandButton = ModelerSession.getComponentFactoryService().createButton(null, + Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.EXPAND_ALL_ICON)); + + protected final JButton collapseButton = ModelerSession.getComponentFactoryService().createButton(null, + Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.COLLAPSE_ICON)); + + protected final JButton addDiagramButton = ModelerSession.getComponentFactoryService().createButton(null, null); + + protected final JButton addSubfolderButton = ModelerSession.getComponentFactoryService().createButton(null, null); + + /** + * Constructs a new dockable frame representing the project navigation tree. + * + * @param dockableFrameIndex is the index of the dockable frame + */ + public ProjectNavigationView(final int dockableFrameIndex){ + super("project navigation"); + + initializeTree(); + + initializeDockableFrame(dockableFrameIndex); + } + + /** + * Initialize the tree. + */ + private void initializeTree() { + projectTree.setRootVisible(false); + } + + /** + * Initialize the navigation dockable frame. + */ + private void initializeDockableFrame(final int dockableFrameIndex) { + setPreferredSize(DEFAULT_SIZE); + + getContext().setInitMode(DockContext.STATE_FRAMEDOCKED); + getContext().setInitSide(DockContext.DOCK_SIDE_WEST); + getContext().setInitIndex(dockableFrameIndex); + getContext().setFloatable(false); + + setSideDockAllowed(false); + setAutohidable(false); + setHidable(false); + setRearrangable(false); + + add(createProjectNavigationPane()); + } + + /** + * Creates the dockable frame representing the project navigation. + * @return the project navigation dockable frame + */ + private JPanel createProjectNavigationPane() { + final JPanel projectNavigationPane = ModelerSession.getComponentFactoryService().createPanel(); + + projectNavigationPane.setLayout(new BorderLayout()); + projectNavigationPane.add(createNorthControlPane(), BorderLayout.NORTH); + projectNavigationPane.add(scrollPane, BorderLayout.CENTER); + + return projectNavigationPane; + } + + /** + * @return the control panel placed on the top of project navigation + */ + private JPanel createNorthControlPane() { + final JPanel northControlPane = ModelerSession.getComponentFactoryService().createPanel(); + + northControlPane.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + northControlPane.setLayout(new FormLayout( + "pref, 3dlu, pref, 3dlu, pref, 3dlu, pref", + "pref")); + final CellConstraints cellConstraints = new CellConstraints(); + + northControlPane.add(addDiagramButton, cellConstraints.xy(1,1)); + northControlPane.add(addSubfolderButton, cellConstraints.xy(3,1)); + northControlPane.add(expandButton, cellConstraints.xy(5,1)); + northControlPane.add(collapseButton, cellConstraints.xy(7,1)); + + return northControlPane; + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/actions/executors/RenameExecutor.java b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/actions/executors/RenameExecutor.java index 3234800..e957534 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/actions/executors/RenameExecutor.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/actions/executors/RenameExecutor.java @@ -1,143 +1,143 @@ -package cz.cvut.promod.gui.projectNavigation.actions.executors; - -import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialogExecutor; -import cz.cvut.promod.gui.projectNavigation.ProjectNavigation; -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectItem; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectContainer; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; -import cz.cvut.promod.services.projectService.results.SaveProjectResult; -import cz.cvut.promod.services.projectService.ProjectService; -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.tree.TreePath; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.*; -import java.io.File; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 3:45:36, 17.4.2010 - */ - -/** - * Simple executor for the standard text dialog performing project item rename action. - * - * @see cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialogExecutor - */ -public class RenameExecutor implements SimpleTextFieldDialogExecutor { - - private static final Logger LOG = Logger.getLogger(RenameExecutor.class); - - private final TreePath treePath; - private final ProjectItem projectItem; - private final JTree projectTree; - - - public RenameExecutor(final TreePath treePath, final ProjectItem projectItem, final JTree projectTree) { - this.treePath = treePath; - this.projectItem = projectItem; - this.projectTree = projectTree; - } - /**{@inheritDoc} performs the rename action*/ - public String execute(final String text) { - if(ProjectServiceUtils.isSyntacticallyCorrectName(text)){ - if(isDuplicitName(treePath.getParentPath(), projectItem, text)){ - return ProjectNavigation.DUPLICATE_NAME_LABEL; - } - - File file = new File(ProjectServiceUtils.getFileSystemPathToProjectItem(treePath)); - final String oldName = projectItem.getDisplayName(); - - if(projectItem instanceof ProjectRoot){ - projectItem.setDisplayName(text); - if(SaveProjectResult.SUCCESS.equals(ModelerSession.getProjectControlService().saveProject(treePath))){ - file = new File(file, oldName + ProjectService.PROJECT_FILE_EXTENSION); - if(file.exists()){ - ProjectServiceUtils.removeDirectory(file); - } else { - showError(); - } - } else { - showError(); - projectItem.setDisplayName(oldName); - } - - } else { - projectItem.setDisplayName(text); - if(ModelerSession.getProjectControlService().synchronize(treePath, true, false, false, false)){ - if(file.exists()){ - ProjectServiceUtils.removeDirectory(file); - } else { - showError(); - } - } else { - projectItem.setDisplayName(oldName); - showError(); - } - } - projectTree.updateUI(); - - return null; - } - - return ProjectNavigation.INVALID_NAME_LABEL + ProjectServiceUtils.getDisallowedNameSymbols(','); - } - - private boolean isDuplicitName(final TreePath treePath, final ProjectItem projectItem, final String newText){ - if(treePath.getLastPathComponent() instanceof DefaultMutableTreeNode){ - final DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - - for(int i = 0; i < defaultMutableTreeNode.getChildCount(); i++){ - if(defaultMutableTreeNode.getChildAt(i) instanceof DefaultMutableTreeNode){ - final DefaultMutableTreeNode node = (DefaultMutableTreeNode) defaultMutableTreeNode.getChildAt(i); - - if(node.getUserObject() instanceof ProjectItem){ - final ProjectItem testedProjectItem = (ProjectItem) node.getUserObject(); - - if(testedProjectItem == projectItem){ - continue; - } - - if(testedProjectItem.getDisplayName() != null && testedProjectItem.getDisplayName().equals(newText)){ - if((testedProjectItem instanceof ProjectContainer) && (projectItem instanceof ProjectContainer)){ - return true; - } - else if((testedProjectItem instanceof ProjectDiagram) && (projectItem instanceof ProjectDiagram)){ - final ProjectDiagram testedProjectDiagram = (ProjectDiagram) testedProjectItem; - final ProjectDiagram projectDiagram = (ProjectDiagram) projectItem; - - if(testedProjectDiagram.getNotationIdentifier().equals(projectDiagram.getNotationIdentifier())){ - return true; - } - } - } - } - - } - } - } else { - LOG.error("A node is not an instance od DefaultMutableTreeNode"); - } - - - return false; - } - - /** - * Shows an error. - */ - private void showError(){ - JOptionPane.showMessageDialog( - ModelerSession.getFrame(), - ProjectNavigation.RENAME_ERROR_LABEL, - ProjectNavigation.RENAME_ERROR_TITLE_LABEL, - JOptionPane.ERROR_MESSAGE); - } - - -} +package cz.cvut.promod.gui.projectNavigation.actions.executors; + +import cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialogExecutor; +import cz.cvut.promod.gui.projectNavigation.ProjectNavigation; +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectItem; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectContainer; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; +import cz.cvut.promod.services.projectService.results.SaveProjectResult; +import cz.cvut.promod.services.projectService.ProjectService; +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.tree.TreePath; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.*; +import java.io.File; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 3:45:36, 17.4.2010 + */ + +/** + * Simple executor for the standard text dialog performing project item rename action. + * + * @see cz.cvut.promod.gui.dialogs.simpleTextFieldDialog.SimpleTextFieldDialogExecutor + */ +public class RenameExecutor implements SimpleTextFieldDialogExecutor { + + private static final Logger LOG = Logger.getLogger(RenameExecutor.class); + + private final TreePath treePath; + private final ProjectItem projectItem; + private final JTree projectTree; + + + public RenameExecutor(final TreePath treePath, final ProjectItem projectItem, final JTree projectTree) { + this.treePath = treePath; + this.projectItem = projectItem; + this.projectTree = projectTree; + } + /**{@inheritDoc} performs the rename action*/ + public String execute(final String text) { + if(ProjectServiceUtils.isSyntacticallyCorrectName(text)){ + if(isDuplicitName(treePath.getParentPath(), projectItem, text)){ + return ProjectNavigation.DUPLICATE_NAME_LABEL; + } + + File file = new File(ProjectServiceUtils.getFileSystemPathToProjectItem(treePath)); + final String oldName = projectItem.getDisplayName(); + + if(projectItem instanceof ProjectRoot){ + projectItem.setDisplayName(text); + if(SaveProjectResult.SUCCESS.equals(ModelerSession.getProjectControlService().saveProject(treePath))){ + file = new File(file, oldName + ProjectService.PROJECT_FILE_EXTENSION); + if(file.exists()){ + ProjectServiceUtils.removeDirectory(file); + } else { + showError(); + } + } else { + showError(); + projectItem.setDisplayName(oldName); + } + + } else { + projectItem.setDisplayName(text); + if(ModelerSession.getProjectControlService().synchronize(treePath, true, false, false, false)){ + if(file.exists()){ + ProjectServiceUtils.removeDirectory(file); + } else { + showError(); + } + } else { + projectItem.setDisplayName(oldName); + showError(); + } + } + projectTree.updateUI(); + + return null; + } + + return ProjectNavigation.INVALID_NAME_LABEL + ProjectServiceUtils.getDisallowedNameSymbols(','); + } + + private boolean isDuplicitName(final TreePath treePath, final ProjectItem projectItem, final String newText){ + if(treePath.getLastPathComponent() instanceof DefaultMutableTreeNode){ + final DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + + for(int i = 0; i < defaultMutableTreeNode.getChildCount(); i++){ + if(defaultMutableTreeNode.getChildAt(i) instanceof DefaultMutableTreeNode){ + final DefaultMutableTreeNode node = (DefaultMutableTreeNode) defaultMutableTreeNode.getChildAt(i); + + if(node.getUserObject() instanceof ProjectItem){ + final ProjectItem testedProjectItem = (ProjectItem) node.getUserObject(); + + if(testedProjectItem == projectItem){ + continue; + } + + if(testedProjectItem.getDisplayName() != null && testedProjectItem.getDisplayName().equals(newText)){ + if((testedProjectItem instanceof ProjectContainer) && (projectItem instanceof ProjectContainer)){ + return true; + } + else if((testedProjectItem instanceof ProjectDiagram) && (projectItem instanceof ProjectDiagram)){ + final ProjectDiagram testedProjectDiagram = (ProjectDiagram) testedProjectItem; + final ProjectDiagram projectDiagram = (ProjectDiagram) projectItem; + + if(testedProjectDiagram.getNotationIdentifier().equals(projectDiagram.getNotationIdentifier())){ + return true; + } + } + } + } + + } + } + } else { + LOG.error("A node is not an instance od DefaultMutableTreeNode"); + } + + + return false; + } + + /** + * Shows an error. + */ + private void showError(){ + JOptionPane.showMessageDialog( + ModelerSession.getFrame(), + ProjectNavigation.RENAME_ERROR_LABEL, + ProjectNavigation.RENAME_ERROR_TITLE_LABEL, + JOptionPane.ERROR_MESSAGE); + } + + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/events/ProjectTreeExpandEvent.java b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/events/ProjectTreeExpandEvent.java index e8d8716..7a30d26 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/events/ProjectTreeExpandEvent.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/events/ProjectTreeExpandEvent.java @@ -1,53 +1,53 @@ -package cz.cvut.promod.gui.projectNavigation.events; - -import javax.swing.tree.TreePath; -import java.awt.event.ActionEvent; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 12:54:20, 24.1.2010 - */ - -/** - * Represent an extension of ActionEvent that hold tree path and depth for expanding/collapsing - * project tree navigation. - */ -public class ProjectTreeExpandEvent extends ActionEvent{ - - private final TreePath treePath; - - private final int depth; // if depth < 1 -> expand/collapse all - - private final boolean expand; - - /** - * Constructs a new event for expand/collapse project tree action. - * - * @param source is the source of action - * @param treePath is the root of subtree to be expanded/collapsed - * @param depth is the depth for expanding, -1 stands for expand all - * @param expand true for expanding, false for collapsing - */ - public ProjectTreeExpandEvent(final Object source, - final TreePath treePath, - final int depth, final boolean expand) { - super(source, 0, null); - - this.treePath = treePath; - this.depth = depth; - this.expand = expand; - } - - public TreePath getTreePath() { - return treePath; - } - - public int getDepth() { - return depth; - } - - public boolean isExpand() { - return expand; - } -} +package cz.cvut.promod.gui.projectNavigation.events; + +import javax.swing.tree.TreePath; +import java.awt.event.ActionEvent; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 12:54:20, 24.1.2010 + */ + +/** + * Represent an extension of ActionEvent that hold tree path and depth for expanding/collapsing + * project tree navigation. + */ +public class ProjectTreeExpandEvent extends ActionEvent{ + + private final TreePath treePath; + + private final int depth; // if depth < 1 -> expand/collapse all + + private final boolean expand; + + /** + * Constructs a new event for expand/collapse project tree action. + * + * @param source is the source of action + * @param treePath is the root of subtree to be expanded/collapsed + * @param depth is the depth for expanding, -1 stands for expand all + * @param expand true for expanding, false for collapsing + */ + public ProjectTreeExpandEvent(final Object source, + final TreePath treePath, + final int depth, final boolean expand) { + super(source, 0, null); + + this.treePath = treePath; + this.depth = depth; + this.expand = expand; + } + + public TreePath getTreePath() { + return treePath; + } + + public int getDepth() { + return depth; + } + + public boolean isExpand() { + return expand; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/listeners/MousePopup.java b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/listeners/MousePopup.java index 6b40d56..5c40158 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/listeners/MousePopup.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/listeners/MousePopup.java @@ -1,55 +1,55 @@ -package cz.cvut.promod.gui.projectNavigation.listeners; - -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.*; -import javax.swing.tree.TreePath; -import java.awt.event.MouseEvent; -import java.awt.event.MouseAdapter; -import java.awt.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:10:30, 22.10.2009 - */ - -/** - * Project navigation mouse popup menu listener. - */ -public class MousePopup extends MouseAdapter { - - final JPopupMenu popup; - final JTree tree; - - public MousePopup(final JPopupMenu popup, final JTree tree){ - this.popup = popup; - this.tree = tree; - } - - @Override - public void mousePressed(final MouseEvent event) { - showPopupMenu(event); - } - - @Override - public void mouseReleased(final MouseEvent event) { - showPopupMenu(event); - } - - /** - * Shows the popup menu. - * - * @param event the mouse event - */ - private void showPopupMenu(final MouseEvent event){ - if (event.isPopupTrigger()) { - final TreePath treePath = tree.getPathForLocation(event.getX(), event.getY()); - - if(treePath != null){ - ModelerSession.getProjectControlService().setSelectedItem(treePath); - popup.show((Component)event.getSource(),event.getX(), event.getY()); - } - } - } -} +package cz.cvut.promod.gui.projectNavigation.listeners; + +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.*; +import javax.swing.tree.TreePath; +import java.awt.event.MouseEvent; +import java.awt.event.MouseAdapter; +import java.awt.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:10:30, 22.10.2009 + */ + +/** + * Project navigation mouse popup menu listener. + */ +public class MousePopup extends MouseAdapter { + + final JPopupMenu popup; + final JTree tree; + + public MousePopup(final JPopupMenu popup, final JTree tree){ + this.popup = popup; + this.tree = tree; + } + + @Override + public void mousePressed(final MouseEvent event) { + showPopupMenu(event); + } + + @Override + public void mouseReleased(final MouseEvent event) { + showPopupMenu(event); + } + + /** + * Shows the popup menu. + * + * @param event the mouse event + */ + private void showPopupMenu(final MouseEvent event){ + if (event.isPopupTrigger()) { + final TreePath treePath = tree.getPathForLocation(event.getX(), event.getY()); + + if(treePath != null){ + ModelerSession.getProjectControlService().setSelectedItem(treePath); + popup.show((Component)event.getSource(),event.getX(), event.getY()); + } + } + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/renderer/ProjectNavigationCellRenderer.java b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/renderer/ProjectNavigationCellRenderer.java index 68024f0..eefe37b 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/renderer/ProjectNavigationCellRenderer.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/projectNavigation/renderer/ProjectNavigationCellRenderer.java @@ -1,167 +1,167 @@ -package cz.cvut.promod.gui.projectNavigation.renderer; - -import org.apache.log4j.Logger; - -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.*; -import java.awt.*; -import java.util.Map; -import java.util.HashMap; - -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectSubFolder; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.resources.Resources; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:26:52, 30.11.2009 - */ - -/** - * Tree node cell renderer that renders special icons for the node that are project roots, - * special ones for nodes that are project subfolderes and special nodes for nodes, that are - * project diagrams. Diagrams can have special icon related to it's notation. - */ -public class ProjectNavigationCellRenderer extends DefaultTreeCellRenderer{ - - private static final Logger LOG = Logger.getLogger(ProjectNavigationCellRenderer.class); - - private final static Map iconMap; // holds notation specific icons - - private final static ImageIcon projectRootIcon; - private final static ImageIcon projectSubfolderIcon; - private final static ImageIcon defaultProjectDiagramIcon; // default diagram icon, if no notation specific is set - - // static constructor - static{ - projectRootIcon = Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.PROJECT_ICON); - projectSubfolderIcon = Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.SUBFOLDER_ICON); - defaultProjectDiagramIcon = Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.DIAGRAM_ICON); - - iconMap = new HashMap(); - } - - @Override - public Component getTreeCellRendererComponent(final JTree tree, - final Object object, - final boolean selected, - final boolean expanded, - final boolean leaf, - final int row, - final boolean hasFocus) { - - final Component component = super.getTreeCellRendererComponent( - tree, object, selected, expanded, leaf,row, hasFocus - ); - - if(component instanceof JLabel){ - if(isProjectRoot(object)){ - setFont(new Font(getFont().getName(), Font.BOLD, getFont().getSize())); - setIcon(projectRootIcon); - - final JLabel label = (JLabel) component; - label.setToolTipText(null); - - } else if(isProjectSubfolder(object)){ - setFont(new Font(getFont().getName(), Font.PLAIN, getFont().getSize())); - setIcon(projectSubfolderIcon); - - final JLabel label = (JLabel) component; - label.setToolTipText(null); - - } else if(isProjectDiagram(object)){ - setFont(new Font(getFont().getName(), Font.PLAIN, getFont().getSize())); - setIcon(getProjectDiagramIcon(object)); - - try{ - final ProjectDiagram projectDiagram = (ProjectDiagram) getTreeNode(object).getUserObject(); - final String toolTip = ModelerSession.getNotationService().getNotation(projectDiagram.getNotationIdentifier()).getNotationToolTip(); - - final JLabel label = (JLabel) component; - if(toolTip != null){ - label.setToolTipText(toolTip); - } else { - label.setToolTipText(null); - } - - } catch (Exception e){ - LOG.error("Not possible to set the tree item tool tip"); - } - } - - } else{ - LOG.error("Project navigation tree cell component is not an instance of JLabel. Wrong icons can occurred in project navigation."); - } - - return component; - } - - /** - * @param object is the node (DefaultMutableTreeNode) - * @return the project diagram icon specified by the notation - */ - private Icon getProjectDiagramIcon(final Object object) { - final ProjectDiagram projectDiagram = (ProjectDiagram) ((DefaultMutableTreeNode)object).getUserObject(); - final String notationIdentifier = projectDiagram.getNotationIdentifier(); - - if(iconMap.containsKey(notationIdentifier)){ - return iconMap.get(notationIdentifier); - } - - Icon icon = ModelerSession.getNotationService().getNotation(notationIdentifier).getNotationIcon(); - - if(icon == null){ - icon = defaultProjectDiagramIcon; - } - - iconMap.put(notationIdentifier, icon); - - return icon; - } - - /** - * @param object is a node - * @return object casted as DefaultMutableTreeNode if possible, null otherwise - */ - private DefaultMutableTreeNode getTreeNode(final Object object){ - if(object instanceof DefaultMutableTreeNode){ - return (DefaultMutableTreeNode) object; - } - - return null; - } - - /** - * @param object is a tree node - * @return true if the node holds the Project Root - */ - private boolean isProjectRoot(final Object object){ - final DefaultMutableTreeNode node = getTreeNode(object); - - return node.getUserObject() instanceof ProjectRoot; - } - - /** - * @param object is a tree node - * @return true if the node holds the Project Subfolder - */ - private boolean isProjectSubfolder(final Object object){ - final DefaultMutableTreeNode node = getTreeNode(object); - - return node.getUserObject() instanceof ProjectSubFolder; - } - - /** - * @param object is a tree node - * @return true if the node holds the Project Diagram - */ - private boolean isProjectDiagram(final Object object){ - final DefaultMutableTreeNode node = getTreeNode(object); - - return node.getUserObject() instanceof ProjectDiagram; - } -} +package cz.cvut.promod.gui.projectNavigation.renderer; + +import org.apache.log4j.Logger; + +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.*; +import java.awt.*; +import java.util.Map; +import java.util.HashMap; + +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectSubFolder; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.resources.Resources; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:26:52, 30.11.2009 + */ + +/** + * Tree node cell renderer that renders special icons for the node that are project roots, + * special ones for nodes that are project subfolderes and special nodes for nodes, that are + * project diagrams. Diagrams can have special icon related to it's notation. + */ +public class ProjectNavigationCellRenderer extends DefaultTreeCellRenderer{ + + private static final Logger LOG = Logger.getLogger(ProjectNavigationCellRenderer.class); + + private final static Map iconMap; // holds notation specific icons + + private final static ImageIcon projectRootIcon; + private final static ImageIcon projectSubfolderIcon; + private final static ImageIcon defaultProjectDiagramIcon; // default diagram icon, if no notation specific is set + + // static constructor + static{ + projectRootIcon = Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.PROJECT_ICON); + projectSubfolderIcon = Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.SUBFOLDER_ICON); + defaultProjectDiagramIcon = Resources.getIcon(Resources.NAVIGATION + Resources.ICONS + Resources.DIAGRAM_ICON); + + iconMap = new HashMap(); + } + + @Override + public Component getTreeCellRendererComponent(final JTree tree, + final Object object, + final boolean selected, + final boolean expanded, + final boolean leaf, + final int row, + final boolean hasFocus) { + + final Component component = super.getTreeCellRendererComponent( + tree, object, selected, expanded, leaf,row, hasFocus + ); + + if(component instanceof JLabel){ + if(isProjectRoot(object)){ + setFont(new Font(getFont().getName(), Font.BOLD, getFont().getSize())); + setIcon(projectRootIcon); + + final JLabel label = (JLabel) component; + label.setToolTipText(null); + + } else if(isProjectSubfolder(object)){ + setFont(new Font(getFont().getName(), Font.PLAIN, getFont().getSize())); + setIcon(projectSubfolderIcon); + + final JLabel label = (JLabel) component; + label.setToolTipText(null); + + } else if(isProjectDiagram(object)){ + setFont(new Font(getFont().getName(), Font.PLAIN, getFont().getSize())); + setIcon(getProjectDiagramIcon(object)); + + try{ + final ProjectDiagram projectDiagram = (ProjectDiagram) getTreeNode(object).getUserObject(); + final String toolTip = ModelerSession.getNotationService().getNotation(projectDiagram.getNotationIdentifier()).getNotationToolTip(); + + final JLabel label = (JLabel) component; + if(toolTip != null){ + label.setToolTipText(toolTip); + } else { + label.setToolTipText(null); + } + + } catch (Exception e){ + LOG.error("Not possible to set the tree item tool tip"); + } + } + + } else{ + LOG.error("Project navigation tree cell component is not an instance of JLabel. Wrong icons can occurred in project navigation."); + } + + return component; + } + + /** + * @param object is the node (DefaultMutableTreeNode) + * @return the project diagram icon specified by the notation + */ + private Icon getProjectDiagramIcon(final Object object) { + final ProjectDiagram projectDiagram = (ProjectDiagram) ((DefaultMutableTreeNode)object).getUserObject(); + final String notationIdentifier = projectDiagram.getNotationIdentifier(); + + if(iconMap.containsKey(notationIdentifier)){ + return iconMap.get(notationIdentifier); + } + + Icon icon = ModelerSession.getNotationService().getNotation(notationIdentifier).getNotationIcon(); + + if(icon == null){ + icon = defaultProjectDiagramIcon; + } + + iconMap.put(notationIdentifier, icon); + + return icon; + } + + /** + * @param object is a node + * @return object casted as DefaultMutableTreeNode if possible, null otherwise + */ + private DefaultMutableTreeNode getTreeNode(final Object object){ + if(object instanceof DefaultMutableTreeNode){ + return (DefaultMutableTreeNode) object; + } + + return null; + } + + /** + * @param object is a tree node + * @return true if the node holds the Project Root + */ + private boolean isProjectRoot(final Object object){ + final DefaultMutableTreeNode node = getTreeNode(object); + + return node.getUserObject() instanceof ProjectRoot; + } + + /** + * @param object is a tree node + * @return true if the node holds the Project Subfolder + */ + private boolean isProjectSubfolder(final Object object){ + final DefaultMutableTreeNode node = getTreeNode(object); + + return node.getUserObject() instanceof ProjectSubFolder; + } + + /** + * @param object is a tree node + * @return true if the node holds the Project Diagram + */ + private boolean isProjectDiagram(final Object object){ + final DefaultMutableTreeNode node = getTreeNode(object); + + return node.getUserObject() instanceof ProjectDiagram; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/settings/BasicSettingPage.java b/IndependentModeler/src/cz/cvut/promod/gui/settings/BasicSettingPage.java index 282ece4..6da92a3 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/settings/BasicSettingPage.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/settings/BasicSettingPage.java @@ -1,47 +1,47 @@ -package cz.cvut.promod.gui.settings; - -import com.jidesoft.dialog.AbstractDialogPage; - -import javax.swing.*; -import java.awt.*; - -import cz.cvut.promod.services.ModelerSession; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:32:45, 24.1.2010 - * - * - * Basic settings of the host application for the settings dialog. - */ -public class BasicSettingPage extends AbstractDialogPage { - - private static final String SETTINGS_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.settings"); - - private final JLabel label = ModelerSession.getComponentFactoryService().createLabel(""); - - - public BasicSettingPage(final String name) { - super(name); - } - - public BasicSettingPage(final String name, final Icon icon) { - super(name, icon); - } - - public void lazyInitialize() { - label.setText("[" + getName() + "] " + SETTINGS_LABEL); - - initLayout(); - } - - public void initLayout() { - setLayout(new BorderLayout()); - - label.setHorizontalAlignment(JLabel.CENTER); - - add(label, BorderLayout.CENTER); - } - -} +package cz.cvut.promod.gui.settings; + +import com.jidesoft.dialog.AbstractDialogPage; + +import javax.swing.*; +import java.awt.*; + +import cz.cvut.promod.services.ModelerSession; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:32:45, 24.1.2010 + * + * + * Basic settings of the host application for the settings dialog. + */ +public class BasicSettingPage extends AbstractDialogPage { + + private static final String SETTINGS_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.settings"); + + private final JLabel label = ModelerSession.getComponentFactoryService().createLabel(""); + + + public BasicSettingPage(final String name) { + super(name); + } + + public BasicSettingPage(final String name, final Icon icon) { + super(name, icon); + } + + public void lazyInitialize() { + label.setText("[" + getName() + "] " + SETTINGS_LABEL); + + initLayout(); + } + + public void initLayout() { + setLayout(new BorderLayout()); + + label.setHorizontalAlignment(JLabel.CENTER); + + add(label, BorderLayout.CENTER); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/settings/SettingsDialog.java b/IndependentModeler/src/cz/cvut/promod/gui/settings/SettingsDialog.java index 7064266..9fb3527 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/settings/SettingsDialog.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/settings/SettingsDialog.java @@ -1,172 +1,172 @@ -package cz.cvut.promod.gui.settings; - -import com.jidesoft.dialog.*; -import com.jidesoft.swing.JideSwingUtilities; -import com.jidesoft.swing.PartialEtchedBorder; - -import java.awt.*; -import java.awt.event.*; - -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.*; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.border.EtchedBorder; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 14:47:40, 24.1.2010 - */ - -/** - * Implementation of the common settings dialog. - */ -public class SettingsDialog extends MultiplePageDialog{ - - private static final String OK_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.ok"); - private static final String CANCEL_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.cancel"); - private static final String APPLY_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.apply"); - - private static final int INIT_WIDTH = 800; - private static final int INIT_HEIGHT = 600; - - public static final String TITLE_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.settings"); - - private final AbstractAction cancelAction; - private final AbstractAction okAction; - private final AbstractAction applyAction; - - - public SettingsDialog(final Frame parentFrame, final String title){ - super(parentFrame, title); - - applyAction = new AbstractAction(APPLY_LABEL) { - public void actionPerformed(ActionEvent e) { - fireButtonEvent(ButtonNames.APPLY); - setEnabled(false); - } - }; - - cancelAction = new AbstractAction(CANCEL_LABEL) { - public void actionPerformed(ActionEvent e) { - fireButtonEvent(ButtonNames.CANCEL); - setDialogResult(RESULT_CANCELLED); - setVisible(false); - applyAction.setEnabled(false); - dispose(); - } - }; - - okAction = new AbstractAction(OK_LABEL) { - public void actionPerformed(ActionEvent e) { - fireButtonEvent(ButtonNames.OK); - setDialogResult(RESULT_AFFIRMED); - setVisible(false); - applyAction.setEnabled(false); - dispose(); - } - }; - - getRootPane().registerKeyboardAction(new ActionListener(){ - public void actionPerformed(ActionEvent actionEvent) { - cancelAction.actionPerformed(null); - } - }, - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - - initEventHandling(); - } - - @Override - protected JTree createTree(DefaultMutableTreeNode root) { - return ModelerSession.getComponentFactoryService().createTree(root); - } - - private void initEventHandling() { - addWindowListener(new WindowAdapter(){ - @Override - public void windowClosing(WindowEvent windowEvent) { - cancelAction.actionPerformed(null); - } - }); - } - - - @Override - public ButtonPanel createButtonPanel() { - final ButtonPanel buttonPanel = super.createButtonPanel(); - - applyAction.setEnabled(false); - - ((JButton) buttonPanel.getButtonByName(ButtonNames.OK)).setAction(okAction); - ((JButton) buttonPanel.getButtonByName(ButtonNames.CANCEL)).setAction(cancelAction); - ((JButton) buttonPanel.getButtonByName(ButtonNames.APPLY)).setAction(applyAction); - - setDefaultAction(okAction); - - return buttonPanel; - } - - /** - * When an button of settings dialog has been pressed (i.g. OK, CANCEL, ...) all pages the has a registered - * instance of ButtonListener class will be notified about this event. - * - * @param buttonName is the name of the button that has been pressed - */ - private void fireButtonEvent(final String buttonName){ - final PageList pageList = getPageList(); - - for(int i = 0; i < pageList.getSize(); i++){ - final AbstractDialogPage page = pageList.getPage(i); - - page.fireButtonEvent(0, buttonName); - } - } - - @Override - public Dimension getPreferredSize() { - return new Dimension(INIT_WIDTH, INIT_HEIGHT); - } - - @Override - protected void initComponents() { - super.initComponents(); - - getContentPanel().setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10)); - - getIndexPanel().setBackground(Color.white); - - getButtonPanel().setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - - getPagesPanel().setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createEmptyBorder(0, 10, 0, 0), - new PartialEtchedBorder(EtchedBorder.LOWERED, PartialEtchedBorder.SOUTH))); - } - - /** - * Shows a settings dialog. - * - * @param settingPagesModel is the list of settings pages defined by plugins - */ - public static void showOptionsDialog(final PageList settingPagesModel) { - final PageList pages = new PageList(); - - for(int i = 0; i < settingPagesModel.getPageCount(); i++){ - pages.append(settingPagesModel.getPage(i)); - } - - final MultiplePageDialog dialog = new SettingsDialog(ModelerSession.getFrame(), TITLE_LABEL); - - dialog.setStyle(MultiplePageDialog.TREE_STYLE); - dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); - - dialog.setPageList(pages); - - dialog.pack(); - JideSwingUtilities.globalCenterWindow(dialog); - dialog.setVisible(true); - } - -} +package cz.cvut.promod.gui.settings; + +import com.jidesoft.dialog.*; +import com.jidesoft.swing.JideSwingUtilities; +import com.jidesoft.swing.PartialEtchedBorder; + +import java.awt.*; +import java.awt.event.*; + +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.*; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.border.EtchedBorder; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 14:47:40, 24.1.2010 + */ + +/** + * Implementation of the common settings dialog. + */ +public class SettingsDialog extends MultiplePageDialog{ + + private static final String OK_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.ok"); + private static final String CANCEL_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.cancel"); + private static final String APPLY_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.apply"); + + private static final int INIT_WIDTH = 800; + private static final int INIT_HEIGHT = 600; + + public static final String TITLE_LABEL = ModelerSession.getCommonResourceBundle().getString("modeler.settings"); + + private final AbstractAction cancelAction; + private final AbstractAction okAction; + private final AbstractAction applyAction; + + + public SettingsDialog(final Frame parentFrame, final String title){ + super(parentFrame, title); + + applyAction = new AbstractAction(APPLY_LABEL) { + public void actionPerformed(ActionEvent e) { + fireButtonEvent(ButtonNames.APPLY); + setEnabled(false); + } + }; + + cancelAction = new AbstractAction(CANCEL_LABEL) { + public void actionPerformed(ActionEvent e) { + fireButtonEvent(ButtonNames.CANCEL); + setDialogResult(RESULT_CANCELLED); + setVisible(false); + applyAction.setEnabled(false); + dispose(); + } + }; + + okAction = new AbstractAction(OK_LABEL) { + public void actionPerformed(ActionEvent e) { + fireButtonEvent(ButtonNames.OK); + setDialogResult(RESULT_AFFIRMED); + setVisible(false); + applyAction.setEnabled(false); + dispose(); + } + }; + + getRootPane().registerKeyboardAction(new ActionListener(){ + public void actionPerformed(ActionEvent actionEvent) { + cancelAction.actionPerformed(null); + } + }, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + + initEventHandling(); + } + + @Override + protected JTree createTree(DefaultMutableTreeNode root) { + return ModelerSession.getComponentFactoryService().createTree(root); + } + + private void initEventHandling() { + addWindowListener(new WindowAdapter(){ + @Override + public void windowClosing(WindowEvent windowEvent) { + cancelAction.actionPerformed(null); + } + }); + } + + + @Override + public ButtonPanel createButtonPanel() { + final ButtonPanel buttonPanel = super.createButtonPanel(); + + applyAction.setEnabled(false); + + ((JButton) buttonPanel.getButtonByName(ButtonNames.OK)).setAction(okAction); + ((JButton) buttonPanel.getButtonByName(ButtonNames.CANCEL)).setAction(cancelAction); + ((JButton) buttonPanel.getButtonByName(ButtonNames.APPLY)).setAction(applyAction); + + setDefaultAction(okAction); + + return buttonPanel; + } + + /** + * When an button of settings dialog has been pressed (i.g. OK, CANCEL, ...) all pages the has a registered + * instance of ButtonListener class will be notified about this event. + * + * @param buttonName is the name of the button that has been pressed + */ + private void fireButtonEvent(final String buttonName){ + final PageList pageList = getPageList(); + + for(int i = 0; i < pageList.getSize(); i++){ + final AbstractDialogPage page = pageList.getPage(i); + + page.fireButtonEvent(0, buttonName); + } + } + + @Override + public Dimension getPreferredSize() { + return new Dimension(INIT_WIDTH, INIT_HEIGHT); + } + + @Override + protected void initComponents() { + super.initComponents(); + + getContentPanel().setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10)); + + getIndexPanel().setBackground(Color.white); + + getButtonPanel().setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + getPagesPanel().setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createEmptyBorder(0, 10, 0, 0), + new PartialEtchedBorder(EtchedBorder.LOWERED, PartialEtchedBorder.SOUTH))); + } + + /** + * Shows a settings dialog. + * + * @param settingPagesModel is the list of settings pages defined by plugins + */ + public static void showOptionsDialog(final PageList settingPagesModel) { + final PageList pages = new PageList(); + + for(int i = 0; i < settingPagesModel.getPageCount(); i++){ + pages.append(settingPagesModel.getPage(i)); + } + + final MultiplePageDialog dialog = new SettingsDialog(ModelerSession.getFrame(), TITLE_LABEL); + + dialog.setStyle(MultiplePageDialog.TREE_STYLE); + dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + + dialog.setPageList(pages); + + dialog.pack(); + JideSwingUtilities.globalCenterWindow(dialog); + dialog.setVisible(true); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/support/utils/DockableFrameWrapper.java b/IndependentModeler/src/cz/cvut/promod/gui/support/utils/DockableFrameWrapper.java index d17031a..7bfbe0e 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/support/utils/DockableFrameWrapper.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/support/utils/DockableFrameWrapper.java @@ -1,155 +1,155 @@ -package cz.cvut.promod.gui.support.utils; - -import com.jidesoft.docking.DockableFrame; -import com.jidesoft.docking.DockingManager; -import com.jidesoft.swing.JideButton; - -import javax.swing.*; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 2:17:17, 20.10.2009 - */ - -/** - * Data holder for a single dockable frame. - */ -public class DockableFrameWrapper { - - private final DockingManager dockingManager; - - private final DockableFrame dockableFrame; - private final JideButton button; - - private JPopupMenu popupMenu = null; - private JMenuItem moveToLeftItem = null; - private JMenuItem moveToRightItem = null; - private JMenuItem moveToBottomItem = null; - private JMenuItem moveToTopItem = null; - - private boolean hideOtherFrames = true; - private boolean wasAvailable; - - private DockableFrameData.InitialState initialState; - - public DockableFrameWrapper( final DockableFrame dockingFrame, - final JideButton button, - final JPopupMenu popupMenu, - final JMenuItem moveToLeftItem, - final JMenuItem moveToRightItem, - final JMenuItem moveToBottomItem, - final JMenuItem moveToTopItem, - final DockableFrameData.InitialState initialState, - final DockingManager dockingManager){ - - this.initialState = initialState; - - this.dockingManager = dockingManager; - - this.dockableFrame = dockingFrame; - this.button = button; - wasAvailable = false; - - this.popupMenu = popupMenu; - this.moveToLeftItem = moveToLeftItem; - this.moveToRightItem = moveToRightItem; - this.moveToBottomItem = moveToBottomItem; - this.moveToTopItem = moveToTopItem; - - if( initialState == DockableFrameData.InitialState.OPENED){ - setWasAvailable(true); - } - } - - /** - * @return the frame initial state - */ - public DockableFrameData.InitialState getInitialState() { - DockableFrameData.InitialState a = initialState; - initialState = null; - return a; - } - - /** - * @return left menu item - */ - public JMenuItem getMoveToLeftItem(){ - return moveToLeftItem; - } - - /** - * @return right menu item - */ - public JMenuItem getMoveToRightItem(){ - return moveToRightItem; - } - - public JMenuItem getMoveToBottomItem() { - return moveToBottomItem; - } - - /** - * @return top menu item - */ - public JMenuItem getMoveToTopItem() { - return moveToTopItem; - } - - /** - * @return the dockable frame itself - */ - public DockableFrame getDockableFrame(){ - return dockableFrame; - } - - /** - * @return the associated button for visibility controlling - */ - public JideButton getButton(){ - return button; - } - - /** - * @return associated button popup menu - */ - public JPopupMenu getPopupMenu(){ - return popupMenu; - } - - /** - * @return true if the dockable frame was visible before context switch, false otherwise - */ - public boolean isWasAvailable(){ - return wasAvailable; - } - - /** - * Sets the wasAvailable flag - * - * @param wasAvailable true if the is supposed to be true, false otherwise - */ - public void setWasAvailable( boolean wasAvailable ){ - this.wasAvailable = wasAvailable; - } - - /** - * @return true if all other frames are supposed to be hidden - */ - public boolean isHideOtherFrames(){ - boolean returnValue = hideOtherFrames; - hideOtherFrames = true; - return returnValue; - } - - /** - * Sets the hideOtherFrames flag. - * @param notHideOtherFrames new value for hideOtherFrames flag - */ - public void setHideOtherFrames( boolean notHideOtherFrames ){ - this.hideOtherFrames = notHideOtherFrames; - } -} - +package cz.cvut.promod.gui.support.utils; + +import com.jidesoft.docking.DockableFrame; +import com.jidesoft.docking.DockingManager; +import com.jidesoft.swing.JideButton; + +import javax.swing.*; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 2:17:17, 20.10.2009 + */ + +/** + * Data holder for a single dockable frame. + */ +public class DockableFrameWrapper { + + private final DockingManager dockingManager; + + private final DockableFrame dockableFrame; + private final JideButton button; + + private JPopupMenu popupMenu = null; + private JMenuItem moveToLeftItem = null; + private JMenuItem moveToRightItem = null; + private JMenuItem moveToBottomItem = null; + private JMenuItem moveToTopItem = null; + + private boolean hideOtherFrames = true; + private boolean wasAvailable; + + private DockableFrameData.InitialState initialState; + + public DockableFrameWrapper( final DockableFrame dockingFrame, + final JideButton button, + final JPopupMenu popupMenu, + final JMenuItem moveToLeftItem, + final JMenuItem moveToRightItem, + final JMenuItem moveToBottomItem, + final JMenuItem moveToTopItem, + final DockableFrameData.InitialState initialState, + final DockingManager dockingManager){ + + this.initialState = initialState; + + this.dockingManager = dockingManager; + + this.dockableFrame = dockingFrame; + this.button = button; + wasAvailable = false; + + this.popupMenu = popupMenu; + this.moveToLeftItem = moveToLeftItem; + this.moveToRightItem = moveToRightItem; + this.moveToBottomItem = moveToBottomItem; + this.moveToTopItem = moveToTopItem; + + if( initialState == DockableFrameData.InitialState.OPENED){ + setWasAvailable(true); + } + } + + /** + * @return the frame initial state + */ + public DockableFrameData.InitialState getInitialState() { + DockableFrameData.InitialState a = initialState; + initialState = null; + return a; + } + + /** + * @return left menu item + */ + public JMenuItem getMoveToLeftItem(){ + return moveToLeftItem; + } + + /** + * @return right menu item + */ + public JMenuItem getMoveToRightItem(){ + return moveToRightItem; + } + + public JMenuItem getMoveToBottomItem() { + return moveToBottomItem; + } + + /** + * @return top menu item + */ + public JMenuItem getMoveToTopItem() { + return moveToTopItem; + } + + /** + * @return the dockable frame itself + */ + public DockableFrame getDockableFrame(){ + return dockableFrame; + } + + /** + * @return the associated button for visibility controlling + */ + public JideButton getButton(){ + return button; + } + + /** + * @return associated button popup menu + */ + public JPopupMenu getPopupMenu(){ + return popupMenu; + } + + /** + * @return true if the dockable frame was visible before context switch, false otherwise + */ + public boolean isWasAvailable(){ + return wasAvailable; + } + + /** + * Sets the wasAvailable flag + * + * @param wasAvailable true if the is supposed to be true, false otherwise + */ + public void setWasAvailable( boolean wasAvailable ){ + this.wasAvailable = wasAvailable; + } + + /** + * @return true if all other frames are supposed to be hidden + */ + public boolean isHideOtherFrames(){ + boolean returnValue = hideOtherFrames; + hideOtherFrames = true; + return returnValue; + } + + /** + * Sets the hideOtherFrames flag. + * @param notHideOtherFrames new value for hideOtherFrames flag + */ + public void setHideOtherFrames( boolean notHideOtherFrames ){ + this.hideOtherFrames = notHideOtherFrames; + } +} + diff --git a/IndependentModeler/src/cz/cvut/promod/gui/support/utils/LoadProjectDialogFileFilter.java b/IndependentModeler/src/cz/cvut/promod/gui/support/utils/LoadProjectDialogFileFilter.java index 4b6a5af..1c65f00 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/support/utils/LoadProjectDialogFileFilter.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/support/utils/LoadProjectDialogFileFilter.java @@ -1,36 +1,36 @@ -package cz.cvut.promod.gui.support.utils; - -import cz.cvut.promod.services.projectService.ProjectService; -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.filechooser.FileFilter; -import java.io.File; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:18:58, 11.11.2009 - */ - -/** - * Class for file selection in the load project dialog. - */ -public class LoadProjectDialogFileFilter extends FileFilter { - - public boolean accept(final File f) { - if(f.isDirectory()){ - return true; - } - - if(f.isFile() && f.getName().endsWith(ProjectService.PROJECT_FILE_EXTENSION)){ - return true; - } - - return false; - } - - public String getDescription() { - return ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.description"); - } - -} +package cz.cvut.promod.gui.support.utils; + +import cz.cvut.promod.services.projectService.ProjectService; +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.filechooser.FileFilter; +import java.io.File; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:18:58, 11.11.2009 + */ + +/** + * Class for file selection in the load project dialog. + */ +public class LoadProjectDialogFileFilter extends FileFilter { + + public boolean accept(final File f) { + if(f.isDirectory()){ + return true; + } + + if(f.isFile() && f.getName().endsWith(ProjectService.PROJECT_FILE_EXTENSION)){ + return true; + } + + return false; + } + + public String getDescription() { + return ModelerSession.getCommonResourceBundle().getString("modeler.action.project.load.description"); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/gui/support/utils/NotationGuiHolder.java b/IndependentModeler/src/cz/cvut/promod/gui/support/utils/NotationGuiHolder.java index a4f2baa..3a3335f 100644 --- a/IndependentModeler/src/cz/cvut/promod/gui/support/utils/NotationGuiHolder.java +++ b/IndependentModeler/src/cz/cvut/promod/gui/support/utils/NotationGuiHolder.java @@ -1,496 +1,496 @@ -package cz.cvut.promod.gui.support.utils; - -import com.jidesoft.docking.DefaultDockingManager; -import com.jidesoft.docking.DockableFrame; -import com.jidesoft.docking.DockContext; -import com.jidesoft.swing.JideButton; - -import java.util.*; -import java.util.List; - -import org.apache.log4j.Logger; - -import javax.swing.*; - -import cz.cvut.promod.gui.Modeler; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; -import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.NotationWorkspaceData; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 18:52:49, 12.10.2009 - */ - -/** - * Notation specific data holder. - */ -public class NotationGuiHolder { - - private static final Logger LOG = Logger.getLogger(NotationGuiHolder.class); - - public static enum Position{ - LEFT, RIGHT, BOTTOM, TOP - } - - private final String notationIdentifier; - - private Map rightItems; - - private Map leftItems; - - private Map bottomItems; - - private Map topItems; - - private NotationWorkspaceData notationWorkspace; - - private final DefaultDockingManager dockingManager; - - private final Set takenPositions; - - public NotationGuiHolder( final String notationIdentifier, final DefaultDockingManager dockingManager){ - this.notationIdentifier = notationIdentifier; - this.dockingManager = dockingManager; - - this.takenPositions = new HashSet(); - - rightItems = new HashMap(); - leftItems = new HashMap(); - bottomItems = new HashMap(); - topItems = new HashMap(); - } - - public String getNotationIdentifier() { - return notationIdentifier; - } - - /** - * Returns the required dockable frame position. - * @param frameName the dockable frame name - * @return the dockable frame or null if no such a dockable frame exists - */ - public Position getPosition( final String frameName ){ - if( rightItems.containsKey(frameName) ){ - return Position.RIGHT; - } else if( leftItems.containsKey(frameName) ){ - return Position.LEFT; - } else if( bottomItems.containsKey(frameName) ){ - return Position.BOTTOM; - } else if( topItems.containsKey(frameName) ){ - return Position.TOP; - } - - return null; - } - - /** - * @return notation's workspace - */ - public NotationWorkspaceData getNotationWorkspace(){ - return notationWorkspace; - } - - /** - * Sets the notation's workspace. - * @param notationWorkspaceData the notation workspace - */ - public void setNotationWorkspace( final NotationWorkspaceData notationWorkspaceData){ - notationWorkspace = notationWorkspaceData; - } - - /** - * Returns the dockable frame associated button. - * @param dockableFrameName is the name of the dockable frame - * @param position is the dockable frame position - * @return the dockable frame associated button. - */ - public JideButton getButton( final String dockableFrameName, final Position position ){ - return getItems(position).get(dockableFrameName).getButton(); - } - - /** - * Returns all items from the specified position. - * @param position is the specified position - * @return map holding name and DockableFrameWrappers - */ - public Map getItems(final Position position){ - final Map items; - switch( position ){ - case RIGHT: - items = rightItems; - break; - case LEFT: - items = leftItems; - break; - case BOTTOM: - items = bottomItems; - break; - case TOP: - items = topItems; - break; - default: - LOG.error("No such a dockable frame position."); - throw new IllegalArgumentException("Wrong dockable frame position."); - } - - return items; - } - - /** - * Returns allowed dockable frame initial state - * @param initialState is the required initial state - * @param position is the required position - * @param dockableFrameName is the dockable frame name - * @return the allowed state, no two different dockable frames are supposed to be docked and visible in a moment - */ - private DockableFrameData.InitialState getAllowedInitialState(final DockableFrameData.InitialState initialState, - final Position position, - final String dockableFrameName) { - if(initialState == null){ - return DockableFrameData.InitialState.HIDDEN; - } - - if(DockableFrameData.InitialState.OPENED.equals(initialState)){ - if(takenPositions.contains(position)){ - LOG.warn("DockableFrame " + dockableFrameName +" has been set as HIDDEN."); - return DockableFrameData.InitialState.HIDDEN; - } - - takenPositions.add(position); - } - - return initialState; - } - - /** - * Adds a new frame and it's associated button. - * - * @param dockableFrame is the dockable frame - * @param button is the button - * @param popupMenu is the button's popup menu - * @param moveToLeftItem is the menu's item - * @param moveToRightItem is the menu's item - * @param moveToBottomItem is the menu's item - * @param moveToTopItem is the menu's item - * @param position is the dockable frame position - * @param initialState is the dockable frame initial state - */ - public void addFrameWithButton( final DockableFrame dockableFrame, - final JideButton button, - final JPopupMenu popupMenu, - final JMenuItem moveToLeftItem, - final JMenuItem moveToRightItem, - final JMenuItem moveToBottomItem, - final JMenuItem moveToTopItem, - final Position position, - DockableFrameData.InitialState initialState ){ - initialState = getAllowedInitialState(initialState, position, dockableFrame.getName()); - - final Map items = getItems(position); - - switch( position ){ - case RIGHT: - moveToRightItem.setEnabled(false); - break; - case LEFT: - moveToLeftItem.setEnabled(false); - break; - case BOTTOM: - moveToBottomItem.setEnabled(false); - break; - case TOP: - moveToTopItem.setEnabled(false); - break; - default: - throw new IllegalArgumentException("Wrong dockable frame position"); - } - - dockingManager.addFrame(dockableFrame); - - items.put(dockableFrame.getName(), new DockableFrameWrapper(dockableFrame, - button, - popupMenu, - moveToLeftItem, - moveToRightItem, - moveToBottomItem, - moveToTopItem, - initialState, - dockingManager)); - } - - /** - * Returns the list of dockable frame from the positions specified. - * @param position is the required position - * @return the list of required frames - */ - public List getListOfFrames( final Position position ){ - final List frames = new LinkedList(); - - final Map items = getItems(position); - - final Collection wrappers = items.values(); - - for( final DockableFrameWrapper wrapper : wrappers){ - frames.add(wrapper.getDockableFrame()); - } - - return frames; - } - - /** - * Returns the list of buttons from the positions specified. - * @param position is the required position - * @return the list of required buttons - */ - public List getListOfButtons( final Position position ){ - final List buttons = new LinkedList(); - final Collection wrappers = getItems(position).values(); - - for( final DockableFrameWrapper wrapper : wrappers){ - buttons.add(wrapper.getButton()); - } - - return buttons; - } - - /** - * Sets the dockable frame's button's movement possibilities. - * @param frame is the dockable frame - */ - public void setButtonsMovementOptions( final DockableFrame frame ){ - final Position position = getPosition(frame.getName()); - final DockableFrameWrapper wrapper = getItems(position).get(frame.getName()); - - try{ - switch( position ){ - case LEFT: - setButtonsMovementOptions(wrapper, false, true, true, true); - break; - case RIGHT: - setButtonsMovementOptions(wrapper, true, false, true, true); - break; - case BOTTOM: - setButtonsMovementOptions(wrapper, true, true, false, true); - break; - case TOP: - setButtonsMovementOptions(wrapper, true, true, true, false); - break; - default: - LOG.error("No such a dockable frame position"); - throw new IllegalArgumentException(); - } - } catch(NullPointerException exception){ - LOG.error("Non existing DockableFrameWrapper in setButtonsMovementOptions( DockableFrame frame )", exception); - } catch(IllegalArgumentException exception){ - LOG.error("Illegal position of DockableFrameWrapper in setButtonsMovementOptions( DockableFrame frame )", exception); - } - } - - /** - * Update the dockable frame's button's movement possibilities. - * @param wrapper is the wrapper of the dockable frame and related button - * @param toLeft required state - * @param toRight required state - * @param toBottom required state - * @param toTop required state - * @throws NullPointerException when an item is missing - */ - private void setButtonsMovementOptions( final DockableFrameWrapper wrapper, - final boolean toLeft, - final boolean toRight, - final boolean toBottom, - final boolean toTop) throws NullPointerException{ - if( wrapper.getDockableFrame().isFloated() ){ - wrapper.getMoveToLeftItem().setEnabled(false); - wrapper.getMoveToRightItem().setEnabled(false); - wrapper.getMoveToBottomItem().setEnabled(false); - wrapper.getMoveToTopItem().setEnabled(false); - } else{ - wrapper.getMoveToLeftItem().setEnabled(toLeft); - wrapper.getMoveToRightItem().setEnabled(toRight); - wrapper.getMoveToBottomItem().setEnabled(toBottom); - wrapper.getMoveToTopItem().setEnabled(toTop); - } - } - - /** - * Moves the dockable frame. - * @param name is the name of the dockable frame - * @param directionOfMovement is the direction of the movement - * @throws IllegalArgumentException when the move is not possible - */ - public void moveButtonAndFrame(final String name, final NotationGuiHolder.Position directionOfMovement) throws IllegalArgumentException{ - final Position position = getPosition(name); - - if( position == null ){ - throw new IllegalArgumentException(); - } - - // find the target map - final Map items = getItems(directionOfMovement); - - //remove from current map - final DockableFrameWrapper movingWrapper = getItems(position).remove(name); - - items.put(name, movingWrapper); - - moveFrameToAnotherSide(movingWrapper.getDockableFrame(), directionOfMovement); - - updateButtonOrientation(directionOfMovement, movingWrapper.getButton()); - } - - /** - * Updates the button orientation. - * @param directionOfMovement is the movement direction - * @param button is the button to be updated - */ - private void updateButtonOrientation(final Position directionOfMovement, final JideButton button) { - switch(directionOfMovement){ - case LEFT: - case RIGHT: - button.setOrientation(ComponentFactoryService.JIDE_BUTTON_VERTICAL_ORIENTATION); - break; - case BOTTOM: - case TOP: - button.setOrientation(ComponentFactoryService.JIDE_BUTTON_HORIZONTAL_ORIENTATION); - } - } - - /** - * Performed the auxiliary movement operations. - * @param frame is the frame supposed to be moved - * @param items related dockable frame in form of their wrappers - * @param direction is the direction of movement - * @throws IllegalArgumentException when an error occurs - */ - private void performFrameMovement( final DockableFrame frame, - final Map items, - final Position direction ) throws IllegalArgumentException{ - final Collection wrappers; - final int side; - - switch (direction) { - case RIGHT: - side = DockContext.DOCK_SIDE_EAST; - break; - case LEFT: - side = DockContext.DOCK_SIDE_WEST; - break; - case BOTTOM: - side = DockContext.DOCK_SIDE_SOUTH; - break; - case TOP: - side = DockContext.DOCK_SIDE_NORTH; - break; - default: - throw new IllegalArgumentException(); - } - - if( frame.isAvailable() ){ - wrappers = items.values(); - for( final DockableFrameWrapper wrapper : wrappers){ - boolean floatedAndAvailable = frame.isAvailable(); - if( (wrapper.getDockableFrame() != frame) && !floatedAndAvailable ){ - dockingManager.setFrameUnavailable(wrapper.getDockableFrame().getName()); - } - } - dockingManager.dockFrame(frame.getName(), side, - Modeler.dockingFrameCounter++); - dockingManager.setFrameAvailable(frame.getName()); - - } else{ - final DockableFrameWrapper wrapper = items.get(frame.getName()); - - wrapper.setHideOtherFrames(false); - dockingManager.setFrameAvailable(frame.getName()); - wrapper.setHideOtherFrames(false); - dockingManager.dockFrame(frame.getName(), side, Modeler.dockingFrameCounter++); - dockingManager.setFrameUnavailable(frame.getName()); - } - } - - /** - * Starts the dockable frame movement - * @param frame is the dockable frame to be moved - * @param direction is the direction of movement - */ - private void moveFrameToAnotherSide( final DockableFrame frame, final Position direction ){ - performFrameMovement(frame, getItems(direction), direction); - } - - /** - * Enables the frames and their buttons. - */ - public void enable(){ - final Collection wrappers = getAllDockableFrameFacades(); - - for( DockableFrameWrapper wrapper : wrappers){ - if(wrapper.isWasAvailable()){ - wrapper.setWasAvailable(false); - wrapper.getButton().doClick(); - } - } - } - - /** - * Unables the frames and their buttons. - */ - public void unable(){ - final Collection wrappers = getAllDockableFrameFacades(); - - for( final DockableFrameWrapper wrapper : wrappers){ - if( wrapper.isWasAvailable() && !wrapper.getDockableFrame().isAvailable() ){ - wrapper.setWasAvailable(false); - } - - if( wrapper.getDockableFrame().isAvailable() ){ - wrapper.getButton().doClick(); - wrapper.setWasAvailable(true); - } - } - } - - /** - * @param frameName is the frame name - * @param position is the frame position - * @return true if all other frames are supposed to be hidden - * @throws IllegalArgumentException when not such a item exists - */ - public boolean isHideOtherFrames( final String frameName, final Position position ) throws IllegalArgumentException{ - return getItems(position).get(frameName).isHideOtherFrames(); - } - - /** - * @return all wrappers representing dockable frames of a notations and it's modules - */ - public Set getAllDockableFrameFacades(){ - final Set wrappers = new HashSet(); - wrappers.addAll(rightItems.values()); - wrappers.addAll(leftItems.values()); - wrappers.addAll((bottomItems.values())); - wrappers.addAll(topItems.values()); - - return wrappers; - } - - /** - * @param frameName is the name of the dockable frame - * @return the required facade representing the dockable frame - */ - public DockableFrameWrapper getDockableFrameFacade( final String frameName ){ - if( leftItems.containsKey(frameName) ){ - return leftItems.get(frameName); - } else if (rightItems.containsKey(frameName)){ - return rightItems.get(frameName); - } else if(bottomItems.containsKey(frameName)){ - return bottomItems.get(frameName); - } else if(topItems.containsKey(frameName)){ - return topItems.get(frameName); - } - - return null; - } - +package cz.cvut.promod.gui.support.utils; + +import com.jidesoft.docking.DefaultDockingManager; +import com.jidesoft.docking.DockableFrame; +import com.jidesoft.docking.DockContext; +import com.jidesoft.swing.JideButton; + +import java.util.*; +import java.util.List; + +import org.apache.log4j.Logger; + +import javax.swing.*; + +import cz.cvut.promod.gui.Modeler; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; +import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.NotationWorkspaceData; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 18:52:49, 12.10.2009 + */ + +/** + * Notation specific data holder. + */ +public class NotationGuiHolder { + + private static final Logger LOG = Logger.getLogger(NotationGuiHolder.class); + + public static enum Position{ + LEFT, RIGHT, BOTTOM, TOP + } + + private final String notationIdentifier; + + private Map rightItems; + + private Map leftItems; + + private Map bottomItems; + + private Map topItems; + + private NotationWorkspaceData notationWorkspace; + + private final DefaultDockingManager dockingManager; + + private final Set takenPositions; + + public NotationGuiHolder( final String notationIdentifier, final DefaultDockingManager dockingManager){ + this.notationIdentifier = notationIdentifier; + this.dockingManager = dockingManager; + + this.takenPositions = new HashSet(); + + rightItems = new HashMap(); + leftItems = new HashMap(); + bottomItems = new HashMap(); + topItems = new HashMap(); + } + + public String getNotationIdentifier() { + return notationIdentifier; + } + + /** + * Returns the required dockable frame position. + * @param frameName the dockable frame name + * @return the dockable frame or null if no such a dockable frame exists + */ + public Position getPosition( final String frameName ){ + if( rightItems.containsKey(frameName) ){ + return Position.RIGHT; + } else if( leftItems.containsKey(frameName) ){ + return Position.LEFT; + } else if( bottomItems.containsKey(frameName) ){ + return Position.BOTTOM; + } else if( topItems.containsKey(frameName) ){ + return Position.TOP; + } + + return null; + } + + /** + * @return notation's workspace + */ + public NotationWorkspaceData getNotationWorkspace(){ + return notationWorkspace; + } + + /** + * Sets the notation's workspace. + * @param notationWorkspaceData the notation workspace + */ + public void setNotationWorkspace( final NotationWorkspaceData notationWorkspaceData){ + notationWorkspace = notationWorkspaceData; + } + + /** + * Returns the dockable frame associated button. + * @param dockableFrameName is the name of the dockable frame + * @param position is the dockable frame position + * @return the dockable frame associated button. + */ + public JideButton getButton( final String dockableFrameName, final Position position ){ + return getItems(position).get(dockableFrameName).getButton(); + } + + /** + * Returns all items from the specified position. + * @param position is the specified position + * @return map holding name and DockableFrameWrappers + */ + public Map getItems(final Position position){ + final Map items; + switch( position ){ + case RIGHT: + items = rightItems; + break; + case LEFT: + items = leftItems; + break; + case BOTTOM: + items = bottomItems; + break; + case TOP: + items = topItems; + break; + default: + LOG.error("No such a dockable frame position."); + throw new IllegalArgumentException("Wrong dockable frame position."); + } + + return items; + } + + /** + * Returns allowed dockable frame initial state + * @param initialState is the required initial state + * @param position is the required position + * @param dockableFrameName is the dockable frame name + * @return the allowed state, no two different dockable frames are supposed to be docked and visible in a moment + */ + private DockableFrameData.InitialState getAllowedInitialState(final DockableFrameData.InitialState initialState, + final Position position, + final String dockableFrameName) { + if(initialState == null){ + return DockableFrameData.InitialState.HIDDEN; + } + + if(DockableFrameData.InitialState.OPENED.equals(initialState)){ + if(takenPositions.contains(position)){ + LOG.warn("DockableFrame " + dockableFrameName +" has been set as HIDDEN."); + return DockableFrameData.InitialState.HIDDEN; + } + + takenPositions.add(position); + } + + return initialState; + } + + /** + * Adds a new frame and it's associated button. + * + * @param dockableFrame is the dockable frame + * @param button is the button + * @param popupMenu is the button's popup menu + * @param moveToLeftItem is the menu's item + * @param moveToRightItem is the menu's item + * @param moveToBottomItem is the menu's item + * @param moveToTopItem is the menu's item + * @param position is the dockable frame position + * @param initialState is the dockable frame initial state + */ + public void addFrameWithButton( final DockableFrame dockableFrame, + final JideButton button, + final JPopupMenu popupMenu, + final JMenuItem moveToLeftItem, + final JMenuItem moveToRightItem, + final JMenuItem moveToBottomItem, + final JMenuItem moveToTopItem, + final Position position, + DockableFrameData.InitialState initialState ){ + initialState = getAllowedInitialState(initialState, position, dockableFrame.getName()); + + final Map items = getItems(position); + + switch( position ){ + case RIGHT: + moveToRightItem.setEnabled(false); + break; + case LEFT: + moveToLeftItem.setEnabled(false); + break; + case BOTTOM: + moveToBottomItem.setEnabled(false); + break; + case TOP: + moveToTopItem.setEnabled(false); + break; + default: + throw new IllegalArgumentException("Wrong dockable frame position"); + } + + dockingManager.addFrame(dockableFrame); + + items.put(dockableFrame.getName(), new DockableFrameWrapper(dockableFrame, + button, + popupMenu, + moveToLeftItem, + moveToRightItem, + moveToBottomItem, + moveToTopItem, + initialState, + dockingManager)); + } + + /** + * Returns the list of dockable frame from the positions specified. + * @param position is the required position + * @return the list of required frames + */ + public List getListOfFrames( final Position position ){ + final List frames = new LinkedList(); + + final Map items = getItems(position); + + final Collection wrappers = items.values(); + + for( final DockableFrameWrapper wrapper : wrappers){ + frames.add(wrapper.getDockableFrame()); + } + + return frames; + } + + /** + * Returns the list of buttons from the positions specified. + * @param position is the required position + * @return the list of required buttons + */ + public List getListOfButtons( final Position position ){ + final List buttons = new LinkedList(); + final Collection wrappers = getItems(position).values(); + + for( final DockableFrameWrapper wrapper : wrappers){ + buttons.add(wrapper.getButton()); + } + + return buttons; + } + + /** + * Sets the dockable frame's button's movement possibilities. + * @param frame is the dockable frame + */ + public void setButtonsMovementOptions( final DockableFrame frame ){ + final Position position = getPosition(frame.getName()); + final DockableFrameWrapper wrapper = getItems(position).get(frame.getName()); + + try{ + switch( position ){ + case LEFT: + setButtonsMovementOptions(wrapper, false, true, true, true); + break; + case RIGHT: + setButtonsMovementOptions(wrapper, true, false, true, true); + break; + case BOTTOM: + setButtonsMovementOptions(wrapper, true, true, false, true); + break; + case TOP: + setButtonsMovementOptions(wrapper, true, true, true, false); + break; + default: + LOG.error("No such a dockable frame position"); + throw new IllegalArgumentException(); + } + } catch(NullPointerException exception){ + LOG.error("Non existing DockableFrameWrapper in setButtonsMovementOptions( DockableFrame frame )", exception); + } catch(IllegalArgumentException exception){ + LOG.error("Illegal position of DockableFrameWrapper in setButtonsMovementOptions( DockableFrame frame )", exception); + } + } + + /** + * Update the dockable frame's button's movement possibilities. + * @param wrapper is the wrapper of the dockable frame and related button + * @param toLeft required state + * @param toRight required state + * @param toBottom required state + * @param toTop required state + * @throws NullPointerException when an item is missing + */ + private void setButtonsMovementOptions( final DockableFrameWrapper wrapper, + final boolean toLeft, + final boolean toRight, + final boolean toBottom, + final boolean toTop) throws NullPointerException{ + if( wrapper.getDockableFrame().isFloated() ){ + wrapper.getMoveToLeftItem().setEnabled(false); + wrapper.getMoveToRightItem().setEnabled(false); + wrapper.getMoveToBottomItem().setEnabled(false); + wrapper.getMoveToTopItem().setEnabled(false); + } else{ + wrapper.getMoveToLeftItem().setEnabled(toLeft); + wrapper.getMoveToRightItem().setEnabled(toRight); + wrapper.getMoveToBottomItem().setEnabled(toBottom); + wrapper.getMoveToTopItem().setEnabled(toTop); + } + } + + /** + * Moves the dockable frame. + * @param name is the name of the dockable frame + * @param directionOfMovement is the direction of the movement + * @throws IllegalArgumentException when the move is not possible + */ + public void moveButtonAndFrame(final String name, final NotationGuiHolder.Position directionOfMovement) throws IllegalArgumentException{ + final Position position = getPosition(name); + + if( position == null ){ + throw new IllegalArgumentException(); + } + + // find the target map + final Map items = getItems(directionOfMovement); + + //remove from current map + final DockableFrameWrapper movingWrapper = getItems(position).remove(name); + + items.put(name, movingWrapper); + + moveFrameToAnotherSide(movingWrapper.getDockableFrame(), directionOfMovement); + + updateButtonOrientation(directionOfMovement, movingWrapper.getButton()); + } + + /** + * Updates the button orientation. + * @param directionOfMovement is the movement direction + * @param button is the button to be updated + */ + private void updateButtonOrientation(final Position directionOfMovement, final JideButton button) { + switch(directionOfMovement){ + case LEFT: + case RIGHT: + button.setOrientation(ComponentFactoryService.JIDE_BUTTON_VERTICAL_ORIENTATION); + break; + case BOTTOM: + case TOP: + button.setOrientation(ComponentFactoryService.JIDE_BUTTON_HORIZONTAL_ORIENTATION); + } + } + + /** + * Performed the auxiliary movement operations. + * @param frame is the frame supposed to be moved + * @param items related dockable frame in form of their wrappers + * @param direction is the direction of movement + * @throws IllegalArgumentException when an error occurs + */ + private void performFrameMovement( final DockableFrame frame, + final Map items, + final Position direction ) throws IllegalArgumentException{ + final Collection wrappers; + final int side; + + switch (direction) { + case RIGHT: + side = DockContext.DOCK_SIDE_EAST; + break; + case LEFT: + side = DockContext.DOCK_SIDE_WEST; + break; + case BOTTOM: + side = DockContext.DOCK_SIDE_SOUTH; + break; + case TOP: + side = DockContext.DOCK_SIDE_NORTH; + break; + default: + throw new IllegalArgumentException(); + } + + if( frame.isAvailable() ){ + wrappers = items.values(); + for( final DockableFrameWrapper wrapper : wrappers){ + boolean floatedAndAvailable = frame.isAvailable(); + if( (wrapper.getDockableFrame() != frame) && !floatedAndAvailable ){ + dockingManager.setFrameUnavailable(wrapper.getDockableFrame().getName()); + } + } + dockingManager.dockFrame(frame.getName(), side, + Modeler.dockingFrameCounter++); + dockingManager.setFrameAvailable(frame.getName()); + + } else{ + final DockableFrameWrapper wrapper = items.get(frame.getName()); + + wrapper.setHideOtherFrames(false); + dockingManager.setFrameAvailable(frame.getName()); + wrapper.setHideOtherFrames(false); + dockingManager.dockFrame(frame.getName(), side, Modeler.dockingFrameCounter++); + dockingManager.setFrameUnavailable(frame.getName()); + } + } + + /** + * Starts the dockable frame movement + * @param frame is the dockable frame to be moved + * @param direction is the direction of movement + */ + private void moveFrameToAnotherSide( final DockableFrame frame, final Position direction ){ + performFrameMovement(frame, getItems(direction), direction); + } + + /** + * Enables the frames and their buttons. + */ + public void enable(){ + final Collection wrappers = getAllDockableFrameFacades(); + + for( DockableFrameWrapper wrapper : wrappers){ + if(wrapper.isWasAvailable()){ + wrapper.setWasAvailable(false); + wrapper.getButton().doClick(); + } + } + } + + /** + * Unables the frames and their buttons. + */ + public void unable(){ + final Collection wrappers = getAllDockableFrameFacades(); + + for( final DockableFrameWrapper wrapper : wrappers){ + if( wrapper.isWasAvailable() && !wrapper.getDockableFrame().isAvailable() ){ + wrapper.setWasAvailable(false); + } + + if( wrapper.getDockableFrame().isAvailable() ){ + wrapper.getButton().doClick(); + wrapper.setWasAvailable(true); + } + } + } + + /** + * @param frameName is the frame name + * @param position is the frame position + * @return true if all other frames are supposed to be hidden + * @throws IllegalArgumentException when not such a item exists + */ + public boolean isHideOtherFrames( final String frameName, final Position position ) throws IllegalArgumentException{ + return getItems(position).get(frameName).isHideOtherFrames(); + } + + /** + * @return all wrappers representing dockable frames of a notations and it's modules + */ + public Set getAllDockableFrameFacades(){ + final Set wrappers = new HashSet(); + wrappers.addAll(rightItems.values()); + wrappers.addAll(leftItems.values()); + wrappers.addAll((bottomItems.values())); + wrappers.addAll(topItems.values()); + + return wrappers; + } + + /** + * @param frameName is the name of the dockable frame + * @return the required facade representing the dockable frame + */ + public DockableFrameWrapper getDockableFrameFacade( final String frameName ){ + if( leftItems.containsKey(frameName) ){ + return leftItems.get(frameName); + } else if (rightItems.containsKey(frameName)){ + return rightItems.get(frameName); + } else if(bottomItems.containsKey(frameName)){ + return bottomItems.get(frameName); + } else if(topItems.containsKey(frameName)){ + return topItems.get(frameName); + } + + return null; + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/extension/Extension.java b/IndependentModeler/src/cz/cvut/promod/plugin/extension/Extension.java index 362f4f8..8525921 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/extension/Extension.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/extension/Extension.java @@ -1,16 +1,16 @@ -package cz.cvut.promod.plugin.extension; - -import cz.cvut.promod.plugin.Plugin; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:30:53, 16.10.2009 - */ - -/** - * Extension interface has no specialized methods. Is not a Notation and it is not a module. - * The reason why there are separated interfaces for Module and Extension is, that the Extension - * never has an identifier of related notation. Module does. - */ -public interface Extension extends Plugin {} +package cz.cvut.promod.plugin.extension; + +import cz.cvut.promod.plugin.Plugin; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:30:53, 16.10.2009 + */ + +/** + * Extension interface has no specialized methods. Is not a Notation and it is not a module. + * The reason why there are separated interfaces for Module and Extension is, that the Extension + * never has an identifier of related notation. Module does. + */ +public interface Extension extends Plugin {} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/DockableFrameData.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/DockableFrameData.java index dc72c87..efea7c1 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/DockableFrameData.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/DockableFrameData.java @@ -1,90 +1,90 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn; - -import cz.cvut.promod.gui.support.utils.NotationGuiHolder; - -import javax.swing.*; -import java.util.Set; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 21:21:31, 12.10.2009 - */ - -/** - * Defines a dockable frame component and some meta data related to the frame. - */ -public interface DockableFrameData { - - /** - * Returns the graphics component that is supposed to be displayed on the dockable frame. - * - * @return the component that will be displayed on the dockable frame - */ - public JComponent getDockableFrameComponent(); - - /** - * Returns specification of initial dockable frame position. - * - * @return initial dockable frame position - */ - public NotationGuiHolder.Position getInitialPosition(); - - /** - * Indicated whether this dockable frame should be maximizable or not. If yes, - * special 'maximize' icon appears on the dockable frame. - * - * @return true if the dockable windows is supposed to be maximizable, false otherwise - */ - public boolean isMaximizable(); - - /** - * Returns possible application windows borders where this dockable frame could be docked. - * - * @return allowed sides where to dock the dockable frame - */ - public Set getAllowedDockableFramePositions(); - - /** - * Returns the specification of initial dockable frame state. - * - * @return initial dockable frame state - */ - public InitialState getInitialState(); - - /** - * Returns the dockable frame title. - * - * @return dockable frame title - */ - public String getDockableFrameTitle(); - - /** - * Returns dockable frame associated button icon. - * - * @return an icon for associated button - */ - public Icon getButtonIcon(); - - - /** - * Possible initial states of dockable frame. - */ - public static enum InitialState{ - /** - * The dockable frame will be initially hidden and docked. - */ - HIDDEN, - - /** - * The dockable frame will be initially visible and docked. - */ - OPENED, - - /** - * The dockable frame will be initially visible and floated. - */ - FLOATED - } - -} +package cz.cvut.promod.plugin.notationSpecificPlugIn; + +import cz.cvut.promod.gui.support.utils.NotationGuiHolder; + +import javax.swing.*; +import java.util.Set; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 21:21:31, 12.10.2009 + */ + +/** + * Defines a dockable frame component and some meta data related to the frame. + */ +public interface DockableFrameData { + + /** + * Returns the graphics component that is supposed to be displayed on the dockable frame. + * + * @return the component that will be displayed on the dockable frame + */ + public JComponent getDockableFrameComponent(); + + /** + * Returns specification of initial dockable frame position. + * + * @return initial dockable frame position + */ + public NotationGuiHolder.Position getInitialPosition(); + + /** + * Indicated whether this dockable frame should be maximizable or not. If yes, + * special 'maximize' icon appears on the dockable frame. + * + * @return true if the dockable windows is supposed to be maximizable, false otherwise + */ + public boolean isMaximizable(); + + /** + * Returns possible application windows borders where this dockable frame could be docked. + * + * @return allowed sides where to dock the dockable frame + */ + public Set getAllowedDockableFramePositions(); + + /** + * Returns the specification of initial dockable frame state. + * + * @return initial dockable frame state + */ + public InitialState getInitialState(); + + /** + * Returns the dockable frame title. + * + * @return dockable frame title + */ + public String getDockableFrameTitle(); + + /** + * Returns dockable frame associated button icon. + * + * @return an icon for associated button + */ + public Icon getButtonIcon(); + + + /** + * Possible initial states of dockable frame. + */ + public static enum InitialState{ + /** + * The dockable frame will be initially hidden and docked. + */ + HIDDEN, + + /** + * The dockable frame will be initially visible and docked. + */ + OPENED, + + /** + * The dockable frame will be initially visible and floated. + */ + FLOATED + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/NotationSpecificPlugin.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/NotationSpecificPlugin.java index 66ef0d8..e10eff5 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/NotationSpecificPlugin.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/NotationSpecificPlugin.java @@ -1,25 +1,25 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn; - -import cz.cvut.promod.plugin.Plugin; - -import java.util.Set; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 20:57:52, 12.10.2009 - */ - -/** - * Common interface for so-called notation-specific plugins. - */ -public interface NotationSpecificPlugin extends Plugin { - - /** - * Returns a set of dockable frames (windows) definition. - * - * @return a set of dockable frames (windows) definition - */ - public Set getDockableFrames(); - -} +package cz.cvut.promod.plugin.notationSpecificPlugIn; + +import cz.cvut.promod.plugin.Plugin; + +import java.util.Set; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 20:57:52, 12.10.2009 + */ + +/** + * Common interface for so-called notation-specific plugins. + */ +public interface NotationSpecificPlugin extends Plugin { + + /** + * Returns a set of dockable frames (windows) definition. + * + * @return a set of dockable frames (windows) definition + */ + public Set getDockableFrames(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/module/Module.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/module/Module.java index 0e7b98b..8a9b016 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/module/Module.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/module/Module.java @@ -1,33 +1,33 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.module; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.NotationSpecificPlugin; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 20:58:36, 12.10.2009 - */ - -/** - * Module is notation specific type of plugin. It is supposed to extend some functionality of a notation. Modules can - * add some dockable frames, use tool bar, status bar, menus, etc. - * - * Any module is always related to a notation. - * - * There are several possible ways how to instantiate the module. An author of a module has to provide the module's - * definition with one of following types constructor. If the PluginLoaderService finds such a constructor, then it - * uses this one. Priority/preferred constructor is determined using order rules. To get understand these rules then - * check out comments about the Plugin Loader Service. - * - * @see cz.cvut.promod.services.pluginLoaderService.PluginLoaderService for more details about module instantiation - */ -public interface Module extends NotationSpecificPlugin { - - /** - * Returns the notation identifier which is the module related to. - * - * @return notation identifier - */ - public String getRelatedNotationIdentifier(); - -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.module; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.NotationSpecificPlugin; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 20:58:36, 12.10.2009 + */ + +/** + * Module is notation specific type of plugin. It is supposed to extend some functionality of a notation. Modules can + * add some dockable frames, use tool bar, status bar, menus, etc. + * + * Any module is always related to a notation. + * + * There are several possible ways how to instantiate the module. An author of a module has to provide the module's + * definition with one of following types constructor. If the PluginLoaderService finds such a constructor, then it + * uses this one. Priority/preferred constructor is determined using order rules. To get understand these rules then + * check out comments about the Plugin Loader Service. + * + * @see cz.cvut.promod.services.pluginLoaderService.PluginLoaderService for more details about module instantiation + */ +public interface Module extends NotationSpecificPlugin { + + /** + * Returns the notation identifier which is the module related to. + * + * @return notation identifier + */ + public String getRelatedNotationIdentifier(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/NotationWorkspaceData.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/NotationWorkspaceData.java index f7db446..b83e59f 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/NotationWorkspaceData.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/NotationWorkspaceData.java @@ -1,21 +1,21 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.notation; - -import javax.swing.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 21:26:04, 12.10.2009 - */ -public interface NotationWorkspaceData { - - /** - * Method for obtaining a WorkspaceComponent. Any invocation of this method on the same instance of - * NotationWorkspaceData class has to return the same instance of JComponent (usually an instance of - * JComponent that implements UpdatableWorkspaceComponent interface). - * - * @return an instance of WorkspaceComponent class (every method invocation returns the same object). - */ - public JComponent getWorkspaceComponentSingleton(); - -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.notation; + +import javax.swing.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 21:26:04, 12.10.2009 + */ +public interface NotationWorkspaceData { + + /** + * Method for obtaining a WorkspaceComponent. Any invocation of this method on the same instance of + * NotationWorkspaceData class has to return the same instance of JComponent (usually an instance of + * JComponent that implements UpdatableWorkspaceComponent interface). + * + * @return an instance of WorkspaceComponent class (every method invocation returns the same object). + */ + public JComponent getWorkspaceComponentSingleton(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/factory/DiagramModelFactory.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/factory/DiagramModelFactory.java index 7899678..3857ddc 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/factory/DiagramModelFactory.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/factory/DiagramModelFactory.java @@ -1,26 +1,26 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.factory; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModel; - - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:16:11, 5.11.2009 - */ - -/** - * Every notation has to provide an implementation of DiagramModelFactory. This factory is for obtaining a new - * instance of DiagramModel. I.g. when a new diagram is required by the user. - */ -public interface DiagramModelFactory { - - /** - * Creates a new instance DiagramModel class. Usually every notations has it's own implementation of DiagramModel - * class (Subclass of DiagramModel). - * - * @return an subclass of DiagramModel ready for holding notation specific diagram information - */ - public DiagramModel createEmptyDiagramModel(); - -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.factory; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModel; + + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:16:11, 5.11.2009 + */ + +/** + * Every notation has to provide an implementation of DiagramModelFactory. This factory is for obtaining a new + * instance of DiagramModel. I.g. when a new diagram is required by the user. + */ +public interface DiagramModelFactory { + + /** + * Creates a new instance DiagramModel class. Usually every notations has it's own implementation of DiagramModel + * class (Subclass of DiagramModel). + * + * @return an subclass of DiagramModel ready for holding notation specific diagram information + */ + public DiagramModel createEmptyDiagramModel(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/localIOController/NotationLocalIOController.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/localIOController/NotationLocalIOController.java index e0842ac..6d3bb6f 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/localIOController/NotationLocalIOController.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/localIOController/NotationLocalIOController.java @@ -1,64 +1,64 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.localIOController; - -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 21:52:56, 9.11.2009 - */ - -/** - * NotationLocalIOController is an interface that has to be implemented by all notations. - * - * The functionality defined by methods of this interface are supposed to realize the project diagram FS - * serialization and deserialization. - */ -public interface NotationLocalIOController { - - public static enum SaveResult{ - /** - * The diagram was saved successfully. - */ - SUCCESS, - - /** - * The diagram was NOT saved successfully. An error has occurred. - */ - ERROR - } - - /** - * Saves the project diagram. - * - * @param projectDiagram is the project diagram to be saved - * @param parentLocation is the FS location where the diagram is supposed to be saved - * @param makeDirs true if the method is supposed to create necessary FS structure if missing - * @return a value from SaveResult - */ - public SaveResult saveProjectDiagram(final ProjectDiagram projectDiagram, - final String parentLocation, - final boolean makeDirs); - - /** - * Loads a diagram saved in a notation specific protocol (xml, binary, etc.) form the file on the file system. - * - * Note: - * DISPLAY NAME OF THE LOADED PROJECT DIAGRAM HAS TO MATCH WITH THE FILE NAME WITHOUT THE FILE EXTENSION. - * - * @param diagramLocation is the location of the file representing notation specific dialog on file system - * - * @return an instance of ProjectDiagram class - * - * @throws Exception when something unexpected happens, one of possible reasons is notation mismatch (e.g. there - * is a file on the file system that has extension of a notation, but this file isn't really the diagram file - * of this notation, an exception is then usually thrown). This is why the responsibility for exception handling - * takes programmer and not the service. - */ - public ProjectDiagram loadProjectDiagram(final String diagramLocation) throws Exception; - - /** - * @return the notation's file extension - */ - public String getNotationFileExtension(); -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.localIOController; + +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 21:52:56, 9.11.2009 + */ + +/** + * NotationLocalIOController is an interface that has to be implemented by all notations. + * + * The functionality defined by methods of this interface are supposed to realize the project diagram FS + * serialization and deserialization. + */ +public interface NotationLocalIOController { + + public static enum SaveResult{ + /** + * The diagram was saved successfully. + */ + SUCCESS, + + /** + * The diagram was NOT saved successfully. An error has occurred. + */ + ERROR + } + + /** + * Saves the project diagram. + * + * @param projectDiagram is the project diagram to be saved + * @param parentLocation is the FS location where the diagram is supposed to be saved + * @param makeDirs true if the method is supposed to create necessary FS structure if missing + * @return a value from SaveResult + */ + public SaveResult saveProjectDiagram(final ProjectDiagram projectDiagram, + final String parentLocation, + final boolean makeDirs); + + /** + * Loads a diagram saved in a notation specific protocol (xml, binary, etc.) form the file on the file system. + * + * Note: + * DISPLAY NAME OF THE LOADED PROJECT DIAGRAM HAS TO MATCH WITH THE FILE NAME WITHOUT THE FILE EXTENSION. + * + * @param diagramLocation is the location of the file representing notation specific dialog on file system + * + * @return an instance of ProjectDiagram class + * + * @throws Exception when something unexpected happens, one of possible reasons is notation mismatch (e.g. there + * is a file on the file system that has extension of a notation, but this file isn't really the diagram file + * of this notation, an exception is then usually thrown). This is why the responsibility for exception handling + * takes programmer and not the service. + */ + public ProjectDiagram loadProjectDiagram(final String diagramLocation) throws Exception; + + /** + * @return the notation's file extension + */ + public String getNotationFileExtension(); +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/model/DiagramModel.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/model/DiagramModel.java index b80112f..eda847e 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/model/DiagramModel.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/model/DiagramModel.java @@ -1,44 +1,44 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:27:56, 31.10.2009 - */ - -/** - * DiagramModel interface is base for all class holding actual diagram. Every diagram is represented by an instance - * of ProjectDiagram, which basically represents an item in project tree navigation. - * - * DiagramModel is supposed to be a holder for actual diagram data like vertexes, connections (edges), etc. - */ -public interface DiagramModel { - - /** - * Adds a listener of any change that has occurred in diagram. - * ProjectDiagram registers a listener during initialization time to be informed about all changes - * in diagram and then change state of it's 'changed' variable. - * - * @see cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram for more info - * - * @param listener is an instance of DiagramModelChangeListener class that will be notified when any change in - * an instance of DiagramModel occurs - */ - public void addChangeListener(final DiagramModelChangeListener listener); - - /** - * This method is invoked on the diagram model when the actual model is being changed and this diagram - * is going to be active. - * - * Can be used e.g. for initial settings and initialization of event handling mechanism when - * the diagram is opened for the first time - e.g. after load. - */ - public void update(); - - /** - * This method is invoked on the diagram when the actual model is being changed and this diagram is going - * to be inactive. - */ - public void over(); - -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:27:56, 31.10.2009 + */ + +/** + * DiagramModel interface is base for all class holding actual diagram. Every diagram is represented by an instance + * of ProjectDiagram, which basically represents an item in project tree navigation. + * + * DiagramModel is supposed to be a holder for actual diagram data like vertexes, connections (edges), etc. + */ +public interface DiagramModel { + + /** + * Adds a listener of any change that has occurred in diagram. + * ProjectDiagram registers a listener during initialization time to be informed about all changes + * in diagram and then change state of it's 'changed' variable. + * + * @see cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram for more info + * + * @param listener is an instance of DiagramModelChangeListener class that will be notified when any change in + * an instance of DiagramModel occurs + */ + public void addChangeListener(final DiagramModelChangeListener listener); + + /** + * This method is invoked on the diagram model when the actual model is being changed and this diagram + * is going to be active. + * + * Can be used e.g. for initial settings and initialization of event handling mechanism when + * the diagram is opened for the first time - e.g. after load. + */ + public void update(); + + /** + * This method is invoked on the diagram when the actual model is being changed and this diagram is going + * to be inactive. + */ + public void over(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/model/DiagramModelChangeListener.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/model/DiagramModelChangeListener.java index 4eee2dd..1af1c09 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/model/DiagramModelChangeListener.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/model/DiagramModelChangeListener.java @@ -1,22 +1,22 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:45:34, 17.1.2010 - */ - -/** - * All listeners of changes in a diagram model are supposed to implement this interface. - */ -public interface DiagramModelChangeListener { - - /** - * Whenever any change in an instance of DiagramModel, then that instance is supposed to invoke - * this method of all it's listeners. - * - * @param change holds any detail info about the change - */ - public void changePerformed(final Object change); - -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:45:34, 17.1.2010 + */ + +/** + * All listeners of changes in a diagram model are supposed to implement this interface. + */ +public interface DiagramModelChangeListener { + + /** + * Whenever any change in an instance of DiagramModel, then that instance is supposed to invoke + * this method of all it's listeners. + * + * @param change holds any detail info about the change + */ + public void changePerformed(final Object change); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/utils/DefaultUpdatableWorkspaceComponent.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/utils/DefaultUpdatableWorkspaceComponent.java index 48dafa8..c019bd2 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/utils/DefaultUpdatableWorkspaceComponent.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/utils/DefaultUpdatableWorkspaceComponent.java @@ -1,109 +1,109 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.utils; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.workspace.UpdatableWorkspaceComponent; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; - -import javax.swing.*; -import java.awt.*; -import java.util.UUID; - -import org.apache.log4j.Logger; -import com.jgoodies.forms.layout.FormLayout; -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.factories.Borders; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 14:38:30, 7.11.2009 - */ - -/** - * If the notation doesn't provide it's workplace, this class will be used as a basic component for the basic workspace.. - */ -public class DefaultUpdatableWorkspaceComponent extends JPanel implements UpdatableWorkspaceComponent{ - - private final Logger LOG = Logger.getLogger(DefaultUpdatableWorkspaceComponent.class); - - private final String notationIdentifier; - - private final JLabel infoLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.default.workspace.title") - ); - - private final JLabel notationIdentifierTitleLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.default.workspace.notation.identifier") - ); - private final JLabel notationIdentifierLabel = ModelerSession.getComponentFactoryService().createLabel(""); - - private final JLabel diagramNameTitleLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.default.workspace.diagram.name") - ); - private final JLabel diagramNameLabel = ModelerSession.getComponentFactoryService().createLabel(""); - - private final JLabel diagramIdentifierTitleLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("modeler.default.workspace.diagram.identifier") - ); - private final JLabel diagramIdentifierLabel = ModelerSession.getComponentFactoryService().createLabel(""); - - - private JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); - - public DefaultUpdatableWorkspaceComponent(final String notationIdentifier){ - this.notationIdentifier = notationIdentifier; - - initLayout(); - } - - private void initLayout(){ - panel.setLayout(new FormLayout( - "pref, 3dlu, max(150;pref)", - "pref, 10dlu, pref, 3dlu, pref, 3dlu, pref" - )); - final CellConstraints cellConstraints = new CellConstraints(); - - int row = 1; - panel.add(infoLabel, cellConstraints.xyw(1, row, 3)); - - row += 2; - panel.add(notationIdentifierTitleLabel, cellConstraints.xy(1, row)); - panel.add(notationIdentifierLabel, cellConstraints.xy(3, row)); - - row += 2; - panel.add(diagramNameTitleLabel, cellConstraints.xy(1, row)); - panel.add(diagramNameLabel, cellConstraints.xy(3, row)); - - row += 2; - panel.add(diagramIdentifierTitleLabel, cellConstraints.xy(1, row)); - panel.add(diagramIdentifierLabel, cellConstraints.xy(3, row)); - - setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - setLayout(new BorderLayout()); - add(panel, BorderLayout.NORTH); - } - - /** {@inheritDoc} */ - public void update() { - LOG.debug("DefaultUpdatableWorkspaceComponent update."); - - final String selectedNotationIdentifier = ModelerSession.getProjectService().getSelectedDiagram().getNotationIdentifier(); - final String selectedDisplayName = ModelerSession.getProjectService().getSelectedDiagram().getDisplayName(); - final UUID selectedDiagramUUID = ModelerSession.getProjectService().getSelectedDiagram().getUuid(); - - if(!notationIdentifier.equals(selectedNotationIdentifier)){ - LOG.error("Selected diagram notation doesn't match with showing workspace component."); - return; - } - - notationIdentifierLabel.setText(selectedNotationIdentifier); - diagramNameLabel.setText(selectedDisplayName); - diagramIdentifierLabel.setText(selectedDiagramUUID.toString()); - } - - /** {@inheritDoc} */ - public void over() { - LOG.debug("DefaultUpdatableWorkspaceComponent over."); - } -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.utils; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.workspace.UpdatableWorkspaceComponent; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; + +import javax.swing.*; +import java.awt.*; +import java.util.UUID; + +import org.apache.log4j.Logger; +import com.jgoodies.forms.layout.FormLayout; +import com.jgoodies.forms.layout.CellConstraints; +import com.jgoodies.forms.factories.Borders; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 14:38:30, 7.11.2009 + */ + +/** + * If the notation doesn't provide it's workplace, this class will be used as a basic component for the basic workspace.. + */ +public class DefaultUpdatableWorkspaceComponent extends JPanel implements UpdatableWorkspaceComponent{ + + private final Logger LOG = Logger.getLogger(DefaultUpdatableWorkspaceComponent.class); + + private final String notationIdentifier; + + private final JLabel infoLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.default.workspace.title") + ); + + private final JLabel notationIdentifierTitleLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.default.workspace.notation.identifier") + ); + private final JLabel notationIdentifierLabel = ModelerSession.getComponentFactoryService().createLabel(""); + + private final JLabel diagramNameTitleLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.default.workspace.diagram.name") + ); + private final JLabel diagramNameLabel = ModelerSession.getComponentFactoryService().createLabel(""); + + private final JLabel diagramIdentifierTitleLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("modeler.default.workspace.diagram.identifier") + ); + private final JLabel diagramIdentifierLabel = ModelerSession.getComponentFactoryService().createLabel(""); + + + private JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); + + public DefaultUpdatableWorkspaceComponent(final String notationIdentifier){ + this.notationIdentifier = notationIdentifier; + + initLayout(); + } + + private void initLayout(){ + panel.setLayout(new FormLayout( + "pref, 3dlu, max(150;pref)", + "pref, 10dlu, pref, 3dlu, pref, 3dlu, pref" + )); + final CellConstraints cellConstraints = new CellConstraints(); + + int row = 1; + panel.add(infoLabel, cellConstraints.xyw(1, row, 3)); + + row += 2; + panel.add(notationIdentifierTitleLabel, cellConstraints.xy(1, row)); + panel.add(notationIdentifierLabel, cellConstraints.xy(3, row)); + + row += 2; + panel.add(diagramNameTitleLabel, cellConstraints.xy(1, row)); + panel.add(diagramNameLabel, cellConstraints.xy(3, row)); + + row += 2; + panel.add(diagramIdentifierTitleLabel, cellConstraints.xy(1, row)); + panel.add(diagramIdentifierLabel, cellConstraints.xy(3, row)); + + setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + setLayout(new BorderLayout()); + add(panel, BorderLayout.NORTH); + } + + /** {@inheritDoc} */ + public void update() { + LOG.debug("DefaultUpdatableWorkspaceComponent update."); + + final String selectedNotationIdentifier = ModelerSession.getProjectService().getSelectedDiagram().getNotationIdentifier(); + final String selectedDisplayName = ModelerSession.getProjectService().getSelectedDiagram().getDisplayName(); + final UUID selectedDiagramUUID = ModelerSession.getProjectService().getSelectedDiagram().getUuid(); + + if(!notationIdentifier.equals(selectedNotationIdentifier)){ + LOG.error("Selected diagram notation doesn't match with showing workspace component."); + return; + } + + notationIdentifierLabel.setText(selectedNotationIdentifier); + diagramNameLabel.setText(selectedDisplayName); + diagramIdentifierLabel.setText(selectedDiagramUUID.toString()); + } + + /** {@inheritDoc} */ + public void over() { + LOG.debug("DefaultUpdatableWorkspaceComponent over."); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/utils/NotationWorkspaceDataDefault.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/utils/NotationWorkspaceDataDefault.java index 248bdc7..565f863 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/utils/NotationWorkspaceDataDefault.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/utils/NotationWorkspaceDataDefault.java @@ -1,37 +1,37 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.utils; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.NotationWorkspaceData; - -import javax.swing.*; - -import java.awt.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:25:38, 18.10.2009 - */ - -/** - * Default implementation of NotationWorkspaceData interface. This class is used in case of - * emergency and during testing to insert an instance of an empty JPanel containing just textual - * form of notation identifier. This class is used when there is not own implementation of - * NotationWorkspaceData available in loaded plugin notation. - */ -public class NotationWorkspaceDataDefault implements NotationWorkspaceData { - - private final String notationIdentifier; - - private final DefaultUpdatableWorkspaceComponent defaultUpdatableWorkspaceComponent; - - public NotationWorkspaceDataDefault(final String notationIdentifier){ - this.notationIdentifier = notationIdentifier; - - defaultUpdatableWorkspaceComponent = new DefaultUpdatableWorkspaceComponent(notationIdentifier); - } - - public JComponent getWorkspaceComponentSingleton() { - return defaultUpdatableWorkspaceComponent; - } -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.utils; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.NotationWorkspaceData; + +import javax.swing.*; + +import java.awt.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:25:38, 18.10.2009 + */ + +/** + * Default implementation of NotationWorkspaceData interface. This class is used in case of + * emergency and during testing to insert an instance of an empty JPanel containing just textual + * form of notation identifier. This class is used when there is not own implementation of + * NotationWorkspaceData available in loaded plugin notation. + */ +public class NotationWorkspaceDataDefault implements NotationWorkspaceData { + + private final String notationIdentifier; + + private final DefaultUpdatableWorkspaceComponent defaultUpdatableWorkspaceComponent; + + public NotationWorkspaceDataDefault(final String notationIdentifier){ + this.notationIdentifier = notationIdentifier; + + defaultUpdatableWorkspaceComponent = new DefaultUpdatableWorkspaceComponent(notationIdentifier); + } + + public JComponent getWorkspaceComponentSingleton() { + return defaultUpdatableWorkspaceComponent; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/workspace/UpdatableWorkspaceComponent.java b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/workspace/UpdatableWorkspaceComponent.java index ecea0d1..d939e92 100644 --- a/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/workspace/UpdatableWorkspaceComponent.java +++ b/IndependentModeler/src/cz/cvut/promod/plugin/notationSpecificPlugIn/notation/workspace/UpdatableWorkspaceComponent.java @@ -1,34 +1,34 @@ -package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.workspace; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 14:36:37, 7.11.2009 - */ - -/** - * This interface is intended to be implemented by the workspace components. Every-time the actual model - * is being changes, the host application (modeler) invokes these methods. - * - * It is up to notation plugin developers whether they use this interface when implementing the workspace - * component or not. It is not required. - * - * This order of method invocation is used when switching working models (diagrams): - * 1. finish() - * 2. over() - */ -public interface UpdatableWorkspaceComponent { - - /** - * This method is invoked on the workspace component when the actual model is being changed and the workspace - * component is going to be active. - */ - public void update(); - - /** - * This method is invoked on the workspace component when the actual model is being changed. This method is invoked - * event if the the workspace component is going to be inactivated. - */ - public void over(); - -} +package cz.cvut.promod.plugin.notationSpecificPlugIn.notation.workspace; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 14:36:37, 7.11.2009 + */ + +/** + * This interface is intended to be implemented by the workspace components. Every-time the actual model + * is being changes, the host application (modeler) invokes these methods. + * + * It is up to notation plugin developers whether they use this interface when implementing the workspace + * component or not. It is not required. + * + * This order of method invocation is used when switching working models (diagrams): + * 1. finish() + * 2. over() + */ +public interface UpdatableWorkspaceComponent { + + /** + * This method is invoked on the workspace component when the actual model is being changed and the workspace + * component is going to be active. + */ + public void update(); + + /** + * This method is invoked on the workspace component when the actual model is being changed. This method is invoked + * event if the the workspace component is going to be inactivated. + */ + public void over(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/resources/Resources.java b/IndependentModeler/src/cz/cvut/promod/resources/Resources.java index 593e55e..18a99a5 100644 --- a/IndependentModeler/src/cz/cvut/promod/resources/Resources.java +++ b/IndependentModeler/src/cz/cvut/promod/resources/Resources.java @@ -1,132 +1,132 @@ -package cz.cvut.promod.resources; - -import org.apache.log4j.Logger; - -import javax.swing.*; -import java.util.Map; -import java.util.HashMap; -import java.net.URL; -import java.io.File; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:35:06, 7.12.2009 - */ - -/** - * Resources class is used to load & store all necessary resources like likes, etc. - */ -public class Resources { - - private static final Logger LOG = Logger.getLogger(Resources.class); - - public static final String NAVIGATION = "navigation/"; - public static final String CONFIG = "config/"; - public static final String MODELER = "modeler/"; - - public final static String PLUGINS_XSD_FILE = "plugins.xsd"; - public final static String PROJECT_XSD_FILE = "project.xsd"; - - public static final String ICONS = "icons/"; - - public static final String DIAGRAM_ICON = "projectDiagram.png"; - public static final String PROJECT_ICON = "projectIcon.png"; - public static final String SUBFOLDER_ICON = "subfolderIcon.png"; - public static final String EXPAND_ALL_ICON = "expandAll.png"; - public static final String COLLAPSE_ICON = "collapse.png"; - public static final String DIAGRAM_ADD_ICON = "pageAdd.png"; - public static final String FOLDER_ADD_ICON = "folderAdd.png"; - - public static final String DELETE_ICON = "delete.png"; - public static final String SAVE_ALL_ICON = "saveAll.png"; - public static final String NEW_PROJECT_ICON = "newProject.png"; - public static final String OPEN_ICON = "open.png"; - public static final String RENAME_ICON = "rename.png"; - - private final static Map icons = new HashMap(); - private final static Map configFiles = new HashMap(); - - - /** - * Returns the icon that has been already loaded or tries to load this icon. - * - * @param resourceName is the full name of required resource (= icon) - * @return the required icon if no error(s) occurred, null otherwise - */ - public static ImageIcon getIcon(final String resourceName){ - ImageIcon imageIcon; - - if(icons.containsKey(resourceName)){ - imageIcon = icons.get(resourceName); - - } else { - imageIcon = loadIcon(resourceName); - - if(imageIcon != null){ - icons.put(resourceName, imageIcon); - } - } - - return imageIcon; - } - - /** - * Loads the icon. - * - * @param resourceName is the full name of the icon - * @return the required icon or null if the there is no resource with given resourceName - */ - private static ImageIcon loadIcon(final String resourceName) { - final URL systemResource = ClassLoader.getSystemResource(resourceName); - - if(systemResource == null){ - LOG.error("Resource " + resourceName + " couldn't be found."); - return null; - } - - return new ImageIcon(systemResource); - } - - /** - * Returns the resource that has been already loaded or tries to load this icon. - * - * @param resourceName is the full name of required resource - * @return the required icon if no error(s) occurred, null otherwise - */ - public static File getConfigFile(final String resourceName){ - File configFile; - - if(icons.containsKey(resourceName)){ - configFile = configFiles.get(resourceName); - - } else { - configFile = loadConfigFile(resourceName); - - if(configFile != null){ - configFiles.put(resourceName, configFile); - } - } - - return configFile; - } - - /** - * Loads the config resources. - * - * @param resourceName is the full name of the resource - * @return the required resource or null if the there is no resource with given resourceName - */ - private static File loadConfigFile(final String resourceName) { - final URL systemResource = ClassLoader.getSystemResource(resourceName); - - if(systemResource == null){ - LOG.error("Resource " + resourceName + " couldn't be found."); - return null; - } - - return new File(systemResource.getFile()); - } - -} - +package cz.cvut.promod.resources; + +import org.apache.log4j.Logger; + +import javax.swing.*; +import java.util.Map; +import java.util.HashMap; +import java.net.URL; +import java.io.File; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:35:06, 7.12.2009 + */ + +/** + * Resources class is used to load & store all necessary resources like likes, etc. + */ +public class Resources { + + private static final Logger LOG = Logger.getLogger(Resources.class); + + public static final String NAVIGATION = "navigation/"; + public static final String CONFIG = "config/"; + public static final String MODELER = "modeler/"; + + public final static String PLUGINS_XSD_FILE = "plugins.xsd"; + public final static String PROJECT_XSD_FILE = "project.xsd"; + + public static final String ICONS = "icons/"; + + public static final String DIAGRAM_ICON = "projectDiagram.png"; + public static final String PROJECT_ICON = "projectIcon.png"; + public static final String SUBFOLDER_ICON = "subfolderIcon.png"; + public static final String EXPAND_ALL_ICON = "expandAll.png"; + public static final String COLLAPSE_ICON = "collapse.png"; + public static final String DIAGRAM_ADD_ICON = "pageAdd.png"; + public static final String FOLDER_ADD_ICON = "folderAdd.png"; + + public static final String DELETE_ICON = "delete.png"; + public static final String SAVE_ALL_ICON = "saveAll.png"; + public static final String NEW_PROJECT_ICON = "newProject.png"; + public static final String OPEN_ICON = "open.png"; + public static final String RENAME_ICON = "rename.png"; + + private final static Map icons = new HashMap(); + private final static Map configFiles = new HashMap(); + + + /** + * Returns the icon that has been already loaded or tries to load this icon. + * + * @param resourceName is the full name of required resource (= icon) + * @return the required icon if no error(s) occurred, null otherwise + */ + public static ImageIcon getIcon(final String resourceName){ + ImageIcon imageIcon; + + if(icons.containsKey(resourceName)){ + imageIcon = icons.get(resourceName); + + } else { + imageIcon = loadIcon(resourceName); + + if(imageIcon != null){ + icons.put(resourceName, imageIcon); + } + } + + return imageIcon; + } + + /** + * Loads the icon. + * + * @param resourceName is the full name of the icon + * @return the required icon or null if the there is no resource with given resourceName + */ + private static ImageIcon loadIcon(final String resourceName) { + final URL systemResource = ClassLoader.getSystemResource(resourceName); + + if(systemResource == null){ + LOG.error("Resource " + resourceName + " couldn't be found."); + return null; + } + + return new ImageIcon(systemResource); + } + + /** + * Returns the resource that has been already loaded or tries to load this icon. + * + * @param resourceName is the full name of required resource + * @return the required icon if no error(s) occurred, null otherwise + */ + public static File getConfigFile(final String resourceName){ + File configFile; + + if(icons.containsKey(resourceName)){ + configFile = configFiles.get(resourceName); + + } else { + configFile = loadConfigFile(resourceName); + + if(configFile != null){ + configFiles.put(resourceName, configFile); + } + } + + return configFile; + } + + /** + * Loads the config resources. + * + * @param resourceName is the full name of the resource + * @return the required resource or null if the there is no resource with given resourceName + */ + private static File loadConfigFile(final String resourceName) { + final URL systemResource = ClassLoader.getSystemResource(resourceName); + + if(systemResource == null){ + LOG.error("Resource " + resourceName + " couldn't be found."); + return null; + } + + return new File(systemResource.getFile()); + } + +} + diff --git a/IndependentModeler/src/cz/cvut/promod/resources/TranslationCheck.java b/IndependentModeler/src/cz/cvut/promod/resources/TranslationCheck.java index 6ceb900..686d319 100644 --- a/IndependentModeler/src/cz/cvut/promod/resources/TranslationCheck.java +++ b/IndependentModeler/src/cz/cvut/promod/resources/TranslationCheck.java @@ -1,227 +1,227 @@ -package cz.cvut.promod.resources; - -import org.apache.log4j.Logger; -import cz.cvut.promod.services.ModelerSession; - -import java.util.MissingResourceException; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:38:10, 26.4.2010 - */ - -/** - * Checks whether there is no missing translation. - */ -public class TranslationCheck { - - private static Logger LOG = Logger.getLogger(TranslationCheck.class); - - public static final String[] translation_keys = { - "modeler.ok", - "modeler.yes", - "modeler.no", - "modeler.cancel", - "modeler.apply", - "modeler.plugin.notation", - "modeler.plugin.module", - "modeler.plugin.extension", - "modeler.exit.save.all", - "modeler.exit.skip.all", - "modeler.exit", - "modeler.exit.diagram.unsaved.change", - "modeler.settings", - "modeler.plugins.overview", - "modeler.plugins.overview.notations.title", - "modeler.plugins.overview.extension.title", - "modeler.plugins.overview.identifier", - "modeler.plugins.overview.name", - "modeler.plugins.overview.description", - "modeler.plugins.overview.abbreviation", - "modeler.plugins.overview.full.name", - "modeler.plugins.overview.tool.tip", - "modeler.plugins.overview.file.ext", - "modeler.dockable.frame.move", - "modeler.dockable.frame.move.left", - "modeler.dockable.frame.move.right", - "modeler.dockable.frame.move.top", - "modeler.dockable.frame.move.bottom", - "modeler.configuration.title", - "modeler.configuration.message", - "modeler.configuration.message.detail", - "modeler.configuration.hideButton", - "modeler.configuration.missing.notation", - "modeler.configuration.loaded.value", - "modeler.configuration.actual.value", - "modeler.configuration.missing.module", - "modeler.configuration.missing.extension", - "modeler.configuration.related.notation", - "modeler.configuration.different.extension", - "modeler.configuration.different.abbreviation", - "modeler.configuration.different.name", - "modeler.loadErrorsDialog.message", - "modeler.loadErrorsDialog.log", - "modeler.loadErrorsDialog.title", - "modeler.loadErrorsDialog.hideButton", - "modeler.loadErrorsDialog.propertyName", - "modeler.loadErrorsDialog.fullClassName", - "modeler.loadErrorsDialog.error", - "modeler.loadErrorsDialog.error.message", - "modeler.menu.file", - "modeler.menu.edit", - "modeler.action.exit", - "modeler.action.new.project", - "modeler.action.navigation", - "modeler.action.project.load", - "modeler.action.project.load.description", - "modeler.action.project.load.error.loadfile.title", - "modeler.action.project.load.error.loadfile", - "modeler.action.project.load.error.sync.title", - "modeler.action.project.load.error.sync.message", - "modeler.action.project.save", - "modeler.menu.project", - "modeler.menu.window", - "modeler.project.navigation.expand.all", - "modeler.project.navigation.rename", - "modeler.project.rename.description", - "modeler.project.rename.duplicity", - "modeler.project.rename.error", - "modeler.project.rename.error.title", - "modeler.project.navigation.collapse.all", - "modeler.project.navigation.new.diagram", - "modeler.project.navigation.new.subfolder", - "modeler.project.navigation.add", - "modeler.project.navigation.close.project", - "modeler.project.navigation.refresh", - "modeler.project.navigation.delete", - "modeler.project.navigation.delete.diagram.title", - "modeler.project.navigation.delete.diagram.message", - "modeler.project.navigation.delete.diagram.error.message", - "modeler.project.navigation.delete.subfolder.title", - "modeler.project.navigation.delete.subfolder.message", - "modeler.project.navigation.delete.subfolder.error.message", - "modeler.project.navigation.delete.project.title", - "modeler.project.navigation.delete.project.message", - "modeler.project.navigation.add.subfolder", - "modeler.project.navigation.add.diagram", - "modeler.project.navigation.expand", - "modeler.add.new.subfolder.dialog.title", - "modeler.add.new.subfolder.dialog.label", - "modeler.add.new.subfolder.dialog.confirm", - "modeler.add.new.subfolder.dialog.error.disallowed", - "modeler.add.new.subfolder.dialog.error.nameduplicity", - "modeler.add.new.subfolder.dialog.error", - "modeler.add.new.project.dialog.error.general", - "modeler.add.new.project.dialog.error.relative", - "modeler.add.new.project.dialog.error.existing.file", - "modeler.add.new.project.dialog.error.duplicity", - "modeler.add.new.project.dialog.error.shortName", - "modeler.add.new.project.dialog.error.io", - "modeler.add.new.project.dialog.error.disallowed", - "modeler.add.new.diagram.dialog.title", - "modeler.add.new.diagram.dialog.confirm", - "modeler.add.new.diagram.dialog.tableTitle", - "modeler.add.new.diagram.dialog.nameTitle", - "modeler.add.new.diagram.dialog.noImage", - "modeler.add.new.diagram.dialog.error.duplicity", - "modeler.add.new.diagram.dialog.error.illegalParent", - "modeler.add.new.diagram.dialog.error.illegalNotation", - "modeler.add.new.diagram.dialog.error.disallowed", - "modeler.add.new.diagram.dialog.error", - "modeler.add.dialog.error.noSelectedProject", - "modeler.add.dialog.error.noSelProjectTitle", - "modeler.default.workspace.title", - "modeler.default.workspace.notation.identifier", - "modeler.default.workspace.diagram.name", - "modeler.default.workspace.diagram.identifier", - "project.service.sync.dialog.fromFS.title", - "project.service.sync.dialog.fromPN.title", - "project.service.sync.dialog.errorlist", - "project.service.sync.dialog.searching", - "project.service.sync.dialog.cancel", - "project.service.sync.dialog.canceled", - "project.service.sync.dialog.searching.done", - "project.service.sync.dialog.treepatherror", - "project.service.sync.dialog.default.error.message", - "project.service.sync.dialog.invalidname.error.message", - "project.service.sync.dialog.default.error.from", - "project.service.sync.dialog.default.error.to", - "project.service.sync.dialog.exception", - "project.service.sync.dialog.directory.error", - "project.service.sync.dialog.offset.error", - "project.service.sync.dialog.invalid.treepath", - "project.service.sync.dialog.invalid.parent", - "project.service.sync.dialog.missing.project.file", - "project.service.sync.dialog.diagram.overwritten", - "project.service.sync.dialog.diagram.write", - "project.service.sync.dialog.mkdir.error", - "project.service.sync.dialog.delete.error", - "project.service.sync.dialog.project.file.error", - "project.service.sync.dialog.error.load.project.file", - "project.service.sync.dialog.error.invalid.project.root", - "project.service.sync.dialog.error.subtree", - "project.service.sync.dialog.error.subtree.not.exist", - "project.service.sync.dialog.project.root.error", - "project.service.sync.dialog.subtree.build.error", - "project.service.sync.dialog.diagram.load.error", - "project.service.sync.dialog.diagram.error.identifier", - "project.service.sync.dialog.diagram.error.extension", - "project.service.sync.dialog.diagram.error.diagram", - "modeler.user.service", - "modeler.user.name", - "modeler.user.title", - "modeler.user.switch", - "modeler.user.invalid.name", - "pluginLoaderService.error.missing.xsd", - "pluginLoaderService.error.noError", - "pluginLoaderService.error.xmlParsing", - "pluginLoaderService.error.className", - "pluginLoaderService.error.findClass", - "pluginLoaderService.error.classHierarchy", - "pluginLoaderService.error.instantiation", - "pluginLoaderService.error.nullaryNotationName", - "pluginLoaderService.error.emptyNotationName", - "pluginLoaderService.error.noModelFactory", - "pluginLoaderService.error.invalidModelFactory", - "pluginLoaderService.error.nullaryAbbreviation", - "pluginLoaderService.error.emptyAbbreviation", - "pluginLoaderService.error.ioController", - "pluginLoaderService.error.nullaryFileExtension", - "pluginLoaderService.error.emptyFileExtension", - "pluginLoaderService.error.notationIdentifierDuplicity", - "pluginLoaderService.error.nullaryPluginIdentifier", - "pluginLoaderService.error.likeModelerpluginIdentifier", - "pluginLoaderService.error.emptyPluginIdentifier", - "pluginLoaderService.error.noRelatedNotationIdentifier", - "pluginLoaderService.error.nullaryRelatedNotationIdentifier", - "pluginLoaderService.error.emptyRelatedNotationIdentifier", - "pluginLoaderService.error.moduleIdentifierDuplicity", - "pluginLoaderService.error.extensionIdentifierDuplicity", - "pluginLoaderService.error.nullaryExtensionDescription", - "pluginLoaderService.error.nullaryPluginName", - "pluginLoaderService.error.emptyPluginName", - "pluginLoaderService.error.projectFileLikeNotation", - "pluginLoaderService.error.notationExtensionDuplicity", - "pluginLoaderService.error.too.long.identifier", - "modeler.action.new.project.dialog", - }; - - /** - * Checks whether no translation is missing. - * - * @return true if no translation is missing, false otherwise - */ - public static boolean validateTranslations(){ - for(final String key : translation_keys){ - try{ - ModelerSession.getCommonResourceBundle().getString(key); - } catch (MissingResourceException exception){ - LOG.error("Missing translation for key: " + key + "."); - return false; - } - } - - return true; - } -} +package cz.cvut.promod.resources; + +import org.apache.log4j.Logger; +import cz.cvut.promod.services.ModelerSession; + +import java.util.MissingResourceException; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:38:10, 26.4.2010 + */ + +/** + * Checks whether there is no missing translation. + */ +public class TranslationCheck { + + private static Logger LOG = Logger.getLogger(TranslationCheck.class); + + public static final String[] translation_keys = { + "modeler.ok", + "modeler.yes", + "modeler.no", + "modeler.cancel", + "modeler.apply", + "modeler.plugin.notation", + "modeler.plugin.module", + "modeler.plugin.extension", + "modeler.exit.save.all", + "modeler.exit.skip.all", + "modeler.exit", + "modeler.exit.diagram.unsaved.change", + "modeler.settings", + "modeler.plugins.overview", + "modeler.plugins.overview.notations.title", + "modeler.plugins.overview.extension.title", + "modeler.plugins.overview.identifier", + "modeler.plugins.overview.name", + "modeler.plugins.overview.description", + "modeler.plugins.overview.abbreviation", + "modeler.plugins.overview.full.name", + "modeler.plugins.overview.tool.tip", + "modeler.plugins.overview.file.ext", + "modeler.dockable.frame.move", + "modeler.dockable.frame.move.left", + "modeler.dockable.frame.move.right", + "modeler.dockable.frame.move.top", + "modeler.dockable.frame.move.bottom", + "modeler.configuration.title", + "modeler.configuration.message", + "modeler.configuration.message.detail", + "modeler.configuration.hideButton", + "modeler.configuration.missing.notation", + "modeler.configuration.loaded.value", + "modeler.configuration.actual.value", + "modeler.configuration.missing.module", + "modeler.configuration.missing.extension", + "modeler.configuration.related.notation", + "modeler.configuration.different.extension", + "modeler.configuration.different.abbreviation", + "modeler.configuration.different.name", + "modeler.loadErrorsDialog.message", + "modeler.loadErrorsDialog.log", + "modeler.loadErrorsDialog.title", + "modeler.loadErrorsDialog.hideButton", + "modeler.loadErrorsDialog.propertyName", + "modeler.loadErrorsDialog.fullClassName", + "modeler.loadErrorsDialog.error", + "modeler.loadErrorsDialog.error.message", + "modeler.menu.file", + "modeler.menu.edit", + "modeler.action.exit", + "modeler.action.new.project", + "modeler.action.navigation", + "modeler.action.project.load", + "modeler.action.project.load.description", + "modeler.action.project.load.error.loadfile.title", + "modeler.action.project.load.error.loadfile", + "modeler.action.project.load.error.sync.title", + "modeler.action.project.load.error.sync.message", + "modeler.action.project.save", + "modeler.menu.project", + "modeler.menu.window", + "modeler.project.navigation.expand.all", + "modeler.project.navigation.rename", + "modeler.project.rename.description", + "modeler.project.rename.duplicity", + "modeler.project.rename.error", + "modeler.project.rename.error.title", + "modeler.project.navigation.collapse.all", + "modeler.project.navigation.new.diagram", + "modeler.project.navigation.new.subfolder", + "modeler.project.navigation.add", + "modeler.project.navigation.close.project", + "modeler.project.navigation.refresh", + "modeler.project.navigation.delete", + "modeler.project.navigation.delete.diagram.title", + "modeler.project.navigation.delete.diagram.message", + "modeler.project.navigation.delete.diagram.error.message", + "modeler.project.navigation.delete.subfolder.title", + "modeler.project.navigation.delete.subfolder.message", + "modeler.project.navigation.delete.subfolder.error.message", + "modeler.project.navigation.delete.project.title", + "modeler.project.navigation.delete.project.message", + "modeler.project.navigation.add.subfolder", + "modeler.project.navigation.add.diagram", + "modeler.project.navigation.expand", + "modeler.add.new.subfolder.dialog.title", + "modeler.add.new.subfolder.dialog.label", + "modeler.add.new.subfolder.dialog.confirm", + "modeler.add.new.subfolder.dialog.error.disallowed", + "modeler.add.new.subfolder.dialog.error.nameduplicity", + "modeler.add.new.subfolder.dialog.error", + "modeler.add.new.project.dialog.error.general", + "modeler.add.new.project.dialog.error.relative", + "modeler.add.new.project.dialog.error.existing.file", + "modeler.add.new.project.dialog.error.duplicity", + "modeler.add.new.project.dialog.error.shortName", + "modeler.add.new.project.dialog.error.io", + "modeler.add.new.project.dialog.error.disallowed", + "modeler.add.new.diagram.dialog.title", + "modeler.add.new.diagram.dialog.confirm", + "modeler.add.new.diagram.dialog.tableTitle", + "modeler.add.new.diagram.dialog.nameTitle", + "modeler.add.new.diagram.dialog.noImage", + "modeler.add.new.diagram.dialog.error.duplicity", + "modeler.add.new.diagram.dialog.error.illegalParent", + "modeler.add.new.diagram.dialog.error.illegalNotation", + "modeler.add.new.diagram.dialog.error.disallowed", + "modeler.add.new.diagram.dialog.error", + "modeler.add.dialog.error.noSelectedProject", + "modeler.add.dialog.error.noSelProjectTitle", + "modeler.default.workspace.title", + "modeler.default.workspace.notation.identifier", + "modeler.default.workspace.diagram.name", + "modeler.default.workspace.diagram.identifier", + "project.service.sync.dialog.fromFS.title", + "project.service.sync.dialog.fromPN.title", + "project.service.sync.dialog.errorlist", + "project.service.sync.dialog.searching", + "project.service.sync.dialog.cancel", + "project.service.sync.dialog.canceled", + "project.service.sync.dialog.searching.done", + "project.service.sync.dialog.treepatherror", + "project.service.sync.dialog.default.error.message", + "project.service.sync.dialog.invalidname.error.message", + "project.service.sync.dialog.default.error.from", + "project.service.sync.dialog.default.error.to", + "project.service.sync.dialog.exception", + "project.service.sync.dialog.directory.error", + "project.service.sync.dialog.offset.error", + "project.service.sync.dialog.invalid.treepath", + "project.service.sync.dialog.invalid.parent", + "project.service.sync.dialog.missing.project.file", + "project.service.sync.dialog.diagram.overwritten", + "project.service.sync.dialog.diagram.write", + "project.service.sync.dialog.mkdir.error", + "project.service.sync.dialog.delete.error", + "project.service.sync.dialog.project.file.error", + "project.service.sync.dialog.error.load.project.file", + "project.service.sync.dialog.error.invalid.project.root", + "project.service.sync.dialog.error.subtree", + "project.service.sync.dialog.error.subtree.not.exist", + "project.service.sync.dialog.project.root.error", + "project.service.sync.dialog.subtree.build.error", + "project.service.sync.dialog.diagram.load.error", + "project.service.sync.dialog.diagram.error.identifier", + "project.service.sync.dialog.diagram.error.extension", + "project.service.sync.dialog.diagram.error.diagram", + "modeler.user.service", + "modeler.user.name", + "modeler.user.title", + "modeler.user.switch", + "modeler.user.invalid.name", + "pluginLoaderService.error.missing.xsd", + "pluginLoaderService.error.noError", + "pluginLoaderService.error.xmlParsing", + "pluginLoaderService.error.className", + "pluginLoaderService.error.findClass", + "pluginLoaderService.error.classHierarchy", + "pluginLoaderService.error.instantiation", + "pluginLoaderService.error.nullaryNotationName", + "pluginLoaderService.error.emptyNotationName", + "pluginLoaderService.error.noModelFactory", + "pluginLoaderService.error.invalidModelFactory", + "pluginLoaderService.error.nullaryAbbreviation", + "pluginLoaderService.error.emptyAbbreviation", + "pluginLoaderService.error.ioController", + "pluginLoaderService.error.nullaryFileExtension", + "pluginLoaderService.error.emptyFileExtension", + "pluginLoaderService.error.notationIdentifierDuplicity", + "pluginLoaderService.error.nullaryPluginIdentifier", + "pluginLoaderService.error.likeModelerpluginIdentifier", + "pluginLoaderService.error.emptyPluginIdentifier", + "pluginLoaderService.error.noRelatedNotationIdentifier", + "pluginLoaderService.error.nullaryRelatedNotationIdentifier", + "pluginLoaderService.error.emptyRelatedNotationIdentifier", + "pluginLoaderService.error.moduleIdentifierDuplicity", + "pluginLoaderService.error.extensionIdentifierDuplicity", + "pluginLoaderService.error.nullaryExtensionDescription", + "pluginLoaderService.error.nullaryPluginName", + "pluginLoaderService.error.emptyPluginName", + "pluginLoaderService.error.projectFileLikeNotation", + "pluginLoaderService.error.notationExtensionDuplicity", + "pluginLoaderService.error.too.long.identifier", + "modeler.action.new.project.dialog", + }; + + /** + * Checks whether no translation is missing. + * + * @return true if no translation is missing, false otherwise + */ + public static boolean validateTranslations(){ + for(final String key : translation_keys){ + try{ + ModelerSession.getCommonResourceBundle().getString(key); + } catch (MissingResourceException exception){ + LOG.error("Missing translation for key: " + key + "."); + return false; + } + } + + return true; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/ModelerSession.java b/IndependentModeler/src/cz/cvut/promod/services/ModelerSession.java index 82056e3..caa33b5 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/ModelerSession.java +++ b/IndependentModeler/src/cz/cvut/promod/services/ModelerSession.java @@ -1,457 +1,457 @@ -package cz.cvut.promod.services; - -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; -import cz.cvut.promod.services.userService.UserService; -import cz.cvut.promod.services.actionService.ActionControlService; -import cz.cvut.promod.services.actionService.ActionService; -import cz.cvut.promod.services.projectService.ProjectControlService; -import cz.cvut.promod.services.projectService.ProjectService; -import cz.cvut.promod.services.menuService.MenuService; -import cz.cvut.promod.services.notationService.NotationService; -import cz.cvut.promod.services.toolBarService.ToolBarService; -import cz.cvut.promod.services.toolBarService.ToolBarControlService; -import cz.cvut.promod.services.statusBarService.StatusBarControlService; -import cz.cvut.promod.services.statusBarService.StatusBarService; -import cz.cvut.promod.services.extensionService.ExtensionService; -import cz.cvut.promod.gui.ModelerModel; -import org.apache.log4j.Logger; - -import javax.swing.*; -import java.util.ResourceBundle; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:10:56, 10.10.2009 - */ - -/** - * ModelerSession allows access to all services and shared resources. - * - * It is supposed to be an entry point for plugins when need to use services. - * - * IMPORTANT NOTE: One is always supposed to use all services and other resources only in Event Dispatcher Thread - * or Main Thread (during application start). - * - * Usage of services and their resources form another thread than Event Dispatcher Thread or Main Thread can cause a - * unpredictable inconsistency of application. One is supposed to always avoid using services and their - * resources out of the Event Dispatcher Thread (when the GUI is shown)! - * - * @see cz.cvut.promod.services.Service - * @see javax.swing.SwingUtilities - */ -public final class ModelerSession { - - private static final Logger LOG = Logger.getLogger(ModelerSession.class); - - /** testing purposes */ - public static final String NULL_METHOD_NAME = "nullServices"; - - private static final ModelerSession MODELER_SESSION_INSTANCE = new ModelerSession(); - - private static ResourceBundle commonResourceBundle = null; - - private static JFrame frame = null; - - private ComponentFactoryService componentFactoryService = null; - private UserService userService = null; - private ActionControlService actionControlService = null; - private ProjectControlService projectControlService = null; - private MenuService menuService = null; - private NotationService notationService = null; - private ToolBarControlService toolBarControlService = null; - private StatusBarControlService statusBarControlService = null; - private ExtensionService extensionsService = null; - - /** - * @return every-time the same instance of ModelerSession (singleton) - */ - public static ModelerSession getModelerSession() { - return MODELER_SESSION_INSTANCE; - } - - /** - * Returns the common resource bundle - common translations. - * - * @return the common resource bundle - common translations - */ - public static ResourceBundle getCommonResourceBundle() { - return commonResourceBundle; - } - - /** - * Sets the resource bundle object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param commonResourceBundle the resource bundle holding translations - */ - public static void setCommonResourceBundle(final ResourceBundle commonResourceBundle) { - if(ModelerSession.commonResourceBundle == null){ - ModelerSession.commonResourceBundle = commonResourceBundle; - } - } - - /** - * Usage of this method is a way how to get reference to the JFrame object of Modeler. - * One should always check whether return value is not null before actual use. - * - * @return an instance of the modeler frame - */ - public static JFrame getFrame() { - return frame; - } - - /** - * Allows to set a title for the Modeler frame. - * - * @param text is the text to be shown - */ - public static void setFrameTitleText(final String text){ - if(frame != null){ - final StringBuffer stringBuffer = new StringBuffer(); - stringBuffer.append(ModelerModel.APPLICATION_NAME); - - if(text != null && !text.isEmpty()){ - stringBuffer.append(" - ["); - stringBuffer.append(text); - stringBuffer.append("]"); - } - - frame.setTitle(stringBuffer.toString()); - } - } - - /** - * Sets the title of Modeler frame to initial text. - */ - public static void clearFrameTitleText(){ - if(frame != null){ - frame.setTitle(ModelerModel.APPLICATION_NAME); - } - } - - /** - * Sets the application frame object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param frame is the application frame - */ - public static void setFrame(final JFrame frame) { - if(ModelerSession.frame == null){ - ModelerSession.frame = frame; - } - } - - /** - * Returns the ComponentFactoryService object. - * - * @return every-time the same ComponentFactoryService object - */ - public static ComponentFactoryService getComponentFactoryService() { - final ComponentFactoryService componentFactoryService = MODELER_SESSION_INSTANCE.componentFactoryService; - - if(componentFactoryService == null){ - LOG.error("ComponentFactoryService has not been set."); - throw new NullPointerException("ComponentFactoryService is not available."); - } - - return componentFactoryService; - } - - /** - * Sets the ComponentFactoryService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param componentFactoryService is the ComponentFactoryService object - */ - public static void setComponentFactoryService(final ComponentFactoryService componentFactoryService) { - MODELER_SESSION_INSTANCE.componentFactoryService = componentFactoryService; - } - - /** - * Returns the UserService object. - * - * @return every-time the same UserService object - */ - public static UserService getUserService() { - return MODELER_SESSION_INSTANCE.userService; - } - - /** - * Sets the UserService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param userService is the UserService object - */ - public static void setUserService(final UserService userService) { - MODELER_SESSION_INSTANCE.userService = userService; - } - - public static ActionControlService getActionControlService() { - final ActionControlService actionControlService = MODELER_SESSION_INSTANCE.actionControlService; - - if(actionControlService == null){ - LOG.error("ActionControlService has not been set."); - throw new NullPointerException("ActionControlService is not available."); - } - - return actionControlService; - } - - public static ActionService getActionService() { - final ActionService actionService = MODELER_SESSION_INSTANCE.actionControlService; - - if(actionService == null){ - LOG.error("ActionService has not been set."); - throw new NullPointerException("ActionService is not available."); - } - - return actionService; - } - - /** - * Sets the ActionControlService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param actionControlService is the ActionControlService object - */ - public static void setActionControlService(final ActionControlService actionControlService) { - if(MODELER_SESSION_INSTANCE.actionControlService == null){ - MODELER_SESSION_INSTANCE.actionControlService = actionControlService; - } - } - - /** - * Returns the ProjectControlService object. - * - * @return every-time the same ProjectControlService object - */ - public static ProjectControlService getProjectControlService() { - final ProjectControlService projectControlService = MODELER_SESSION_INSTANCE.projectControlService; - - if(projectControlService == null){ - LOG.error("ProjectControlService has not been set."); - throw new NullPointerException("ProjectControlService is not available."); - } - - return projectControlService; - } - - /** - * Returns the ProjectService object. - * - * @return every-time the same ProjectService object - */ - public static ProjectService getProjectService() { - final ProjectService projectService = MODELER_SESSION_INSTANCE.projectControlService; - - if(projectService == null){ - LOG.error("ProjectService has not been set."); - throw new NullPointerException("ProjectService is not available."); - } - - return projectService; - } - - /** - * Sets the ProjectControlService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param projectControlService is the ProjectControlService object - */ - public static void setProjectControlService(final ProjectControlService projectControlService) { - if(MODELER_SESSION_INSTANCE.projectControlService == null){ - MODELER_SESSION_INSTANCE.projectControlService = projectControlService; - } - } - - /** - * Returns the MenuService object. - * - * @return every-time the same MenuService object - */ - public static MenuService getMenuService() { - final MenuService menuService = MODELER_SESSION_INSTANCE.menuService; - - if(menuService == null){ - LOG.error("MenuService has not been set."); - throw new NullPointerException("MenuService is not available."); - } - - return menuService; - } - - /** - * Sets the MenuService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param menuService is the MenuService object - */ - public static void setMainMenuService(final MenuService menuService) { - if(MODELER_SESSION_INSTANCE.menuService == null){ - MODELER_SESSION_INSTANCE.menuService = menuService; - } - } - - /** - * Returns the NotationService object. - * - * @return every-time the same NotationService object - */ - public static NotationService getNotationService() { - final NotationService notationService = MODELER_SESSION_INSTANCE.notationService; - - if(notationService == null){ - LOG.error("NotationService has not been set."); - throw new NullPointerException("NotationService is not available."); - } - - return notationService; - } - - /** - * Sets the NotationService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param notationService is the NotationService object - */ - public static void setNotationService(final NotationService notationService) { - if(MODELER_SESSION_INSTANCE.notationService == null){ - MODELER_SESSION_INSTANCE.notationService = notationService; - } - } - - /** - * Returns the ToolBarService object. - * - * @return every-time the same ToolBarService object - */ - public static ToolBarService getToolBarService() { - final ToolBarService toolBarService = MODELER_SESSION_INSTANCE.toolBarControlService; - - if(toolBarService == null){ - LOG.error("ToolBarService has not been set."); - throw new NullPointerException("ToolBarService is not available."); - } - - return toolBarService; - } - - /** - * Returns the ToolBarControlService object. - * - * @return every-time the same ToolBarControlService object - */ - public static ToolBarControlService getToolBarControlService() { - final ToolBarControlService toolBarControlService = MODELER_SESSION_INSTANCE.toolBarControlService; - - if(toolBarControlService == null){ - LOG.error("ToolBarControlService has not been set."); - throw new NullPointerException("ToolBarControlService is not available."); - } - - return toolBarControlService; - } - - /** - * Sets the ToolBarControlService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param toolBarService is the ToolBarControlService object - */ - public static void setToolBarControlService(final ToolBarControlService toolBarService) { - if(MODELER_SESSION_INSTANCE.toolBarControlService == null){ - MODELER_SESSION_INSTANCE.toolBarControlService = toolBarService; - } - } - - /** - * Returns the StatusBarControlService object. - * - * @return every-time the same StatusBarControlService object - */ - public static StatusBarControlService getStatusBarControlService() { - final StatusBarControlService statusBarControlService = MODELER_SESSION_INSTANCE.statusBarControlService; - - if(statusBarControlService == null){ - LOG.error("statusBarControlService has not been set."); - throw new NullPointerException("statusBarControlService is not available."); - } - - return statusBarControlService; - } - - /** - * Returns the StatusBarService object. - * - * @return every-time the same StatusBarService object - */ - public static StatusBarService getStatusBarService() { - final StatusBarService statusBarService = MODELER_SESSION_INSTANCE.statusBarControlService; - - if(statusBarService == null){ - LOG.error("statusBarService has not been set."); - throw new NullPointerException("statusBarService is not available."); - } - - return statusBarService; - } - - /** - * Sets the StatusBarControlService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param statusBarControlService is the StatusBarControlService object - */ - public static void setStatusBarControlService(final StatusBarControlService statusBarControlService) { - if(MODELER_SESSION_INSTANCE.statusBarControlService == null){ - MODELER_SESSION_INSTANCE.statusBarControlService = statusBarControlService; - } - } - - /** - * Returns the ExtensionService object. - * - * @return every-time the same ExtensionService object - */ - public static ExtensionService getExtensionService() { - final ExtensionService extensionService = MODELER_SESSION_INSTANCE.extensionsService; - - if(extensionService == null){ - LOG.error("extension service has not been set."); - throw new NullPointerException("extension service is not available."); - } - - return extensionService; - } - - /** - * Sets the ExtensionService object. It can be set only once. All next attempts to set it again will - * have no effect. - * - * @param extensionService is the ExtensionService object - */ - public static void setExtensionService(final ExtensionService extensionService) { - if(MODELER_SESSION_INSTANCE.extensionsService == null){ - MODELER_SESSION_INSTANCE.extensionsService = extensionService; - } - } - - /** - * Private static method to null all services. Used in automatic tests - JUnit tests to null services. - * None is supposed to use this method for non-testing purposes. - * - * Tests use this method through reflection. - */ - private static void nullServices(){ - MODELER_SESSION_INSTANCE.componentFactoryService = null; - MODELER_SESSION_INSTANCE.userService = null; - MODELER_SESSION_INSTANCE.actionControlService = null; - MODELER_SESSION_INSTANCE.projectControlService = null; - MODELER_SESSION_INSTANCE.menuService = null; - MODELER_SESSION_INSTANCE.notationService = null; - MODELER_SESSION_INSTANCE.toolBarControlService = null; - MODELER_SESSION_INSTANCE.statusBarControlService = null; - MODELER_SESSION_INSTANCE.extensionsService = null; - } +package cz.cvut.promod.services; + +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; +import cz.cvut.promod.services.userService.UserService; +import cz.cvut.promod.services.actionService.ActionControlService; +import cz.cvut.promod.services.actionService.ActionService; +import cz.cvut.promod.services.projectService.ProjectControlService; +import cz.cvut.promod.services.projectService.ProjectService; +import cz.cvut.promod.services.menuService.MenuService; +import cz.cvut.promod.services.notationService.NotationService; +import cz.cvut.promod.services.toolBarService.ToolBarService; +import cz.cvut.promod.services.toolBarService.ToolBarControlService; +import cz.cvut.promod.services.statusBarService.StatusBarControlService; +import cz.cvut.promod.services.statusBarService.StatusBarService; +import cz.cvut.promod.services.extensionService.ExtensionService; +import cz.cvut.promod.gui.ModelerModel; +import org.apache.log4j.Logger; + +import javax.swing.*; +import java.util.ResourceBundle; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:10:56, 10.10.2009 + */ + +/** + * ModelerSession allows access to all services and shared resources. + * + * It is supposed to be an entry point for plugins when need to use services. + * + * IMPORTANT NOTE: One is always supposed to use all services and other resources only in Event Dispatcher Thread + * or Main Thread (during application start). + * + * Usage of services and their resources form another thread than Event Dispatcher Thread or Main Thread can cause a + * unpredictable inconsistency of application. One is supposed to always avoid using services and their + * resources out of the Event Dispatcher Thread (when the GUI is shown)! + * + * @see cz.cvut.promod.services.Service + * @see javax.swing.SwingUtilities + */ +public final class ModelerSession { + + private static final Logger LOG = Logger.getLogger(ModelerSession.class); + + /** testing purposes */ + public static final String NULL_METHOD_NAME = "nullServices"; + + private static final ModelerSession MODELER_SESSION_INSTANCE = new ModelerSession(); + + private static ResourceBundle commonResourceBundle = null; + + private static JFrame frame = null; + + private ComponentFactoryService componentFactoryService = null; + private UserService userService = null; + private ActionControlService actionControlService = null; + private ProjectControlService projectControlService = null; + private MenuService menuService = null; + private NotationService notationService = null; + private ToolBarControlService toolBarControlService = null; + private StatusBarControlService statusBarControlService = null; + private ExtensionService extensionsService = null; + + /** + * @return every-time the same instance of ModelerSession (singleton) + */ + public static ModelerSession getModelerSession() { + return MODELER_SESSION_INSTANCE; + } + + /** + * Returns the common resource bundle - common translations. + * + * @return the common resource bundle - common translations + */ + public static ResourceBundle getCommonResourceBundle() { + return commonResourceBundle; + } + + /** + * Sets the resource bundle object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param commonResourceBundle the resource bundle holding translations + */ + public static void setCommonResourceBundle(final ResourceBundle commonResourceBundle) { + if(ModelerSession.commonResourceBundle == null){ + ModelerSession.commonResourceBundle = commonResourceBundle; + } + } + + /** + * Usage of this method is a way how to get reference to the JFrame object of Modeler. + * One should always check whether return value is not null before actual use. + * + * @return an instance of the modeler frame + */ + public static JFrame getFrame() { + return frame; + } + + /** + * Allows to set a title for the Modeler frame. + * + * @param text is the text to be shown + */ + public static void setFrameTitleText(final String text){ + if(frame != null){ + final StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append(ModelerModel.APPLICATION_NAME); + + if(text != null && !text.isEmpty()){ + stringBuffer.append(" - ["); + stringBuffer.append(text); + stringBuffer.append("]"); + } + + frame.setTitle(stringBuffer.toString()); + } + } + + /** + * Sets the title of Modeler frame to initial text. + */ + public static void clearFrameTitleText(){ + if(frame != null){ + frame.setTitle(ModelerModel.APPLICATION_NAME); + } + } + + /** + * Sets the application frame object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param frame is the application frame + */ + public static void setFrame(final JFrame frame) { + if(ModelerSession.frame == null){ + ModelerSession.frame = frame; + } + } + + /** + * Returns the ComponentFactoryService object. + * + * @return every-time the same ComponentFactoryService object + */ + public static ComponentFactoryService getComponentFactoryService() { + final ComponentFactoryService componentFactoryService = MODELER_SESSION_INSTANCE.componentFactoryService; + + if(componentFactoryService == null){ + LOG.error("ComponentFactoryService has not been set."); + throw new NullPointerException("ComponentFactoryService is not available."); + } + + return componentFactoryService; + } + + /** + * Sets the ComponentFactoryService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param componentFactoryService is the ComponentFactoryService object + */ + public static void setComponentFactoryService(final ComponentFactoryService componentFactoryService) { + MODELER_SESSION_INSTANCE.componentFactoryService = componentFactoryService; + } + + /** + * Returns the UserService object. + * + * @return every-time the same UserService object + */ + public static UserService getUserService() { + return MODELER_SESSION_INSTANCE.userService; + } + + /** + * Sets the UserService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param userService is the UserService object + */ + public static void setUserService(final UserService userService) { + MODELER_SESSION_INSTANCE.userService = userService; + } + + public static ActionControlService getActionControlService() { + final ActionControlService actionControlService = MODELER_SESSION_INSTANCE.actionControlService; + + if(actionControlService == null){ + LOG.error("ActionControlService has not been set."); + throw new NullPointerException("ActionControlService is not available."); + } + + return actionControlService; + } + + public static ActionService getActionService() { + final ActionService actionService = MODELER_SESSION_INSTANCE.actionControlService; + + if(actionService == null){ + LOG.error("ActionService has not been set."); + throw new NullPointerException("ActionService is not available."); + } + + return actionService; + } + + /** + * Sets the ActionControlService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param actionControlService is the ActionControlService object + */ + public static void setActionControlService(final ActionControlService actionControlService) { + if(MODELER_SESSION_INSTANCE.actionControlService == null){ + MODELER_SESSION_INSTANCE.actionControlService = actionControlService; + } + } + + /** + * Returns the ProjectControlService object. + * + * @return every-time the same ProjectControlService object + */ + public static ProjectControlService getProjectControlService() { + final ProjectControlService projectControlService = MODELER_SESSION_INSTANCE.projectControlService; + + if(projectControlService == null){ + LOG.error("ProjectControlService has not been set."); + throw new NullPointerException("ProjectControlService is not available."); + } + + return projectControlService; + } + + /** + * Returns the ProjectService object. + * + * @return every-time the same ProjectService object + */ + public static ProjectService getProjectService() { + final ProjectService projectService = MODELER_SESSION_INSTANCE.projectControlService; + + if(projectService == null){ + LOG.error("ProjectService has not been set."); + throw new NullPointerException("ProjectService is not available."); + } + + return projectService; + } + + /** + * Sets the ProjectControlService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param projectControlService is the ProjectControlService object + */ + public static void setProjectControlService(final ProjectControlService projectControlService) { + if(MODELER_SESSION_INSTANCE.projectControlService == null){ + MODELER_SESSION_INSTANCE.projectControlService = projectControlService; + } + } + + /** + * Returns the MenuService object. + * + * @return every-time the same MenuService object + */ + public static MenuService getMenuService() { + final MenuService menuService = MODELER_SESSION_INSTANCE.menuService; + + if(menuService == null){ + LOG.error("MenuService has not been set."); + throw new NullPointerException("MenuService is not available."); + } + + return menuService; + } + + /** + * Sets the MenuService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param menuService is the MenuService object + */ + public static void setMainMenuService(final MenuService menuService) { + if(MODELER_SESSION_INSTANCE.menuService == null){ + MODELER_SESSION_INSTANCE.menuService = menuService; + } + } + + /** + * Returns the NotationService object. + * + * @return every-time the same NotationService object + */ + public static NotationService getNotationService() { + final NotationService notationService = MODELER_SESSION_INSTANCE.notationService; + + if(notationService == null){ + LOG.error("NotationService has not been set."); + throw new NullPointerException("NotationService is not available."); + } + + return notationService; + } + + /** + * Sets the NotationService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param notationService is the NotationService object + */ + public static void setNotationService(final NotationService notationService) { + if(MODELER_SESSION_INSTANCE.notationService == null){ + MODELER_SESSION_INSTANCE.notationService = notationService; + } + } + + /** + * Returns the ToolBarService object. + * + * @return every-time the same ToolBarService object + */ + public static ToolBarService getToolBarService() { + final ToolBarService toolBarService = MODELER_SESSION_INSTANCE.toolBarControlService; + + if(toolBarService == null){ + LOG.error("ToolBarService has not been set."); + throw new NullPointerException("ToolBarService is not available."); + } + + return toolBarService; + } + + /** + * Returns the ToolBarControlService object. + * + * @return every-time the same ToolBarControlService object + */ + public static ToolBarControlService getToolBarControlService() { + final ToolBarControlService toolBarControlService = MODELER_SESSION_INSTANCE.toolBarControlService; + + if(toolBarControlService == null){ + LOG.error("ToolBarControlService has not been set."); + throw new NullPointerException("ToolBarControlService is not available."); + } + + return toolBarControlService; + } + + /** + * Sets the ToolBarControlService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param toolBarService is the ToolBarControlService object + */ + public static void setToolBarControlService(final ToolBarControlService toolBarService) { + if(MODELER_SESSION_INSTANCE.toolBarControlService == null){ + MODELER_SESSION_INSTANCE.toolBarControlService = toolBarService; + } + } + + /** + * Returns the StatusBarControlService object. + * + * @return every-time the same StatusBarControlService object + */ + public static StatusBarControlService getStatusBarControlService() { + final StatusBarControlService statusBarControlService = MODELER_SESSION_INSTANCE.statusBarControlService; + + if(statusBarControlService == null){ + LOG.error("statusBarControlService has not been set."); + throw new NullPointerException("statusBarControlService is not available."); + } + + return statusBarControlService; + } + + /** + * Returns the StatusBarService object. + * + * @return every-time the same StatusBarService object + */ + public static StatusBarService getStatusBarService() { + final StatusBarService statusBarService = MODELER_SESSION_INSTANCE.statusBarControlService; + + if(statusBarService == null){ + LOG.error("statusBarService has not been set."); + throw new NullPointerException("statusBarService is not available."); + } + + return statusBarService; + } + + /** + * Sets the StatusBarControlService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param statusBarControlService is the StatusBarControlService object + */ + public static void setStatusBarControlService(final StatusBarControlService statusBarControlService) { + if(MODELER_SESSION_INSTANCE.statusBarControlService == null){ + MODELER_SESSION_INSTANCE.statusBarControlService = statusBarControlService; + } + } + + /** + * Returns the ExtensionService object. + * + * @return every-time the same ExtensionService object + */ + public static ExtensionService getExtensionService() { + final ExtensionService extensionService = MODELER_SESSION_INSTANCE.extensionsService; + + if(extensionService == null){ + LOG.error("extension service has not been set."); + throw new NullPointerException("extension service is not available."); + } + + return extensionService; + } + + /** + * Sets the ExtensionService object. It can be set only once. All next attempts to set it again will + * have no effect. + * + * @param extensionService is the ExtensionService object + */ + public static void setExtensionService(final ExtensionService extensionService) { + if(MODELER_SESSION_INSTANCE.extensionsService == null){ + MODELER_SESSION_INSTANCE.extensionsService = extensionService; + } + } + + /** + * Private static method to null all services. Used in automatic tests - JUnit tests to null services. + * None is supposed to use this method for non-testing purposes. + * + * Tests use this method through reflection. + */ + private static void nullServices(){ + MODELER_SESSION_INSTANCE.componentFactoryService = null; + MODELER_SESSION_INSTANCE.userService = null; + MODELER_SESSION_INSTANCE.actionControlService = null; + MODELER_SESSION_INSTANCE.projectControlService = null; + MODELER_SESSION_INSTANCE.menuService = null; + MODELER_SESSION_INSTANCE.notationService = null; + MODELER_SESSION_INSTANCE.toolBarControlService = null; + MODELER_SESSION_INSTANCE.statusBarControlService = null; + MODELER_SESSION_INSTANCE.extensionsService = null; + } } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionControlService.java b/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionControlService.java index 98bd1c3..a0caf2a 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionControlService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionControlService.java @@ -1,25 +1,25 @@ -package cz.cvut.promod.services.actionService; - -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 18:59:19, 10.10.2009 - */ - -/** - * ActionControlService is the second service layer for the ActionService. - */ -public interface ActionControlService extends ActionService{ - - /** - * Updates visibility of actions registered with the ActionService. If a action has been registered with the - * notation identifier specified as a argument of this method or with a identifier of ProMod Modeler, such - * a action will be visible. Other actions will be invisible. - * - * @param notationIdentifier is the identifier that is supposed to be active - */ - public void updateActionsVisibility(final String notationIdentifier); - -} +package cz.cvut.promod.services.actionService; + +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 18:59:19, 10.10.2009 + */ + +/** + * ActionControlService is the second service layer for the ActionService. + */ +public interface ActionControlService extends ActionService{ + + /** + * Updates visibility of actions registered with the ActionService. If a action has been registered with the + * notation identifier specified as a argument of this method or with a identifier of ProMod Modeler, such + * a action will be visible. Other actions will be invisible. + * + * @param notationIdentifier is the identifier that is supposed to be active + */ + public void updateActionsVisibility(final String notationIdentifier); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionControlServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionControlServiceImpl.java index 697fe74..e4f5f79 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionControlServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionControlServiceImpl.java @@ -1,194 +1,194 @@ -package cz.cvut.promod.services.actionService; - -import cz.cvut.promod.gui.ModelerModel; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import org.apache.log4j.Logger; - -import javax.swing.*; -import java.util.HashMap; -import java.util.Map; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:48:55, 10.10.2009 - */ - -/** - * ActionControlService implementation. - */ -public class ActionControlServiceImpl implements ActionControlService{ - - private final Logger LOG = Logger.getLogger(ActionControlServiceImpl.class); - - private final Map notationSpecificActionsMap; - - public ActionControlServiceImpl(){ - notationSpecificActionsMap = new HashMap(); - } - - /** {@inheritDoc} */ - public boolean check() { - return true; - } - - /** {@inheritDoc} */ - public ProModAction getAction(final String notationIdentifier, - final String moduleIdentifier, - final String actionIdentifier){ - - if(notationIdentifier == null || actionIdentifier == null){ - return null; - } - - if(notationSpecificActionsMap.containsKey(notationIdentifier)){ - final NotationSpecificActions notationSpecificActions = notationSpecificActionsMap.get(notationIdentifier); - - if(moduleIdentifier == null){ - return notationSpecificActions.getAction(actionIdentifier); - } else { - return notationSpecificActions.getAction(moduleIdentifier, actionIdentifier); - } - } - - return null; - } - - public ProModAction getAction(final String notationIdentifier, final String actionIdentifier) { - return getAction(notationIdentifier, null, actionIdentifier); - } - - /** {@inheritDoc} */ - public ProModAction registerAction(final String notationIdentifier, - final String moduleIdentifier, - final String actionIdentifier, - final ProModAction action){ - - if(notationIdentifier == null || actionIdentifier == null){ - LOG.error("Action registration failed due to nullary info," + - " actionIdentifier: " + actionIdentifier + - ", notationIdentifier: " + notationIdentifier + - ", moduleIdentifier: " + moduleIdentifier + "."); - - return null; - } - - final ProModAction proModAction = getAction(notationIdentifier, moduleIdentifier, actionIdentifier); - - if(proModAction != null){ - return proModAction; - - } else { - if(action == null){ - LOG.error("Nullary action is not possible to register."); - return null; - } - - if(!isUniqueKeyAccelerator(notationIdentifier, (KeyStroke) action.getValue(AbstractAction.ACCELERATOR_KEY))){ - LOG.error("Duplicity in action's 'ACCELERATOR KEY'," + - " action: " + actionIdentifier + - " notation: " + notationIdentifier + - " module: " + moduleIdentifier); - action.putValue(AbstractAction.ACCELERATOR_KEY, null); - } - - action.initAction( - notationIdentifier, - moduleIdentifier, - actionIdentifier); - - setAction(notationIdentifier, moduleIdentifier, actionIdentifier, action); - - LOG.debug("New Action (" + actionIdentifier + ") has been added."); - - return action; - } - } - - /** - * Tests whether there is no other already registered action with the same accelerator key definition. This - * test is done only by the 'modeler' action and actions of the same notation. - * - * @param notationIdentifier is the notation where to perform the test - * @param keyStroke is the accelerator key to be tested @return true if there is no such a action, false otherwise - * @return true if the accelerator key is unique, false otherwise - */ - private boolean isUniqueKeyAccelerator(final String notationIdentifier, final KeyStroke keyStroke) { - - NotationSpecificActions notationSpecificActions = notationSpecificActionsMap.get(notationIdentifier); - if(notationSpecificActions != null){ - if(notationSpecificActions.existAcceleratorKey(keyStroke)){ - return false; - } - } - - notationSpecificActions = notationSpecificActionsMap.get(ModelerModel.MODELER_IDENTIFIER); - if(notationSpecificActions != null){ - if(notationSpecificActions.existAcceleratorKey(keyStroke)){ - return false; - } - } - - - return true; - } - - /** - * {@inheritDoc} - */ - public ProModAction registerAction(final String notationIdentifier, - final String actionIdentifier, - final ProModAction action) { - - return registerAction( - notationIdentifier, - null, - actionIdentifier, - action - ); - } - - /** - * Sets the action. - * - * @param notationIdentifier is the notation identifier - * @param moduleIdentifier os the module identifier - * @param actionIdentifier is the action identifier - * @param newProModAction is the action - */ - private void setAction(final String notationIdentifier, - final String moduleIdentifier, - final String actionIdentifier, - final ProModAction newProModAction){ - if(notationIdentifier == null || actionIdentifier == null){ - return; - } - - if(notationSpecificActionsMap.containsKey(notationIdentifier)){ - notationSpecificActionsMap.get(notationIdentifier).setAction(moduleIdentifier, actionIdentifier, newProModAction); - } else { - final NotationSpecificActions notationSpecificActions = new NotationSpecificActions(); - notationSpecificActions.setAction(moduleIdentifier, actionIdentifier, newProModAction); - notationSpecificActionsMap.put(notationIdentifier, notationSpecificActions); - } - } - - - /** {@inheritDoc} */ - public void updateActionsVisibility(final String newNotationIdentifier) { - for(final NotationSpecificActions notationSpecificActions : notationSpecificActionsMap.values()){ - notationSpecificActions.updateActionVisibility(newNotationIdentifier); - } - } - - /** {@inheritDoc} */ - public boolean isRegisteredAction(final ProModAction action) { - for(final NotationSpecificActions notationSpecificActions : notationSpecificActionsMap.values()){ - if(notationSpecificActions.existAction(action)){ - return true; - } - } - - return false; - } -} +package cz.cvut.promod.services.actionService; + +import cz.cvut.promod.gui.ModelerModel; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import org.apache.log4j.Logger; + +import javax.swing.*; +import java.util.HashMap; +import java.util.Map; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:48:55, 10.10.2009 + */ + +/** + * ActionControlService implementation. + */ +public class ActionControlServiceImpl implements ActionControlService{ + + private final Logger LOG = Logger.getLogger(ActionControlServiceImpl.class); + + private final Map notationSpecificActionsMap; + + public ActionControlServiceImpl(){ + notationSpecificActionsMap = new HashMap(); + } + + /** {@inheritDoc} */ + public boolean check() { + return true; + } + + /** {@inheritDoc} */ + public ProModAction getAction(final String notationIdentifier, + final String moduleIdentifier, + final String actionIdentifier){ + + if(notationIdentifier == null || actionIdentifier == null){ + return null; + } + + if(notationSpecificActionsMap.containsKey(notationIdentifier)){ + final NotationSpecificActions notationSpecificActions = notationSpecificActionsMap.get(notationIdentifier); + + if(moduleIdentifier == null){ + return notationSpecificActions.getAction(actionIdentifier); + } else { + return notationSpecificActions.getAction(moduleIdentifier, actionIdentifier); + } + } + + return null; + } + + public ProModAction getAction(final String notationIdentifier, final String actionIdentifier) { + return getAction(notationIdentifier, null, actionIdentifier); + } + + /** {@inheritDoc} */ + public ProModAction registerAction(final String notationIdentifier, + final String moduleIdentifier, + final String actionIdentifier, + final ProModAction action){ + + if(notationIdentifier == null || actionIdentifier == null){ + LOG.error("Action registration failed due to nullary info," + + " actionIdentifier: " + actionIdentifier + + ", notationIdentifier: " + notationIdentifier + + ", moduleIdentifier: " + moduleIdentifier + "."); + + return null; + } + + final ProModAction proModAction = getAction(notationIdentifier, moduleIdentifier, actionIdentifier); + + if(proModAction != null){ + return proModAction; + + } else { + if(action == null){ + LOG.error("Nullary action is not possible to register."); + return null; + } + + if(!isUniqueKeyAccelerator(notationIdentifier, (KeyStroke) action.getValue(AbstractAction.ACCELERATOR_KEY))){ + LOG.error("Duplicity in action's 'ACCELERATOR KEY'," + + " action: " + actionIdentifier + + " notation: " + notationIdentifier + + " module: " + moduleIdentifier); + action.putValue(AbstractAction.ACCELERATOR_KEY, null); + } + + action.initAction( + notationIdentifier, + moduleIdentifier, + actionIdentifier); + + setAction(notationIdentifier, moduleIdentifier, actionIdentifier, action); + + LOG.debug("New Action (" + actionIdentifier + ") has been added."); + + return action; + } + } + + /** + * Tests whether there is no other already registered action with the same accelerator key definition. This + * test is done only by the 'modeler' action and actions of the same notation. + * + * @param notationIdentifier is the notation where to perform the test + * @param keyStroke is the accelerator key to be tested @return true if there is no such a action, false otherwise + * @return true if the accelerator key is unique, false otherwise + */ + private boolean isUniqueKeyAccelerator(final String notationIdentifier, final KeyStroke keyStroke) { + + NotationSpecificActions notationSpecificActions = notationSpecificActionsMap.get(notationIdentifier); + if(notationSpecificActions != null){ + if(notationSpecificActions.existAcceleratorKey(keyStroke)){ + return false; + } + } + + notationSpecificActions = notationSpecificActionsMap.get(ModelerModel.MODELER_IDENTIFIER); + if(notationSpecificActions != null){ + if(notationSpecificActions.existAcceleratorKey(keyStroke)){ + return false; + } + } + + + return true; + } + + /** + * {@inheritDoc} + */ + public ProModAction registerAction(final String notationIdentifier, + final String actionIdentifier, + final ProModAction action) { + + return registerAction( + notationIdentifier, + null, + actionIdentifier, + action + ); + } + + /** + * Sets the action. + * + * @param notationIdentifier is the notation identifier + * @param moduleIdentifier os the module identifier + * @param actionIdentifier is the action identifier + * @param newProModAction is the action + */ + private void setAction(final String notationIdentifier, + final String moduleIdentifier, + final String actionIdentifier, + final ProModAction newProModAction){ + if(notationIdentifier == null || actionIdentifier == null){ + return; + } + + if(notationSpecificActionsMap.containsKey(notationIdentifier)){ + notationSpecificActionsMap.get(notationIdentifier).setAction(moduleIdentifier, actionIdentifier, newProModAction); + } else { + final NotationSpecificActions notationSpecificActions = new NotationSpecificActions(); + notationSpecificActions.setAction(moduleIdentifier, actionIdentifier, newProModAction); + notationSpecificActionsMap.put(notationIdentifier, notationSpecificActions); + } + } + + + /** {@inheritDoc} */ + public void updateActionsVisibility(final String newNotationIdentifier) { + for(final NotationSpecificActions notationSpecificActions : notationSpecificActionsMap.values()){ + notationSpecificActions.updateActionVisibility(newNotationIdentifier); + } + } + + /** {@inheritDoc} */ + public boolean isRegisteredAction(final ProModAction action) { + for(final NotationSpecificActions notationSpecificActions : notationSpecificActionsMap.values()){ + if(notationSpecificActions.existAction(action)){ + return true; + } + } + + return false; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionService.java b/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionService.java index 5c07f69..38ae3c3 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/actionService/ActionService.java @@ -1,103 +1,103 @@ -package cz.cvut.promod.services.actionService; - -import cz.cvut.promod.services.Service; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:44:48, 10.10.2009 - */ - -/** - * ActionService interface is a base point for ProModAction handling. One is supposed to use methods defined in this - * interface for registering and obtaining actions. - * - * Using ModelerSession.getActionService() is possible to get proper implementation of this interface ready for use. - * - * All instances of ProModAction class (this class is defined as abstract, so all class that extend ProMod class and - * implement method actionPerformed(ActionEvent event)) are initially defined as disabled. This forces user to use this - * mechanism for action registration. But on the other hand, this is not very strong protection, so be careful with - * dealing with not registered actions. - */ -public interface ActionService extends Service { - - /** - * Register a new ProModAction. - * - * @param notationIdentifier is a identifier of notation to that the action belongs - * @param moduleIdentifier is a identifier of module to that the action belongs - * @param actionIdentifier is the action identifier - * @param action is an instance of any class that extends ProModAction - * - * @return the reference to the action (so the same as in the action parameter), or a reference to the action - * that has the same actionIdentifier, notationIdentifier and moduleIdentifier and that has been registered before. - * - * One can use for example: - * MyProModAction myAction = new MyProModAction(); - * ProModAction action = ModelerSession.getActionService().registerAction(...); - * - * if(myAction == action){ //my action has been registered } - * else {// my action was not registered because of action duplicity } - */ - public ProModAction registerAction(final String notationIdentifier, - final String moduleIdentifier, - final String actionIdentifier, - final ProModAction action - ); - - - /** - * Register a new ProModAction. Just syntactical sugar supplement of the more complex method. - * - * @param notationIdentifier is a identifier of notation to that the action belongs - * @param actionIdentifier is the action identifier - * @param action is the action identifier - * @return the reference to the action (so the same as in the action parameter), or a reference to the action - * that has the same actionIdentifier, notationIdentifier and moduleIdentifier and that has been registered before. - */ - public ProModAction registerAction(final String notationIdentifier, - final String actionIdentifier, - final ProModAction action - ); - - - /** - * Finds a returns an instance of ProModAction that has been registered by the ActionService with - * the given notation identifier, given module identifier and given action identifier. - * - * @param notationIdentifier is the identifier of notation under that has been the action registered - * @param moduleIdentifier is the identifier of module under that has been the action registered - * @param actionIdentifier is the identifier of action - * - * @return the instance of action if such a action has been successfully registered, null otherwise - */ - public ProModAction getAction(final String notationIdentifier, - final String moduleIdentifier, - final String actionIdentifier - ); - - - /** - * Finds a returns an instance of ProModAction that has been registered by the ActionService with - * the given notation identifier and given action identifier. - * - * @param notationIdentifier is the identifier of notation under that has been the action registered - * @param actionIdentifier is the identifier of action - * - * @return the instance of action if such a action has been successfully registered, null otherwise - */ - public ProModAction getAction(final String notationIdentifier, - final String actionIdentifier - ); - - /** - * Checks whether the action given as a parameter is any already registered action by any plugin or - * modeler itself. - * - * @param action is the action to be checked - * @return true if the actions has already been registered, false otherwise - */ - public boolean isRegisteredAction(final ProModAction action); - -} +package cz.cvut.promod.services.actionService; + +import cz.cvut.promod.services.Service; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:44:48, 10.10.2009 + */ + +/** + * ActionService interface is a base point for ProModAction handling. One is supposed to use methods defined in this + * interface for registering and obtaining actions. + * + * Using ModelerSession.getActionService() is possible to get proper implementation of this interface ready for use. + * + * All instances of ProModAction class (this class is defined as abstract, so all class that extend ProMod class and + * implement method actionPerformed(ActionEvent event)) are initially defined as disabled. This forces user to use this + * mechanism for action registration. But on the other hand, this is not very strong protection, so be careful with + * dealing with not registered actions. + */ +public interface ActionService extends Service { + + /** + * Register a new ProModAction. + * + * @param notationIdentifier is a identifier of notation to that the action belongs + * @param moduleIdentifier is a identifier of module to that the action belongs + * @param actionIdentifier is the action identifier + * @param action is an instance of any class that extends ProModAction + * + * @return the reference to the action (so the same as in the action parameter), or a reference to the action + * that has the same actionIdentifier, notationIdentifier and moduleIdentifier and that has been registered before. + * + * One can use for example: + * MyProModAction myAction = new MyProModAction(); + * ProModAction action = ModelerSession.getActionService().registerAction(...); + * + * if(myAction == action){ //my action has been registered } + * else {// my action was not registered because of action duplicity } + */ + public ProModAction registerAction(final String notationIdentifier, + final String moduleIdentifier, + final String actionIdentifier, + final ProModAction action + ); + + + /** + * Register a new ProModAction. Just syntactical sugar supplement of the more complex method. + * + * @param notationIdentifier is a identifier of notation to that the action belongs + * @param actionIdentifier is the action identifier + * @param action is the action identifier + * @return the reference to the action (so the same as in the action parameter), or a reference to the action + * that has the same actionIdentifier, notationIdentifier and moduleIdentifier and that has been registered before. + */ + public ProModAction registerAction(final String notationIdentifier, + final String actionIdentifier, + final ProModAction action + ); + + + /** + * Finds a returns an instance of ProModAction that has been registered by the ActionService with + * the given notation identifier, given module identifier and given action identifier. + * + * @param notationIdentifier is the identifier of notation under that has been the action registered + * @param moduleIdentifier is the identifier of module under that has been the action registered + * @param actionIdentifier is the identifier of action + * + * @return the instance of action if such a action has been successfully registered, null otherwise + */ + public ProModAction getAction(final String notationIdentifier, + final String moduleIdentifier, + final String actionIdentifier + ); + + + /** + * Finds a returns an instance of ProModAction that has been registered by the ActionService with + * the given notation identifier and given action identifier. + * + * @param notationIdentifier is the identifier of notation under that has been the action registered + * @param actionIdentifier is the identifier of action + * + * @return the instance of action if such a action has been successfully registered, null otherwise + */ + public ProModAction getAction(final String notationIdentifier, + final String actionIdentifier + ); + + /** + * Checks whether the action given as a parameter is any already registered action by any plugin or + * modeler itself. + * + * @param action is the action to be checked + * @return true if the actions has already been registered, false otherwise + */ + public boolean isRegisteredAction(final ProModAction action); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/actionService/ModuleSpecificActions.java b/IndependentModeler/src/cz/cvut/promod/services/actionService/ModuleSpecificActions.java index f54598f..04851d0 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/actionService/ModuleSpecificActions.java +++ b/IndependentModeler/src/cz/cvut/promod/services/actionService/ModuleSpecificActions.java @@ -1,82 +1,82 @@ -package cz.cvut.promod.services.actionService; - -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import org.apache.log4j.Logger; - -import javax.swing.*; -import java.util.HashMap; -import java.util.Map; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:23:05, 2.11.2009 - */ - -/** - * Module specific actions holder. - */ -public class ModuleSpecificActions { - - private final Logger LOG = Logger.getLogger(ModuleSpecificActions.class); - - private final Map moduleActionsMap; - - public ModuleSpecificActions(){ - moduleActionsMap = new HashMap(); - } - - /** - * @param actionIdentifier is the action identifier - * @return returns modules required action - */ - public ProModAction getAction(final String actionIdentifier) { - if(moduleActionsMap.containsKey(actionIdentifier)){ - return moduleActionsMap.get(actionIdentifier); - } - - return null; - } - - public void setAction(final String actionIdentifier, final ProModAction newProModAction) { - if(moduleActionsMap.containsKey(actionIdentifier)){ - LOG.error("An attempt to insert the same notation action to the notation actions map, action identifier: " + actionIdentifier + "."); - } else { - moduleActionsMap.put(actionIdentifier, newProModAction); - } - } - - public void updateActionVisibility(final String notationIdentifier) { - for(final ProModAction proModAction : moduleActionsMap.values()){ - proModAction.updateActionVisibility(notationIdentifier); - } - } - - /** - * Tests whether there is no other already registered action with the same accelerator key definition - * by this module. - * - * @param keyStroke is the accelerator key to be tested - * @return true if there is such a action, false otherwise - */ - public boolean existAcceleratorKey(final KeyStroke keyStroke) { - for(final ProModAction action : moduleActionsMap.values()){ - final KeyStroke key = (KeyStroke) action.getValue(AbstractAction.ACCELERATOR_KEY); - if(key != null && key.equals(keyStroke)){ - return true; - } - } - - return false; - } - - /** - * Checks whether there has been registered such a action earlier. - * - * @param action is the action to be checked - * @return true if such a action has been already registered, false otherwise - */ - public boolean exist(final ProModAction action) { - return moduleActionsMap.values().contains(action); - } -} +package cz.cvut.promod.services.actionService; + +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import org.apache.log4j.Logger; + +import javax.swing.*; +import java.util.HashMap; +import java.util.Map; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:23:05, 2.11.2009 + */ + +/** + * Module specific actions holder. + */ +public class ModuleSpecificActions { + + private final Logger LOG = Logger.getLogger(ModuleSpecificActions.class); + + private final Map moduleActionsMap; + + public ModuleSpecificActions(){ + moduleActionsMap = new HashMap(); + } + + /** + * @param actionIdentifier is the action identifier + * @return returns modules required action + */ + public ProModAction getAction(final String actionIdentifier) { + if(moduleActionsMap.containsKey(actionIdentifier)){ + return moduleActionsMap.get(actionIdentifier); + } + + return null; + } + + public void setAction(final String actionIdentifier, final ProModAction newProModAction) { + if(moduleActionsMap.containsKey(actionIdentifier)){ + LOG.error("An attempt to insert the same notation action to the notation actions map, action identifier: " + actionIdentifier + "."); + } else { + moduleActionsMap.put(actionIdentifier, newProModAction); + } + } + + public void updateActionVisibility(final String notationIdentifier) { + for(final ProModAction proModAction : moduleActionsMap.values()){ + proModAction.updateActionVisibility(notationIdentifier); + } + } + + /** + * Tests whether there is no other already registered action with the same accelerator key definition + * by this module. + * + * @param keyStroke is the accelerator key to be tested + * @return true if there is such a action, false otherwise + */ + public boolean existAcceleratorKey(final KeyStroke keyStroke) { + for(final ProModAction action : moduleActionsMap.values()){ + final KeyStroke key = (KeyStroke) action.getValue(AbstractAction.ACCELERATOR_KEY); + if(key != null && key.equals(keyStroke)){ + return true; + } + } + + return false; + } + + /** + * Checks whether there has been registered such a action earlier. + * + * @param action is the action to be checked + * @return true if such a action has been already registered, false otherwise + */ + public boolean exist(final ProModAction action) { + return moduleActionsMap.values().contains(action); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/actionService/NotationSpecificActions.java b/IndependentModeler/src/cz/cvut/promod/services/actionService/NotationSpecificActions.java index 4692e9e..36e0395 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/actionService/NotationSpecificActions.java +++ b/IndependentModeler/src/cz/cvut/promod/services/actionService/NotationSpecificActions.java @@ -1,141 +1,141 @@ -package cz.cvut.promod.services.actionService; - -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import org.apache.log4j.Logger; - -import javax.swing.*; -import java.util.HashMap; -import java.util.Map; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:19:25, 2.11.2009 - */ - -/** - * Notation specific actions holder. - */ -public class NotationSpecificActions { - - private final Logger LOG = Logger.getLogger(NotationSpecificActions.class); - - private final Map notationActionsMap; - - private final Map moduleActionsMap; - - - public NotationSpecificActions(){ - notationActionsMap = new HashMap(); - moduleActionsMap = new HashMap(); - } - - /** - * @param actionIdentifier is the action identifier - * @return returns the action is such a action exists, null otherwise - */ - public ProModAction getAction(final String actionIdentifier) { - if(notationActionsMap.containsKey(actionIdentifier)){ - return notationActionsMap.get(actionIdentifier); - } - - return null; - } - - /** - * @param moduleIdentifier is the module identifier - * @param actionIdentifier is the action identifier - * @return returns the action is such a action exists, null otherwise - */ - public ProModAction getAction(final String moduleIdentifier, final String actionIdentifier) { - if(moduleActionsMap.containsKey(moduleIdentifier)){ - return moduleActionsMap.get(moduleIdentifier).getAction(actionIdentifier); - } - - return null; - } - - /** - * Sets the action. - * @param moduleIdentifier module identifier - * @param actionIdentifier action identifier - * @param newProModAction the action itself - */ - public void setAction(final String moduleIdentifier, final String actionIdentifier, final ProModAction newProModAction) { - if(moduleIdentifier == null){ - if(notationActionsMap.containsKey(actionIdentifier)){ - LOG.error("An attempt to insert the same notation action to the notation actions map, action identifier: " + actionIdentifier + "."); - } else { - notationActionsMap.put(actionIdentifier, newProModAction); - } - - } else { - if(moduleActionsMap.containsKey(moduleIdentifier)){ - moduleActionsMap.get(moduleIdentifier).setAction(actionIdentifier, newProModAction); - } else { - final ModuleSpecificActions moduleSpecificActions = new ModuleSpecificActions(); - moduleSpecificActions.setAction(actionIdentifier, newProModAction); - moduleActionsMap.put(moduleIdentifier, moduleSpecificActions); - } - } - } - - /** - * Updates the action visibility on the basis of active notation. - * @param notationIdentifier is the identifier of active notation. - */ - public void updateActionVisibility(final String notationIdentifier) { - for(final ProModAction proModAction : notationActionsMap.values()){ - proModAction.updateActionVisibility(notationIdentifier); - } - - for(final ModuleSpecificActions moduleSpecificActions : moduleActionsMap.values()){ - moduleSpecificActions.updateActionVisibility(notationIdentifier); - } - } - - /** - * Tests whether there is no other already registered action with the same accelerator key definition - * by this notation. Additionally, check all registered actions of this notation's modules. - * - * @param keyStroke is the accelerator key to be tested - * @return true if there is such a action, false otherwise - */ - public boolean existAcceleratorKey(final KeyStroke keyStroke){ - for(final ProModAction action : notationActionsMap.values()){ - final KeyStroke key = (KeyStroke) action.getValue(AbstractAction.ACCELERATOR_KEY); - - if(key != null && key.equals(keyStroke)){ - return true; - } - } - - for(final ModuleSpecificActions moduleSpecificActions : moduleActionsMap.values()){ - if(moduleSpecificActions.existAcceleratorKey(keyStroke)){ - return true; - } - } - - return false; - } - - /** - * Check whether such a action has been already registered by a notation or any of it's modules. - * - * @param action is the action to be checked - * @return true if such a actions has been already registered, false otherwise - */ - public boolean existAction(final ProModAction action) { - if(notationActionsMap.values().contains(action)){ - return true; - } - - for(final ModuleSpecificActions moduleSpecificActions : moduleActionsMap.values()){ - if(moduleSpecificActions.exist(action)){ - return true; - } - } - - return false; - } -} +package cz.cvut.promod.services.actionService; + +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import org.apache.log4j.Logger; + +import javax.swing.*; +import java.util.HashMap; +import java.util.Map; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:19:25, 2.11.2009 + */ + +/** + * Notation specific actions holder. + */ +public class NotationSpecificActions { + + private final Logger LOG = Logger.getLogger(NotationSpecificActions.class); + + private final Map notationActionsMap; + + private final Map moduleActionsMap; + + + public NotationSpecificActions(){ + notationActionsMap = new HashMap(); + moduleActionsMap = new HashMap(); + } + + /** + * @param actionIdentifier is the action identifier + * @return returns the action is such a action exists, null otherwise + */ + public ProModAction getAction(final String actionIdentifier) { + if(notationActionsMap.containsKey(actionIdentifier)){ + return notationActionsMap.get(actionIdentifier); + } + + return null; + } + + /** + * @param moduleIdentifier is the module identifier + * @param actionIdentifier is the action identifier + * @return returns the action is such a action exists, null otherwise + */ + public ProModAction getAction(final String moduleIdentifier, final String actionIdentifier) { + if(moduleActionsMap.containsKey(moduleIdentifier)){ + return moduleActionsMap.get(moduleIdentifier).getAction(actionIdentifier); + } + + return null; + } + + /** + * Sets the action. + * @param moduleIdentifier module identifier + * @param actionIdentifier action identifier + * @param newProModAction the action itself + */ + public void setAction(final String moduleIdentifier, final String actionIdentifier, final ProModAction newProModAction) { + if(moduleIdentifier == null){ + if(notationActionsMap.containsKey(actionIdentifier)){ + LOG.error("An attempt to insert the same notation action to the notation actions map, action identifier: " + actionIdentifier + "."); + } else { + notationActionsMap.put(actionIdentifier, newProModAction); + } + + } else { + if(moduleActionsMap.containsKey(moduleIdentifier)){ + moduleActionsMap.get(moduleIdentifier).setAction(actionIdentifier, newProModAction); + } else { + final ModuleSpecificActions moduleSpecificActions = new ModuleSpecificActions(); + moduleSpecificActions.setAction(actionIdentifier, newProModAction); + moduleActionsMap.put(moduleIdentifier, moduleSpecificActions); + } + } + } + + /** + * Updates the action visibility on the basis of active notation. + * @param notationIdentifier is the identifier of active notation. + */ + public void updateActionVisibility(final String notationIdentifier) { + for(final ProModAction proModAction : notationActionsMap.values()){ + proModAction.updateActionVisibility(notationIdentifier); + } + + for(final ModuleSpecificActions moduleSpecificActions : moduleActionsMap.values()){ + moduleSpecificActions.updateActionVisibility(notationIdentifier); + } + } + + /** + * Tests whether there is no other already registered action with the same accelerator key definition + * by this notation. Additionally, check all registered actions of this notation's modules. + * + * @param keyStroke is the accelerator key to be tested + * @return true if there is such a action, false otherwise + */ + public boolean existAcceleratorKey(final KeyStroke keyStroke){ + for(final ProModAction action : notationActionsMap.values()){ + final KeyStroke key = (KeyStroke) action.getValue(AbstractAction.ACCELERATOR_KEY); + + if(key != null && key.equals(keyStroke)){ + return true; + } + } + + for(final ModuleSpecificActions moduleSpecificActions : moduleActionsMap.values()){ + if(moduleSpecificActions.existAcceleratorKey(keyStroke)){ + return true; + } + } + + return false; + } + + /** + * Check whether such a action has been already registered by a notation or any of it's modules. + * + * @param action is the action to be checked + * @return true if such a actions has been already registered, false otherwise + */ + public boolean existAction(final ProModAction action) { + if(notationActionsMap.values().contains(action)){ + return true; + } + + for(final ModuleSpecificActions moduleSpecificActions : moduleActionsMap.values()){ + if(moduleSpecificActions.exist(action)){ + return true; + } + } + + return false; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/actionService/actionUtils/ProModAction.java b/IndependentModeler/src/cz/cvut/promod/services/actionService/actionUtils/ProModAction.java index 0d677d2..5fe1109 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/actionService/actionUtils/ProModAction.java +++ b/IndependentModeler/src/cz/cvut/promod/services/actionService/actionUtils/ProModAction.java @@ -1,102 +1,102 @@ -package cz.cvut.promod.services.actionService.actionUtils; - -import cz.cvut.promod.gui.ModelerModel; - -import javax.swing.*; -import java.awt.event.ActionEvent; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:51:16, 13.10.2009 - */ - -/** - * Represents basic ProMod action. This kind of actions is supposed to be - * used with the ActionService. - * - * @see cz.cvut.promod.services.actionService.ActionService - */ -public abstract class ProModAction extends AbstractAction{ - - private String actionIdentifier = null; - - private String notationIdentifier = null; - - private String moduleIdentifier = null; - - public ProModAction(final String displayName, - final Icon icon, - final KeyStroke keyStroke){ - - super(displayName, icon); - - putValue(ACCELERATOR_KEY, keyStroke); - - /** - * All instances of ProModAction class are initially disabled. Action is enabled when the - * notation identifier is set during action registration by ActionService. Only ActionService is supposed - * to use initAction method. - * - * For example, if anyone don't register action using ActionService and only inserts this action to the menu, - * then visibility of this action is never updated. - * @see cz.cvut.promod.gui.ModelerModel an it's update method - * That's way this action is initially disabled. - */ - setEnabled(false); - } - - public void updateActionVisibility(final String notationIdentifier){ - if(ModelerModel.MODELER_IDENTIFIER.equals(this.notationIdentifier)){ - return; - } - - if(this.notationIdentifier.equals(notationIdentifier)){ - setEnabled(true); - } else { - setEnabled(false); - } - } - - /** - * Once the notation identifier has been set, no one can change it. This method should NEVER EVER be used - * by the programmer. Only ActionService uses this method to initialize this service. - * - * @param notationIdentifier required notation identifier - * @param moduleIdentifier is the identifier of a module - * @param actionIdentifier is the identifier of a action - * - * @return true if notation identifier has been set, false otherwise - */ - public boolean initAction(final String notationIdentifier, - final String moduleIdentifier, - final String actionIdentifier){ - - if(this.notationIdentifier == null && this.moduleIdentifier == null && this.actionIdentifier == null){ - this.notationIdentifier = notationIdentifier; - this.moduleIdentifier = moduleIdentifier; - this.actionIdentifier = actionIdentifier; - - setEnabled(true); - - return true; - } - - return false; - } - - - public String getActionIdentifier() { - return actionIdentifier; - } - - public String getNotationIdentifier() { - return notationIdentifier; - } - - public String getModuleIdentifier() { - return moduleIdentifier; - } - - public abstract void actionPerformed(ActionEvent event); -} +package cz.cvut.promod.services.actionService.actionUtils; + +import cz.cvut.promod.gui.ModelerModel; + +import javax.swing.*; +import java.awt.event.ActionEvent; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:51:16, 13.10.2009 + */ + +/** + * Represents basic ProMod action. This kind of actions is supposed to be + * used with the ActionService. + * + * @see cz.cvut.promod.services.actionService.ActionService + */ +public abstract class ProModAction extends AbstractAction{ + + private String actionIdentifier = null; + + private String notationIdentifier = null; + + private String moduleIdentifier = null; + + public ProModAction(final String displayName, + final Icon icon, + final KeyStroke keyStroke){ + + super(displayName, icon); + + putValue(ACCELERATOR_KEY, keyStroke); + + /** + * All instances of ProModAction class are initially disabled. Action is enabled when the + * notation identifier is set during action registration by ActionService. Only ActionService is supposed + * to use initAction method. + * + * For example, if anyone don't register action using ActionService and only inserts this action to the menu, + * then visibility of this action is never updated. + * @see cz.cvut.promod.gui.ModelerModel an it's update method + * That's way this action is initially disabled. + */ + setEnabled(false); + } + + public void updateActionVisibility(final String notationIdentifier){ + if(ModelerModel.MODELER_IDENTIFIER.equals(this.notationIdentifier)){ + return; + } + + if(this.notationIdentifier.equals(notationIdentifier)){ + setEnabled(true); + } else { + setEnabled(false); + } + } + + /** + * Once the notation identifier has been set, no one can change it. This method should NEVER EVER be used + * by the programmer. Only ActionService uses this method to initialize this service. + * + * @param notationIdentifier required notation identifier + * @param moduleIdentifier is the identifier of a module + * @param actionIdentifier is the identifier of a action + * + * @return true if notation identifier has been set, false otherwise + */ + public boolean initAction(final String notationIdentifier, + final String moduleIdentifier, + final String actionIdentifier){ + + if(this.notationIdentifier == null && this.moduleIdentifier == null && this.actionIdentifier == null){ + this.notationIdentifier = notationIdentifier; + this.moduleIdentifier = moduleIdentifier; + this.actionIdentifier = actionIdentifier; + + setEnabled(true); + + return true; + } + + return false; + } + + + public String getActionIdentifier() { + return actionIdentifier; + } + + public String getNotationIdentifier() { + return notationIdentifier; + } + + public String getModuleIdentifier() { + return moduleIdentifier; + } + + public abstract void actionPerformed(ActionEvent event); +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/componentFactoryService/ComponentFactoryService.java b/IndependentModeler/src/cz/cvut/promod/services/componentFactoryService/ComponentFactoryService.java index e036a31..76f56e2 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/componentFactoryService/ComponentFactoryService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/componentFactoryService/ComponentFactoryService.java @@ -1,213 +1,213 @@ -package cz.cvut.promod.services.componentFactoryService; - -import com.jidesoft.swing.JideButton; -import com.jidesoft.grid.PropertyTable; -import com.jidesoft.status.StatusBar; -import com.jidesoft.status.LabelStatusBarItem; -import com.jidesoft.status.ButtonStatusBarItem; -import com.jidesoft.pane.OutlookTabbedPane; - -import javax.swing.*; -import javax.swing.tree.TreeNode; -import java.awt.*; - -import cz.cvut.promod.services.Service; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 21:13:35, 5.1.2010 - */ - -/** - * All Plugins and even the Modeler are supposed to use ComponentFactoryClass for creation of GUI components - * (including Swing components and JideSoft components). - * - * This programming style should ensure some kind of visual consistency in ProMod application. - */ -public interface ComponentFactoryService extends Service { - - /** - * Defines the recommended form border. Usually for usage in JGoodies.Borders factory. - * @see com.jgoodies.forms.factories.Borders - */ - public static final String DEFAULT_FORM_BORDER = "5dlu, 5dlu, 5dlu, 5dlu"; - - - /** Defines horizontal orientation of an instance of JideButton class */ - public static final int JIDE_BUTTON_HORIZONTAL_ORIENTATION = 0; - - /** Defines vertical orientation of an instance of JideButton class */ - public static final int JIDE_BUTTON_VERTICAL_ORIENTATION = 1; - - /** - * @return an instance of JComboBox class - */ - public JComboBox createComboBox(); - - /** - * @return an instance of JSpinner class - */ - public JSpinner createSpinner(); - - /** - * @return an instance of JTextArea class - */ - public JTextArea createTextArea(); - - /** - * @return an instance of JTextField class - */ - public JTextField createTextField(); - - /** - * @param text to be displayed in the JTextField - * @return an instance of JTextField class - */ - public JTextField createTextField(final String text); - - - /** - * @return an instance of JSlider class - */ - public JSlider createSlider(); - - /** - * @param text is a text to be displayed on the Label - * @return an instance of Label class - */ - public JLabel createLabel(final String text); - - /** - * @return an instance of JTree class - */ - public JTree createTree(); - - /** - * @return an instance of JTree class - */ - public JTree createTree(final TreeNode node); - - /** - * @param component is a component to be inserted to the ScrollPane - * @return an instance of ScrollPane class - */ - public JScrollPane createScrollPane(final Component component); - - /** - * @return an instance of JCheckBox class - */ - public JCheckBox createCheckBox(); - - /** - * @return an instance of MenuBar class - */ - public JMenuBar createMenuBar(); - - /** - * @return an instance of JToolBar class - */ - public JToolBar createToolBar(); - - /** - * @param text is a text to be displayed on the Menu - * @return an instance of Menu class - */ - public JMenu createMenu(final String text); - - /** - * @return an instance of JPopupMenu class - */ - public JPopupMenu createPopupMenu(); - - /** - * @return an instance of OutlookTabbedPane class. - */ - public OutlookTabbedPane createOutlookTabbedPane(); - - /** - * @param text is a text to be displayed on the MenuItem - * @return an instance of MenuItem class - */ - public JMenuItem createMenuItem(final String text); - - /** - * @param text is a text to be displayed on the Button - * @param icon is a icon to be displayed on the Button - * @return an instance of Button class - */ - public JButton createButton(final String text, final Icon icon); - - /** - * @param text is a text to be displayed on the ToggleButton - * @param icon is a icon to be displayed on the ToggleButton - * @return an instance of ToggleButton class - */ - public JToggleButton createToggleButton(final String text, final Icon icon); - - /** - * - * @param text is a text to be displayed on the button - * @param icon is an icon to be displayed on the button - * @param orientation JIDE_BUTTON_HORIZONTAL_ORIENTATION or JIDE_BUTTON_VERTICAL_ORIENTATION - * @return an instance of JideButton class - */ - public JideButton createJideButton( final String text, final Icon icon, int orientation ); - - /** - * @return an instance of JPanel class - */ - public JPanel createPanel(); - - /** - * @return an instance of JList class - */ - public JList createList(); - - /** - * @return an instance of JTable class - */ - public JTable createTable(); - - /** - * @return an instance of PropertyTable class - */ - public PropertyTable createPropertyTable(); - - /** - * @see com.jidesoft.status.StatusBar - * - * @return an instance of StatusBar class - */ - public StatusBar createStatusBar(); - - /** - * @see com.jidesoft.status.LabelStatusBarItem - * - * @return an instance of LabelStatusBarItem class - */ - public LabelStatusBarItem createLabelStatusBarItem(); - - /** - * @see com.jidesoft.status.ButtonStatusBarItem - * - * @return an instance of ButtonStatusBarItem class - */ - public ButtonStatusBarItem createButtonStatusBarItem(); - - /** - * @return an instance of JColorChooser class - */ - public JColorChooser createColorChooser(); - - /** - * @param text is the text for the button - * @return an instance of JRadioButton class - */ - public JRadioButton createRadioButton(final String text); - - /** - * @return an instance of JTabbedPane class - */ - public JTabbedPane createTabbedPane(); -} +package cz.cvut.promod.services.componentFactoryService; + +import com.jidesoft.swing.JideButton; +import com.jidesoft.grid.PropertyTable; +import com.jidesoft.status.StatusBar; +import com.jidesoft.status.LabelStatusBarItem; +import com.jidesoft.status.ButtonStatusBarItem; +import com.jidesoft.pane.OutlookTabbedPane; + +import javax.swing.*; +import javax.swing.tree.TreeNode; +import java.awt.*; + +import cz.cvut.promod.services.Service; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 21:13:35, 5.1.2010 + */ + +/** + * All Plugins and even the Modeler are supposed to use ComponentFactoryClass for creation of GUI components + * (including Swing components and JideSoft components). + * + * This programming style should ensure some kind of visual consistency in ProMod application. + */ +public interface ComponentFactoryService extends Service { + + /** + * Defines the recommended form border. Usually for usage in JGoodies.Borders factory. + * @see com.jgoodies.forms.factories.Borders + */ + public static final String DEFAULT_FORM_BORDER = "5dlu, 5dlu, 5dlu, 5dlu"; + + + /** Defines horizontal orientation of an instance of JideButton class */ + public static final int JIDE_BUTTON_HORIZONTAL_ORIENTATION = 0; + + /** Defines vertical orientation of an instance of JideButton class */ + public static final int JIDE_BUTTON_VERTICAL_ORIENTATION = 1; + + /** + * @return an instance of JComboBox class + */ + public JComboBox createComboBox(); + + /** + * @return an instance of JSpinner class + */ + public JSpinner createSpinner(); + + /** + * @return an instance of JTextArea class + */ + public JTextArea createTextArea(); + + /** + * @return an instance of JTextField class + */ + public JTextField createTextField(); + + /** + * @param text to be displayed in the JTextField + * @return an instance of JTextField class + */ + public JTextField createTextField(final String text); + + + /** + * @return an instance of JSlider class + */ + public JSlider createSlider(); + + /** + * @param text is a text to be displayed on the Label + * @return an instance of Label class + */ + public JLabel createLabel(final String text); + + /** + * @return an instance of JTree class + */ + public JTree createTree(); + + /** + * @return an instance of JTree class + */ + public JTree createTree(final TreeNode node); + + /** + * @param component is a component to be inserted to the ScrollPane + * @return an instance of ScrollPane class + */ + public JScrollPane createScrollPane(final Component component); + + /** + * @return an instance of JCheckBox class + */ + public JCheckBox createCheckBox(); + + /** + * @return an instance of MenuBar class + */ + public JMenuBar createMenuBar(); + + /** + * @return an instance of JToolBar class + */ + public JToolBar createToolBar(); + + /** + * @param text is a text to be displayed on the Menu + * @return an instance of Menu class + */ + public JMenu createMenu(final String text); + + /** + * @return an instance of JPopupMenu class + */ + public JPopupMenu createPopupMenu(); + + /** + * @return an instance of OutlookTabbedPane class. + */ + public OutlookTabbedPane createOutlookTabbedPane(); + + /** + * @param text is a text to be displayed on the MenuItem + * @return an instance of MenuItem class + */ + public JMenuItem createMenuItem(final String text); + + /** + * @param text is a text to be displayed on the Button + * @param icon is a icon to be displayed on the Button + * @return an instance of Button class + */ + public JButton createButton(final String text, final Icon icon); + + /** + * @param text is a text to be displayed on the ToggleButton + * @param icon is a icon to be displayed on the ToggleButton + * @return an instance of ToggleButton class + */ + public JToggleButton createToggleButton(final String text, final Icon icon); + + /** + * + * @param text is a text to be displayed on the button + * @param icon is an icon to be displayed on the button + * @param orientation JIDE_BUTTON_HORIZONTAL_ORIENTATION or JIDE_BUTTON_VERTICAL_ORIENTATION + * @return an instance of JideButton class + */ + public JideButton createJideButton( final String text, final Icon icon, int orientation ); + + /** + * @return an instance of JPanel class + */ + public JPanel createPanel(); + + /** + * @return an instance of JList class + */ + public JList createList(); + + /** + * @return an instance of JTable class + */ + public JTable createTable(); + + /** + * @return an instance of PropertyTable class + */ + public PropertyTable createPropertyTable(); + + /** + * @see com.jidesoft.status.StatusBar + * + * @return an instance of StatusBar class + */ + public StatusBar createStatusBar(); + + /** + * @see com.jidesoft.status.LabelStatusBarItem + * + * @return an instance of LabelStatusBarItem class + */ + public LabelStatusBarItem createLabelStatusBarItem(); + + /** + * @see com.jidesoft.status.ButtonStatusBarItem + * + * @return an instance of ButtonStatusBarItem class + */ + public ButtonStatusBarItem createButtonStatusBarItem(); + + /** + * @return an instance of JColorChooser class + */ + public JColorChooser createColorChooser(); + + /** + * @param text is the text for the button + * @return an instance of JRadioButton class + */ + public JRadioButton createRadioButton(final String text); + + /** + * @return an instance of JTabbedPane class + */ + public JTabbedPane createTabbedPane(); +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/componentFactoryService/ComponentFactoryServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/componentFactoryService/ComponentFactoryServiceImpl.java index b79e65b..e91e17b 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/componentFactoryService/ComponentFactoryServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/componentFactoryService/ComponentFactoryServiceImpl.java @@ -1,183 +1,183 @@ -package cz.cvut.promod.services.componentFactoryService; - -import cz.cvut.promod.services.Service; - -import javax.swing.*; -import javax.swing.tree.TreeNode; -import java.awt.*; - -import com.jidesoft.swing.JideButton; -import com.jidesoft.swing.JideToggleButton; -import com.jidesoft.swing.ButtonStyle; -import com.jidesoft.grid.PropertyTable; -import com.jidesoft.pane.OutlookTabbedPane; -import com.jidesoft.status.StatusBar; -import com.jidesoft.status.LabelStatusBarItem; -import com.jidesoft.status.ButtonStatusBarItem; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 16:21:11, 10.10.2009 - */ -public class ComponentFactoryServiceImpl implements Service, ComponentFactoryService{ - - /** {@inheritDoc} */ - public boolean check() { - // no tests required for this service - return true; - } - - /** {@inheritDoc} */ - public JComboBox createComboBox(){ - return new JComboBox(); - } - - /** {@inheritDoc} */ - public JSpinner createSpinner(){ - return new JSpinner(); - } - - /** {@inheritDoc} */ - public JTextArea createTextArea(){ - return new JTextArea(); - } - - /** {@inheritDoc} */ - public JTextField createTextField(){ - return new JTextField(); - } - - /** {@inheritDoc} */ - public JTextField createTextField(final String text){ - return new JTextField(text); - } - - /** {@inheritDoc} */ - public JSlider createSlider(){ - return new JSlider(); - } - - /** {@inheritDoc} */ - public JLabel createLabel(final String text){ - return new JLabel(text); - } - - /** {@inheritDoc} */ - public JTree createTree(){ - return new JTree(); - } - - /** {@inheritDoc} */ - public JTree createTree(final TreeNode node) { - return new JTree(node); - } - - /** {@inheritDoc} */ - public JScrollPane createScrollPane(final Component component){ - return new JScrollPane(component); - } - - /** {@inheritDoc} */ - public JCheckBox createCheckBox(){ - return new JCheckBox(); - } - - /** {@inheritDoc} */ - public JMenuBar createMenuBar(){ - return new JMenuBar(); - } - - /** {@inheritDoc} */ - public JToolBar createToolBar(){ - return new JToolBar(); - } - - /** {@inheritDoc} */ - public JMenu createMenu(final String text){ - return new JMenu(text); - } - - /** {@inheritDoc} */ - public JPopupMenu createPopupMenu(){ - return new JPopupMenu(); - } - - /** {@inheritDoc} */ - public JMenuItem createMenuItem(final String text){ - return new JMenuItem(text); - } - - /** {@inheritDoc} */ - public JButton createButton(final String text, final Icon icon){ - return new JButton(text, icon); - } - - /** {@inheritDoc} */ - public JToggleButton createToggleButton(final String text, final Icon icon){ - return new JToggleButton(text, icon); - } - - /** {@inheritDoc} */ - public JideButton createJideButton( final String text, final Icon icon, int orientation ){ - JideToggleButton button = new JideToggleButton(text, icon); - button.setButtonStyle(ButtonStyle.TOOLBOX_STYLE); - button.setOrientation(orientation); - - return button; - } - - /** {@inheritDoc} */ - public JPanel createPanel(){ - return new JPanel(); - } - - /** {@inheritDoc} */ - public JList createList(){ - return new JList(); - } - - /** {@inheritDoc} */ - public JTable createTable(){ - return new JTable(); - } - - /** {@inheritDoc} */ - public PropertyTable createPropertyTable() { - return new PropertyTable(); - } - - public OutlookTabbedPane createOutlookTabbedPane() { - return new OutlookTabbedPane(); - } - - /** {@inheritDoc} */ - public StatusBar createStatusBar() { - return new StatusBar(); - } - - /** {@inheritDoc} */ - public LabelStatusBarItem createLabelStatusBarItem() { - return new LabelStatusBarItem(); - } - - /** {@inheritDoc} */ - public ButtonStatusBarItem createButtonStatusBarItem() { - return new ButtonStatusBarItem(); - } - - /** {@inheritDoc} */ - public JColorChooser createColorChooser() { - return new JColorChooser(); - } - - /** {@inheritDoc} */ - public JRadioButton createRadioButton(final String text) { - return new JRadioButton(text); - } - - /** {@inheritDoc} */ - public JTabbedPane createTabbedPane() { - return new JTabbedPane(); - } -} +package cz.cvut.promod.services.componentFactoryService; + +import cz.cvut.promod.services.Service; + +import javax.swing.*; +import javax.swing.tree.TreeNode; +import java.awt.*; + +import com.jidesoft.swing.JideButton; +import com.jidesoft.swing.JideToggleButton; +import com.jidesoft.swing.ButtonStyle; +import com.jidesoft.grid.PropertyTable; +import com.jidesoft.pane.OutlookTabbedPane; +import com.jidesoft.status.StatusBar; +import com.jidesoft.status.LabelStatusBarItem; +import com.jidesoft.status.ButtonStatusBarItem; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 16:21:11, 10.10.2009 + */ +public class ComponentFactoryServiceImpl implements Service, ComponentFactoryService{ + + /** {@inheritDoc} */ + public boolean check() { + // no tests required for this service + return true; + } + + /** {@inheritDoc} */ + public JComboBox createComboBox(){ + return new JComboBox(); + } + + /** {@inheritDoc} */ + public JSpinner createSpinner(){ + return new JSpinner(); + } + + /** {@inheritDoc} */ + public JTextArea createTextArea(){ + return new JTextArea(); + } + + /** {@inheritDoc} */ + public JTextField createTextField(){ + return new JTextField(); + } + + /** {@inheritDoc} */ + public JTextField createTextField(final String text){ + return new JTextField(text); + } + + /** {@inheritDoc} */ + public JSlider createSlider(){ + return new JSlider(); + } + + /** {@inheritDoc} */ + public JLabel createLabel(final String text){ + return new JLabel(text); + } + + /** {@inheritDoc} */ + public JTree createTree(){ + return new JTree(); + } + + /** {@inheritDoc} */ + public JTree createTree(final TreeNode node) { + return new JTree(node); + } + + /** {@inheritDoc} */ + public JScrollPane createScrollPane(final Component component){ + return new JScrollPane(component); + } + + /** {@inheritDoc} */ + public JCheckBox createCheckBox(){ + return new JCheckBox(); + } + + /** {@inheritDoc} */ + public JMenuBar createMenuBar(){ + return new JMenuBar(); + } + + /** {@inheritDoc} */ + public JToolBar createToolBar(){ + return new JToolBar(); + } + + /** {@inheritDoc} */ + public JMenu createMenu(final String text){ + return new JMenu(text); + } + + /** {@inheritDoc} */ + public JPopupMenu createPopupMenu(){ + return new JPopupMenu(); + } + + /** {@inheritDoc} */ + public JMenuItem createMenuItem(final String text){ + return new JMenuItem(text); + } + + /** {@inheritDoc} */ + public JButton createButton(final String text, final Icon icon){ + return new JButton(text, icon); + } + + /** {@inheritDoc} */ + public JToggleButton createToggleButton(final String text, final Icon icon){ + return new JToggleButton(text, icon); + } + + /** {@inheritDoc} */ + public JideButton createJideButton( final String text, final Icon icon, int orientation ){ + JideToggleButton button = new JideToggleButton(text, icon); + button.setButtonStyle(ButtonStyle.TOOLBOX_STYLE); + button.setOrientation(orientation); + + return button; + } + + /** {@inheritDoc} */ + public JPanel createPanel(){ + return new JPanel(); + } + + /** {@inheritDoc} */ + public JList createList(){ + return new JList(); + } + + /** {@inheritDoc} */ + public JTable createTable(){ + return new JTable(); + } + + /** {@inheritDoc} */ + public PropertyTable createPropertyTable() { + return new PropertyTable(); + } + + public OutlookTabbedPane createOutlookTabbedPane() { + return new OutlookTabbedPane(); + } + + /** {@inheritDoc} */ + public StatusBar createStatusBar() { + return new StatusBar(); + } + + /** {@inheritDoc} */ + public LabelStatusBarItem createLabelStatusBarItem() { + return new LabelStatusBarItem(); + } + + /** {@inheritDoc} */ + public ButtonStatusBarItem createButtonStatusBarItem() { + return new ButtonStatusBarItem(); + } + + /** {@inheritDoc} */ + public JColorChooser createColorChooser() { + return new JColorChooser(); + } + + /** {@inheritDoc} */ + public JRadioButton createRadioButton(final String text) { + return new JRadioButton(text); + } + + /** {@inheritDoc} */ + public JTabbedPane createTabbedPane() { + return new JTabbedPane(); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/extensionService/ExtensionService.java b/IndependentModeler/src/cz/cvut/promod/services/extensionService/ExtensionService.java index abada34..7861095 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/extensionService/ExtensionService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/extensionService/ExtensionService.java @@ -1,35 +1,35 @@ -package cz.cvut.promod.services.extensionService; - -import cz.cvut.promod.plugin.extension.Extension; -import cz.cvut.promod.services.Service; - -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:40:57, 26.1.2010 - */ - -/** - * Extension Service is a access point to all loaded extensions. - */ -public interface ExtensionService extends Service { - - /** - * Returns the extension that is specified by the identifier. - * - * @param identifier is the extension's identifier - * - * @return required extension, null if there is not such a extension - */ - public Extension getExtension(final String identifier); - - /** - * Returns a list of all extensions. - * - * @return a list of all extensions - */ - public List getExtensions(); - -} +package cz.cvut.promod.services.extensionService; + +import cz.cvut.promod.plugin.extension.Extension; +import cz.cvut.promod.services.Service; + +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:40:57, 26.1.2010 + */ + +/** + * Extension Service is a access point to all loaded extensions. + */ +public interface ExtensionService extends Service { + + /** + * Returns the extension that is specified by the identifier. + * + * @param identifier is the extension's identifier + * + * @return required extension, null if there is not such a extension + */ + public Extension getExtension(final String identifier); + + /** + * Returns a list of all extensions. + * + * @return a list of all extensions + */ + public List getExtensions(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/extensionService/ExtensionServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/extensionService/ExtensionServiceImpl.java index f71f135..3dec3f3 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/extensionService/ExtensionServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/extensionService/ExtensionServiceImpl.java @@ -1,45 +1,45 @@ -package cz.cvut.promod.services.extensionService; - -import cz.cvut.promod.plugin.extension.Extension; - -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:41:08, 26.1.2010 - */ - -/** - * Implementation of Extension Service. - */ -public class ExtensionServiceImpl implements ExtensionService { - - private final List extensionsList; - - - public ExtensionServiceImpl(final List extensionsList) { - this.extensionsList = extensionsList; - } - - /** {@inheritDoc} */ - public Extension getExtension(final String identifier) { - for(final Extension extension : extensionsList){ - if(extension.getIdentifier().equals(identifier)){ - return extension; - } - } - - return null; - } - - /** {@inheritDoc} */ - public List getExtensions() { - return extensionsList; - } - - /** {@inheritDoc} */ - public boolean check() { - return true; - } -} +package cz.cvut.promod.services.extensionService; + +import cz.cvut.promod.plugin.extension.Extension; + +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:41:08, 26.1.2010 + */ + +/** + * Implementation of Extension Service. + */ +public class ExtensionServiceImpl implements ExtensionService { + + private final List extensionsList; + + + public ExtensionServiceImpl(final List extensionsList) { + this.extensionsList = extensionsList; + } + + /** {@inheritDoc} */ + public Extension getExtension(final String identifier) { + for(final Extension extension : extensionsList){ + if(extension.getIdentifier().equals(identifier)){ + return extension; + } + } + + return null; + } + + /** {@inheritDoc} */ + public List getExtensions() { + return extensionsList; + } + + /** {@inheritDoc} */ + public boolean check() { + return true; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuControlService.java b/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuControlService.java index 7a99e85..8dff88d 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuControlService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuControlService.java @@ -1,30 +1,30 @@ -package cz.cvut.promod.services.menuService; - -import javax.swing.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 0:20:39, 14.10.2009 - */ - -/** - * MenuControlService contains advanced method for menu managing. - */ -public interface MenuControlService extends MenuService { - - /** - * Returns the main menu bar. - * - * @return the main menu bar - */ - public JMenuBar getMenuBar(); - - /** - * Returns project navigation tree popup menu. - * - * @return project navigation tree popup menu - */ - public JPopupMenu getProjectTreePopupMenu(); - -} +package cz.cvut.promod.services.menuService; + +import javax.swing.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 0:20:39, 14.10.2009 + */ + +/** + * MenuControlService contains advanced method for menu managing. + */ +public interface MenuControlService extends MenuService { + + /** + * Returns the main menu bar. + * + * @return the main menu bar + */ + public JMenuBar getMenuBar(); + + /** + * Returns project navigation tree popup menu. + * + * @return project navigation tree popup menu + */ + public JPopupMenu getProjectTreePopupMenu(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuControlServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuControlServiceImpl.java index dc1b894..bee2706 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuControlServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuControlServiceImpl.java @@ -1,746 +1,746 @@ -package cz.cvut.promod.services.menuService; - -import cz.cvut.promod.gui.ModelerModel; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import cz.cvut.promod.services.menuService.utils.*; -import org.apache.log4j.Logger; - -import javax.swing.*; -import java.awt.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:49:26, 10.10.2009 - */ - -/** - * Implementation of MenuService and MenuControlService. - */ -public class MenuControlServiceImpl implements MenuControlService { - - private final Logger LOG = Logger.getLogger(MenuControlServiceImpl.class); - - private final JPopupMenu projectTreePopupMenu; - private final JMenuBar menuBar; - - public MenuControlServiceImpl(){ - projectTreePopupMenu = ModelerSession.getComponentFactoryService().createPopupMenu(); - menuBar = ModelerSession.getComponentFactoryService().createMenuBar(); - } - - /** {@inheritDoc} */ - public boolean check() { - return true; - } - - /** {@inheritDoc} */ - public JMenuBar getMenuBar(){ - return menuBar; - } - - /** {@inheritDoc} */ - public JPopupMenu getProjectTreePopupMenu() { - return projectTreePopupMenu; - } - - /** {@inheritDoc} */ - public InsertMenuItemResult insertProjectNavigationPopupMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition) { - - return insertProjectNavigationPopupMenuItem( - proModAction, - menuItemPosition, - MenuSeparator.NONE - ); - } - - /** {@inheritDoc} */ - public InsertMenuItemResult insertProjectNavigationPopupMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator) { - - return registerPopupMenuItem( - ModelerModel.MODELER_IDENTIFIER, - proModAction, - menuItemPosition, - menuSeparator - ); - } - - /** {@inheritDoc} */ - public InsertMenuItemResult insertPopupMenuItem(final String notationIdentifier, - final ProModAction proModAction, - final MenuItemPosition menuItemPosition){ - - return insertPopupMenuItem( - notationIdentifier, - proModAction, - menuItemPosition, - MenuSeparator.NONE - ); - } - - /** {@inheritDoc} */ - public InsertMenuItemResult insertPopupMenuItem(final String notationIdentifier, - final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator) { - - return registerPopupMenuItem( - notationIdentifier, - proModAction, - menuItemPosition, - menuSeparator - ); - } - - /** - * Inserts the popup menu item. - * - * @param notationIdentifier is the identifier of notation - * @param proModAction is the action to be added - * @param menuItemPosition is the menu items required position - * @param menuSeparator true if the separator should be added - * @return an value of InsertMenuItemResult enum saying what was the the operation result - */ - private InsertMenuItemResult registerPopupMenuItem(final String notationIdentifier, - final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator) { - - - // check whether all notations identifiers in includedInNotations set are valid identifiers of loaded notations - - //final JPopupMenu popupMenu = getRequiredPopupMenu(notationIdentifier); - - JPopupMenu popupMenu; - - if(ModelerModel.MODELER_IDENTIFIER.equals(notationIdentifier)){ - popupMenu = projectTreePopupMenu; - // if notation doesn't support popup menu - if(popupMenu == null){ - LOG.error("Notation (" + notationIdentifier +") doesn't support popup menu."); - return InsertMenuItemResult.POPUP_NOT_SUPPORTED; - } - - if(menuItemPosition == null || menuItemPosition.getHierarchicalPlacement() == null){ - LOG.error("Nullary MenuItemPosition info."); - return InsertMenuItemResult.WRONG_PLACEMENT; - } - - final String hierarchicalPlacement = menuItemPosition.getHierarchicalPlacement(); - final String[] placementParts; - - if(hierarchicalPlacement != null && !hierarchicalPlacement.isEmpty()){ - placementParts = hierarchicalPlacement.split(PLACEMENT_DELIMITER); - } else { - placementParts = new String[0]; - } - - // get all menus of popupMenuItems - final JMenuItem[] popupMenuItems = new JMenuItem[popupMenu.getComponentCount()]; - for(int i = 0; i < popupMenu.getComponentCount(); i++){ - popupMenuItems[i] = (JMenuItem) popupMenu.getComponent(i); - } - - return insertIntoMenu( - popupMenuItems, - placementParts, - proModAction, - null, - null, - popupMenu, - menuSeparator, - menuItemPosition, - false - ); - } - - if(ModelerSession.getNotationService().existNotation(notationIdentifier)){ - return ModelerSession.getNotationService().getNotation(notationIdentifier).addPopupMenuItem(proModAction, menuItemPosition, menuSeparator, false); - } else { - LOG.error("No existing notation cannot provide it's popup menu."); - return null; - } - - - } - - /** {@inheritDoc} */ - public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final boolean checkable){ - - return insertMainMenuItem(proModAction, menuItemPosition, MenuSeparator.NONE, checkable); - } - - /** {@inheritDoc} */ - public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator, - final boolean checkable){ - - if(menuItemPosition == null || menuItemPosition.getHierarchicalPlacement() == null){ - LOG.error("Nullary MenuItemPosition info."); - return InsertMenuItemResult.WRONG_PLACEMENT; - } - - final String[] placementParts = menuItemPosition.getHierarchicalPlacement().split(PLACEMENT_DELIMITER); - if(!areValidPlacementParts(placementParts)){ - LOG.error("Invalid any/all part(s) of MenuItemPosition info."); - return InsertMenuItemResult.WRONG_PLACEMENT; - } - - if(placementParts.length < 1){ - LOG.error("Illegal menu item location."); - return InsertMenuItemResult.WRONG_PLACEMENT; - } - - // get all menus of menuBar - final JMenuItem[] menuBarItems = new JMenuItem[menuBar.getMenuCount()]; - for(int i = 0; i < menuBar.getMenuCount(); i++){ - menuBarItems[i] = menuBar.getMenu(i); - } - - return insertIntoMenu( - menuBarItems, - placementParts, - proModAction, - null, - menuBar, - null, - menuSeparator, - menuItemPosition, - checkable - ); - } - - /** - * Checks the menu item placement parts not to be null or an empty strings. - * - * @param placementParts is an array representing hierarchical menu item placement - * @return true if all the placement parts are correct, false otherwise - */ - private boolean areValidPlacementParts(final String[] placementParts) { - for(final String placement : placementParts){ - if(placement == null || placement.isEmpty()){ - return false; - } - } - - return true; - } - - /** {@inheritDoc} */ - public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition){ - - return insertMainMenuItem( - proModAction, - menuItemPosition, - false); - } - - /** {@inheritDoc} */ - public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator){ - - return insertMainMenuItem( - proModAction, - menuItemPosition, - menuSeparator, - false); - } - - /** - * @param menu parent - * @return items in the parent menu - */ - private JMenuItem[] getMenuItems(final JMenu menu){ - final ArrayList array = new ArrayList(); - - for(int i = 0; i < menu.getItemCount(); i++){ - final Object object = menu.getItem(i); - if((object != null)){ - array.add(menu.getItem(i)); - } - } - - return array.toArray(new JMenuItem[array.size()]); - } - - /** - * Inserts the menu action. - * - * @param parentMenu is the parent menu where the action is supposed to be added - * @param parentPopupMenu is the parent popup menu where the action is supposed to be added - * @param proModAction is the action to be inserted - * @param menuSeparator the separator if one is supposed to be inserted - * @param menuItemPosition required menu item position - * @param checkable true if the menu item is supposed to be checkable - * @return true if no error occurs, false otherwise - */ - public InsertMenuItemResult insertAction(final JMenu parentMenu, - final JPopupMenu parentPopupMenu, - final ProModAction proModAction, - final MenuSeparator menuSeparator, - final MenuItemPosition menuItemPosition, - final boolean checkable){ - - // just one parent can be used - if(parentMenu != null && parentPopupMenu != null){ - LOG.error("There can be just one parent menu item for new menu item insertion."); - throw new IllegalArgumentException("Obscure parent menu item."); - } - - if(proModAction == null){ - LOG.error("Nullary action cannot be inserted into the menu."); - return InsertMenuItemResult.UNDEFINED_ACTION; - } - - if(proModAction.getValue(Action.NAME) == null || ((String)proModAction.getValue(Action.NAME)).isEmpty()){ - return InsertMenuItemResult.UNDEFINED_ACTION; - } - - final JMenuItem menuItem = (JMenuItem) getMenuItem(checkable); - menuItem.setAction(proModAction); - - // check whether the is no same menu item in the this menu structure level - final List relatives = - isUniqueMenuItemLabel(parentPopupMenu, parentMenu, (String) proModAction.getValue(Action.NAME)); - if(relatives != null){ - LOG.debug("Inserting a menu item to the menu hierarchy where a menu item with the same name (" + - proModAction.getValue(Action.NAME) + ") has already been inserted."); - - if(menuItem instanceof ModelerMenuItem){ - ((ModelerMenuItem) menuItem).setListOfRelatives(relatives); - - // if there are any relatives, always group them - menuItemPosition.getPositionInfo().setRelativePosition(MenuItemPosition.PlacementStyle.GROUPED); - } - } - - if(!isUniqueAction(parentMenu, parentPopupMenu, proModAction)){ - LOG.error("Inserting the same action to the one menu more than once."); - return InsertMenuItemResult.DUPLICIT_ACTION; - } - - int insertionPosition = insertItem(menuItemPosition, menuItem, parentMenu, parentPopupMenu); - if(insertionPosition < 0){ - return InsertMenuItemResult.WRONG_PLACEMENT; - } - - // if items are grouped, only one separator can be inserted before and one after the group - // this statement deals with inserting of separators AFTER the group - if(MenuSeparator.AFTER.equals(menuSeparator)){ - if(relatives != null && relatives.size() > 0){ // grouping active - insertionPosition += relatives.size() + 1; - } - } - - insertSeparator(menuSeparator, parentMenu, parentPopupMenu, insertionPosition); - - return InsertMenuItemResult.SUCCESS; - } - - /** - * Checks whether no the same action has been already inserted under the same menu parent. - * - * @param parentMenu is to menu parent - * @param parentPopupMenu is the popup menu parent - * @param proModAction is the action supposed to be inserted - * @return true if there is no the same action under the parent, false otherwise - */ - private boolean isUniqueAction(final JMenu parentMenu, - final JPopupMenu parentPopupMenu, - final ProModAction proModAction) { - - final Component[] menuComponets; - if(parentMenu != null){ - menuComponets = parentMenu.getMenuComponents(); - } else if(parentPopupMenu != null){ - menuComponets = parentPopupMenu.getComponents(); - } else { - LOG.error("Parent of menu item cannot be determined."); - return false; - } - - for(final Component component : menuComponets){ - if(component instanceof JMenuItem){ - final JMenuItem menuItem = (JMenuItem) component; - final Action action = menuItem.getAction(); - - if(action != null && action == proModAction){ - return false; - } - } - } - - - return true; - } - - /** - * Inserts a menu separator to the required position. Never inserts two separators next to each other. - * - * @param menuSeparator hold information whether insert separator or not and the relative position - * @param parentMenu is the parent menu item - * @param parentPopupMenu is the parent popup menu item - * @param insertionPosition is the actual position of the menu item that has been just added and to which is the - * relative position of the separator specified - */ - private void insertSeparator(final MenuSeparator menuSeparator, - final JMenu parentMenu, - final JPopupMenu parentPopupMenu, - final int insertionPosition) { - - // do not insert two separator next to each other - final Component[] components; - if(parentMenu != null){ - components = parentMenu.getMenuComponents(); - } else if(parentPopupMenu != null){ - components = parentPopupMenu.getComponents(); - } else { - LOG.error("Obscurity in menu parents."); - return; - } - - if(!isAloneSeparator(components, insertionPosition, menuSeparator)){ - LOG.info("Skipping insertion of menu separator."); - return; - } - - // insert line separator before, if obtained - if(MenuSeparator.BEFORE.equals(menuSeparator)){ - if(parentMenu != null) { - parentMenu.insertSeparator(insertionPosition); - } else{ - parentPopupMenu.insert(new JPopupMenu.Separator(), insertionPosition); - } - } - - // insert line separator after, if obtained - if(MenuSeparator.AFTER.equals(menuSeparator)){ - if(parentMenu != null) { - parentMenu.insertSeparator(insertionPosition + 1); - } else { - parentPopupMenu.insert(new JPopupMenu.Separator(), insertionPosition + 1); - } - } - } - - /** - * - * @param menuComponents menu items - * @param insertionPosition required menu item position - * @param menuSeparator menu separator info if one is supposed to be insert - * @return true if there could be the separator added - */ - private boolean isAloneSeparator(final Component[] menuComponents, - final int insertionPosition, - final MenuSeparator menuSeparator) { - if(menuSeparator != null){ - switch(menuSeparator){ - case AFTER: - case BEFORE: - if(isValidMenuPosition(insertionPosition, menuComponents.length)){ - if(menuComponents[insertionPosition] instanceof JPopupMenu.Separator){ - return false; - } - } - } - - switch(menuSeparator){ - case AFTER: - if(isValidMenuPosition(insertionPosition + 1, menuComponents.length)){ - if(menuComponents[insertionPosition + 1] instanceof JPopupMenu.Separator){ - return false; - } - } - break; - case BEFORE: - if(isValidMenuPosition(insertionPosition - 1, menuComponents.length)){ - if(menuComponents[insertionPosition - 1] instanceof JPopupMenu.Separator){ - return false; - } - } - break; - } - } - - return true; - } - - /** - * @param position menu position - * @param menuItems menu items - * @return true if the given position is valid - */ - private boolean isValidMenuPosition(final int position, final int menuItems){ - return !(position < 0 || position > (menuItems - 1)); - - } - - /** - * Performs the actual insertion of menu item. - * - * @param menuItemPosition is the specification of item's position - * @param menuItem is the item to be inserted - * @param parentMenu is the parent menu - * @param parentPopupMenu is the parent popupMenu - * @return the position to that has been the new menu item inserted - */ - private int insertItem(final MenuItemPosition menuItemPosition, - final JMenuItem menuItem, - final JMenu parentMenu, - final JPopupMenu parentPopupMenu) { - - int insertionPosition = -1; - - //insert menuItem to the position specified (exact position, FIRST, LAST possibilities) - if(MenuItemPosition.PlacementStyle.GROUPED.equals(menuItemPosition.getPlacementStyle())){ - final Component[] parentMenuItems; - if(parentMenu != null && parentPopupMenu == null){ - parentMenuItems = parentMenu.getMenuComponents(); - } - else if(parentMenu == null && parentPopupMenu != null){ - parentMenuItems = parentPopupMenu.getComponents(); - } - else { - LOG.error("Obscurity in menu item's parent."); - return -1; - } - - final int position = groupMenuItem(menuItem, parentMenuItems); - if(parentMenu != null){ - parentMenu.insert(menuItem, position); - } else { - parentPopupMenu.insert(menuItem, position); - } - - insertionPosition = position; - } - else if(menuItemPosition.getPosition() >= 0){ - if(parentMenu != null) { - final int position = Math.min(menuItemPosition.getPosition(), parentMenu.getItemCount()); - parentMenu.insert(menuItem, position); - insertionPosition = position; - } - else if(parentPopupMenu != null) { - final int position = Math.min(menuItemPosition.getPosition(), parentPopupMenu.getComponentCount()); - parentPopupMenu.insert(menuItem, position); - insertionPosition = position; - } - } else { - if(MenuItemPosition.PlacementStyle.FIRST.equals(menuItemPosition.getPlacementStyle())){ - if(parentMenu != null) { parentMenu.insert(menuItem, 0); } - else if(parentPopupMenu != null) { parentPopupMenu.insert(menuItem, 0); } - - insertionPosition = 0; - - } else if(MenuItemPosition.PlacementStyle.LAST.equals(menuItemPosition.getPlacementStyle())){ - if(parentMenu != null) { - parentMenu.add(menuItem); - insertionPosition = parentMenu.getMenuComponentCount() -1; - } - else if(parentPopupMenu != null) { - parentPopupMenu.add(menuItem); - insertionPosition = parentPopupMenu.getComponentCount() - 1; - } - } - } - - return insertionPosition; - } - - /** - * Finds the menu item(s) having the same text under the same parent menu item and returns the position - * (first possible) whether the new menu item is supposed to be inserted. - * - * @param menuItem is the menu item that is supposed to be inserted - * @param parentMenuItems are all current menu items - * @return the position where the new menu item is supposed to be inserted - */ - private int groupMenuItem(final JMenuItem menuItem, final Component[] parentMenuItems) { - for(int i = 0; i < parentMenuItems.length; i++){ - final Component component = parentMenuItems[i]; - - if(component instanceof JMenuItem){ - final JMenuItem item = (JMenuItem) component; - - if(item instanceof ModelerMenuItem && item.getText().equalsIgnoreCase(menuItem.getText())){ - return i; - } - } - } - - return parentMenuItems.length; - } - - private ModelerMenuItem getMenuItem(final boolean checkable) { - if(checkable){ - return new CheckableMenuItem(); - } else { - return new DefaultMenuItem(); - } - } - - /** - * Finds the duplicity in menu item names and prepare the 'relatives' mechanism. - * If there are more than one item having the same text on it, then the set if relatives is set to an empty - * set. The last item having the same text on it have this set filled by references on the previous items - * having the same text (relatives). All menu items that do not have any duplicity in text have this set set - * to null. - * - * @param parentPopupMenu is the parent popup menu item - * @param parentMenu is the parent menu item - * @param displayName is the text that is supposed to be displayed on the menu item - * @return the set holding references to the relatives, null if there is no text duplicity - * @throws IllegalArgumentException when an obscurity in parent occurs - */ - private List isUniqueMenuItemLabel( - final JPopupMenu parentPopupMenu, final JMenu parentMenu, final String displayName) throws IllegalArgumentException{ - - if(parentMenu != null && parentPopupMenu != null){ - LOG.error("There can be just one parent menu item for new menu item insertion."); - throw new IllegalArgumentException("Obscure parent menu item."); - } - - final Component[] menuComponents; - if(parentPopupMenu != null){ - menuComponents = parentPopupMenu.getComponents(); - } else { - assert parentMenu != null; - menuComponents = parentMenu.getMenuComponents(); - } - - List relatives = null; - - for(final Component component : menuComponents){ - if(component instanceof JMenuItem){ - final JMenuItem menuItem = (JMenuItem) component; - - if(displayName.equals(menuItem.getText())){ - if(menuItem instanceof ModelerMenuItem){ - final ModelerMenuItem modelerMenuItem = (ModelerMenuItem) menuItem; - - relatives = modelerMenuItem.getListOfRelatives(); - modelerMenuItem.setListOfRelatives(new LinkedList()); - - if(relatives == null){ - relatives = new LinkedList(); - } - - relatives.add(modelerMenuItem); - } - } - } - } - - return relatives; - } - - /** - * Inserts the menu item. - * - * @param menuLevelItems is the parent menu item - * @param placementParts is the hierarchical position - * @param proModAction is the action to be inserted - * @param parentMenu menu parent - * @param parentMenuBar menu bar - * @param parentPopupMenu parent popup menu - * @param menuSeparator menu separator info - * @param menuItemPosition menu item position info - * @param checkable true if the action is supposed to be checkable - * @return true id no error occurred, false otherwise - */ - private InsertMenuItemResult insertIntoMenu( - final JMenuItem[] menuLevelItems, - final String[] placementParts, - final ProModAction proModAction, - final JMenu parentMenu, - final JMenuBar parentMenuBar, - final JPopupMenu parentPopupMenu, - final MenuSeparator menuSeparator, - final MenuItemPosition menuItemPosition, - final boolean checkable) { - // parent has to be clear - if((parentMenu != null && parentMenuBar != null) - || (parentMenu != null && parentPopupMenu != null) - || (parentMenuBar != null && parentPopupMenu != null)){ - LOG.error("Obscurity in parent of menu item"); - throw new IllegalArgumentException("Obscure parent menu item."); - } - - if(proModAction == null){ - LOG.error("Nullary action to be inserted."); - return InsertMenuItemResult.UNDEFINED_ACTION; - } - - if(!ModelerSession.getActionControlService().isRegisteredAction(proModAction)){ - LOG.error("Unregistered action, action identifier: " + proModAction.getActionIdentifier()); - return InsertMenuItemResult.NOT_REGISTERED_ACTION; - } - - if(placementParts.length == 0){ - if(parentMenu != null){ - return insertAction(parentMenu, null, proModAction, menuSeparator, menuItemPosition, checkable); - } else if (parentPopupMenu != null){ - return insertAction(null, parentPopupMenu, proModAction, menuSeparator, menuItemPosition, checkable); - } else { - LOG.error("No parent set for the menu item."); - return InsertMenuItemResult.WRONG_PLACEMENT; - } - } else { - for (final JMenuItem menuItem : menuLevelItems) { - if (menuItem.getText().equals(placementParts[0])) { - if (menuItem instanceof JMenu) { - final JMenu menu = (JMenu) menuItem; - - final JMenuItem[] nextMenuItems = getMenuItems(menu); - - return insertIntoMenu( - nextMenuItems, - Arrays.copyOfRange(placementParts, 1, placementParts.length), - proModAction, - menu, - null, - null, - menuSeparator, - menuItemPosition, - checkable - ); - } - } - } - - JMenu parent = parentMenu; - for (final String placementPart : placementParts) { - final JMenu menu = ModelerSession.getComponentFactoryService().createMenu(placementPart); - - if (parent != null) { - parent.add(menu); - } else if (parentMenuBar != null) { - parentMenuBar.add(menu); - } else if (parentPopupMenu != null) { - parentPopupMenu.add(menu); - } else { - LOG.error("There is no parent set to build the menu structure."); - throw new IllegalArgumentException("Obscure parent menu item."); - } - - parent = menu; - } - - return insertAction(parent, null, proModAction, menuSeparator, menuItemPosition, checkable); - } - } - - } +package cz.cvut.promod.services.menuService; + +import cz.cvut.promod.gui.ModelerModel; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import cz.cvut.promod.services.menuService.utils.*; +import org.apache.log4j.Logger; + +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:49:26, 10.10.2009 + */ + +/** + * Implementation of MenuService and MenuControlService. + */ +public class MenuControlServiceImpl implements MenuControlService { + + private final Logger LOG = Logger.getLogger(MenuControlServiceImpl.class); + + private final JPopupMenu projectTreePopupMenu; + private final JMenuBar menuBar; + + public MenuControlServiceImpl(){ + projectTreePopupMenu = ModelerSession.getComponentFactoryService().createPopupMenu(); + menuBar = ModelerSession.getComponentFactoryService().createMenuBar(); + } + + /** {@inheritDoc} */ + public boolean check() { + return true; + } + + /** {@inheritDoc} */ + public JMenuBar getMenuBar(){ + return menuBar; + } + + /** {@inheritDoc} */ + public JPopupMenu getProjectTreePopupMenu() { + return projectTreePopupMenu; + } + + /** {@inheritDoc} */ + public InsertMenuItemResult insertProjectNavigationPopupMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition) { + + return insertProjectNavigationPopupMenuItem( + proModAction, + menuItemPosition, + MenuSeparator.NONE + ); + } + + /** {@inheritDoc} */ + public InsertMenuItemResult insertProjectNavigationPopupMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator) { + + return registerPopupMenuItem( + ModelerModel.MODELER_IDENTIFIER, + proModAction, + menuItemPosition, + menuSeparator + ); + } + + /** {@inheritDoc} */ + public InsertMenuItemResult insertPopupMenuItem(final String notationIdentifier, + final ProModAction proModAction, + final MenuItemPosition menuItemPosition){ + + return insertPopupMenuItem( + notationIdentifier, + proModAction, + menuItemPosition, + MenuSeparator.NONE + ); + } + + /** {@inheritDoc} */ + public InsertMenuItemResult insertPopupMenuItem(final String notationIdentifier, + final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator) { + + return registerPopupMenuItem( + notationIdentifier, + proModAction, + menuItemPosition, + menuSeparator + ); + } + + /** + * Inserts the popup menu item. + * + * @param notationIdentifier is the identifier of notation + * @param proModAction is the action to be added + * @param menuItemPosition is the menu items required position + * @param menuSeparator true if the separator should be added + * @return an value of InsertMenuItemResult enum saying what was the the operation result + */ + private InsertMenuItemResult registerPopupMenuItem(final String notationIdentifier, + final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator) { + + + // check whether all notations identifiers in includedInNotations set are valid identifiers of loaded notations + + //final JPopupMenu popupMenu = getRequiredPopupMenu(notationIdentifier); + + JPopupMenu popupMenu; + + if(ModelerModel.MODELER_IDENTIFIER.equals(notationIdentifier)){ + popupMenu = projectTreePopupMenu; + // if notation doesn't support popup menu + if(popupMenu == null){ + LOG.error("Notation (" + notationIdentifier +") doesn't support popup menu."); + return InsertMenuItemResult.POPUP_NOT_SUPPORTED; + } + + if(menuItemPosition == null || menuItemPosition.getHierarchicalPlacement() == null){ + LOG.error("Nullary MenuItemPosition info."); + return InsertMenuItemResult.WRONG_PLACEMENT; + } + + final String hierarchicalPlacement = menuItemPosition.getHierarchicalPlacement(); + final String[] placementParts; + + if(hierarchicalPlacement != null && !hierarchicalPlacement.isEmpty()){ + placementParts = hierarchicalPlacement.split(PLACEMENT_DELIMITER); + } else { + placementParts = new String[0]; + } + + // get all menus of popupMenuItems + final JMenuItem[] popupMenuItems = new JMenuItem[popupMenu.getComponentCount()]; + for(int i = 0; i < popupMenu.getComponentCount(); i++){ + popupMenuItems[i] = (JMenuItem) popupMenu.getComponent(i); + } + + return insertIntoMenu( + popupMenuItems, + placementParts, + proModAction, + null, + null, + popupMenu, + menuSeparator, + menuItemPosition, + false + ); + } + + if(ModelerSession.getNotationService().existNotation(notationIdentifier)){ + return ModelerSession.getNotationService().getNotation(notationIdentifier).addPopupMenuItem(proModAction, menuItemPosition, menuSeparator, false); + } else { + LOG.error("No existing notation cannot provide it's popup menu."); + return null; + } + + + } + + /** {@inheritDoc} */ + public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final boolean checkable){ + + return insertMainMenuItem(proModAction, menuItemPosition, MenuSeparator.NONE, checkable); + } + + /** {@inheritDoc} */ + public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator, + final boolean checkable){ + + if(menuItemPosition == null || menuItemPosition.getHierarchicalPlacement() == null){ + LOG.error("Nullary MenuItemPosition info."); + return InsertMenuItemResult.WRONG_PLACEMENT; + } + + final String[] placementParts = menuItemPosition.getHierarchicalPlacement().split(PLACEMENT_DELIMITER); + if(!areValidPlacementParts(placementParts)){ + LOG.error("Invalid any/all part(s) of MenuItemPosition info."); + return InsertMenuItemResult.WRONG_PLACEMENT; + } + + if(placementParts.length < 1){ + LOG.error("Illegal menu item location."); + return InsertMenuItemResult.WRONG_PLACEMENT; + } + + // get all menus of menuBar + final JMenuItem[] menuBarItems = new JMenuItem[menuBar.getMenuCount()]; + for(int i = 0; i < menuBar.getMenuCount(); i++){ + menuBarItems[i] = menuBar.getMenu(i); + } + + return insertIntoMenu( + menuBarItems, + placementParts, + proModAction, + null, + menuBar, + null, + menuSeparator, + menuItemPosition, + checkable + ); + } + + /** + * Checks the menu item placement parts not to be null or an empty strings. + * + * @param placementParts is an array representing hierarchical menu item placement + * @return true if all the placement parts are correct, false otherwise + */ + private boolean areValidPlacementParts(final String[] placementParts) { + for(final String placement : placementParts){ + if(placement == null || placement.isEmpty()){ + return false; + } + } + + return true; + } + + /** {@inheritDoc} */ + public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition){ + + return insertMainMenuItem( + proModAction, + menuItemPosition, + false); + } + + /** {@inheritDoc} */ + public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator){ + + return insertMainMenuItem( + proModAction, + menuItemPosition, + menuSeparator, + false); + } + + /** + * @param menu parent + * @return items in the parent menu + */ + private JMenuItem[] getMenuItems(final JMenu menu){ + final ArrayList array = new ArrayList(); + + for(int i = 0; i < menu.getItemCount(); i++){ + final Object object = menu.getItem(i); + if((object != null)){ + array.add(menu.getItem(i)); + } + } + + return array.toArray(new JMenuItem[array.size()]); + } + + /** + * Inserts the menu action. + * + * @param parentMenu is the parent menu where the action is supposed to be added + * @param parentPopupMenu is the parent popup menu where the action is supposed to be added + * @param proModAction is the action to be inserted + * @param menuSeparator the separator if one is supposed to be inserted + * @param menuItemPosition required menu item position + * @param checkable true if the menu item is supposed to be checkable + * @return true if no error occurs, false otherwise + */ + public InsertMenuItemResult insertAction(final JMenu parentMenu, + final JPopupMenu parentPopupMenu, + final ProModAction proModAction, + final MenuSeparator menuSeparator, + final MenuItemPosition menuItemPosition, + final boolean checkable){ + + // just one parent can be used + if(parentMenu != null && parentPopupMenu != null){ + LOG.error("There can be just one parent menu item for new menu item insertion."); + throw new IllegalArgumentException("Obscure parent menu item."); + } + + if(proModAction == null){ + LOG.error("Nullary action cannot be inserted into the menu."); + return InsertMenuItemResult.UNDEFINED_ACTION; + } + + if(proModAction.getValue(Action.NAME) == null || ((String)proModAction.getValue(Action.NAME)).isEmpty()){ + return InsertMenuItemResult.UNDEFINED_ACTION; + } + + final JMenuItem menuItem = (JMenuItem) getMenuItem(checkable); + menuItem.setAction(proModAction); + + // check whether the is no same menu item in the this menu structure level + final List relatives = + isUniqueMenuItemLabel(parentPopupMenu, parentMenu, (String) proModAction.getValue(Action.NAME)); + if(relatives != null){ + LOG.debug("Inserting a menu item to the menu hierarchy where a menu item with the same name (" + + proModAction.getValue(Action.NAME) + ") has already been inserted."); + + if(menuItem instanceof ModelerMenuItem){ + ((ModelerMenuItem) menuItem).setListOfRelatives(relatives); + + // if there are any relatives, always group them + menuItemPosition.getPositionInfo().setRelativePosition(MenuItemPosition.PlacementStyle.GROUPED); + } + } + + if(!isUniqueAction(parentMenu, parentPopupMenu, proModAction)){ + LOG.error("Inserting the same action to the one menu more than once."); + return InsertMenuItemResult.DUPLICIT_ACTION; + } + + int insertionPosition = insertItem(menuItemPosition, menuItem, parentMenu, parentPopupMenu); + if(insertionPosition < 0){ + return InsertMenuItemResult.WRONG_PLACEMENT; + } + + // if items are grouped, only one separator can be inserted before and one after the group + // this statement deals with inserting of separators AFTER the group + if(MenuSeparator.AFTER.equals(menuSeparator)){ + if(relatives != null && relatives.size() > 0){ // grouping active + insertionPosition += relatives.size() + 1; + } + } + + insertSeparator(menuSeparator, parentMenu, parentPopupMenu, insertionPosition); + + return InsertMenuItemResult.SUCCESS; + } + + /** + * Checks whether no the same action has been already inserted under the same menu parent. + * + * @param parentMenu is to menu parent + * @param parentPopupMenu is the popup menu parent + * @param proModAction is the action supposed to be inserted + * @return true if there is no the same action under the parent, false otherwise + */ + private boolean isUniqueAction(final JMenu parentMenu, + final JPopupMenu parentPopupMenu, + final ProModAction proModAction) { + + final Component[] menuComponets; + if(parentMenu != null){ + menuComponets = parentMenu.getMenuComponents(); + } else if(parentPopupMenu != null){ + menuComponets = parentPopupMenu.getComponents(); + } else { + LOG.error("Parent of menu item cannot be determined."); + return false; + } + + for(final Component component : menuComponets){ + if(component instanceof JMenuItem){ + final JMenuItem menuItem = (JMenuItem) component; + final Action action = menuItem.getAction(); + + if(action != null && action == proModAction){ + return false; + } + } + } + + + return true; + } + + /** + * Inserts a menu separator to the required position. Never inserts two separators next to each other. + * + * @param menuSeparator hold information whether insert separator or not and the relative position + * @param parentMenu is the parent menu item + * @param parentPopupMenu is the parent popup menu item + * @param insertionPosition is the actual position of the menu item that has been just added and to which is the + * relative position of the separator specified + */ + private void insertSeparator(final MenuSeparator menuSeparator, + final JMenu parentMenu, + final JPopupMenu parentPopupMenu, + final int insertionPosition) { + + // do not insert two separator next to each other + final Component[] components; + if(parentMenu != null){ + components = parentMenu.getMenuComponents(); + } else if(parentPopupMenu != null){ + components = parentPopupMenu.getComponents(); + } else { + LOG.error("Obscurity in menu parents."); + return; + } + + if(!isAloneSeparator(components, insertionPosition, menuSeparator)){ + LOG.info("Skipping insertion of menu separator."); + return; + } + + // insert line separator before, if obtained + if(MenuSeparator.BEFORE.equals(menuSeparator)){ + if(parentMenu != null) { + parentMenu.insertSeparator(insertionPosition); + } else{ + parentPopupMenu.insert(new JPopupMenu.Separator(), insertionPosition); + } + } + + // insert line separator after, if obtained + if(MenuSeparator.AFTER.equals(menuSeparator)){ + if(parentMenu != null) { + parentMenu.insertSeparator(insertionPosition + 1); + } else { + parentPopupMenu.insert(new JPopupMenu.Separator(), insertionPosition + 1); + } + } + } + + /** + * + * @param menuComponents menu items + * @param insertionPosition required menu item position + * @param menuSeparator menu separator info if one is supposed to be insert + * @return true if there could be the separator added + */ + private boolean isAloneSeparator(final Component[] menuComponents, + final int insertionPosition, + final MenuSeparator menuSeparator) { + if(menuSeparator != null){ + switch(menuSeparator){ + case AFTER: + case BEFORE: + if(isValidMenuPosition(insertionPosition, menuComponents.length)){ + if(menuComponents[insertionPosition] instanceof JPopupMenu.Separator){ + return false; + } + } + } + + switch(menuSeparator){ + case AFTER: + if(isValidMenuPosition(insertionPosition + 1, menuComponents.length)){ + if(menuComponents[insertionPosition + 1] instanceof JPopupMenu.Separator){ + return false; + } + } + break; + case BEFORE: + if(isValidMenuPosition(insertionPosition - 1, menuComponents.length)){ + if(menuComponents[insertionPosition - 1] instanceof JPopupMenu.Separator){ + return false; + } + } + break; + } + } + + return true; + } + + /** + * @param position menu position + * @param menuItems menu items + * @return true if the given position is valid + */ + private boolean isValidMenuPosition(final int position, final int menuItems){ + return !(position < 0 || position > (menuItems - 1)); + + } + + /** + * Performs the actual insertion of menu item. + * + * @param menuItemPosition is the specification of item's position + * @param menuItem is the item to be inserted + * @param parentMenu is the parent menu + * @param parentPopupMenu is the parent popupMenu + * @return the position to that has been the new menu item inserted + */ + private int insertItem(final MenuItemPosition menuItemPosition, + final JMenuItem menuItem, + final JMenu parentMenu, + final JPopupMenu parentPopupMenu) { + + int insertionPosition = -1; + + //insert menuItem to the position specified (exact position, FIRST, LAST possibilities) + if(MenuItemPosition.PlacementStyle.GROUPED.equals(menuItemPosition.getPlacementStyle())){ + final Component[] parentMenuItems; + if(parentMenu != null && parentPopupMenu == null){ + parentMenuItems = parentMenu.getMenuComponents(); + } + else if(parentMenu == null && parentPopupMenu != null){ + parentMenuItems = parentPopupMenu.getComponents(); + } + else { + LOG.error("Obscurity in menu item's parent."); + return -1; + } + + final int position = groupMenuItem(menuItem, parentMenuItems); + if(parentMenu != null){ + parentMenu.insert(menuItem, position); + } else { + parentPopupMenu.insert(menuItem, position); + } + + insertionPosition = position; + } + else if(menuItemPosition.getPosition() >= 0){ + if(parentMenu != null) { + final int position = Math.min(menuItemPosition.getPosition(), parentMenu.getItemCount()); + parentMenu.insert(menuItem, position); + insertionPosition = position; + } + else if(parentPopupMenu != null) { + final int position = Math.min(menuItemPosition.getPosition(), parentPopupMenu.getComponentCount()); + parentPopupMenu.insert(menuItem, position); + insertionPosition = position; + } + } else { + if(MenuItemPosition.PlacementStyle.FIRST.equals(menuItemPosition.getPlacementStyle())){ + if(parentMenu != null) { parentMenu.insert(menuItem, 0); } + else if(parentPopupMenu != null) { parentPopupMenu.insert(menuItem, 0); } + + insertionPosition = 0; + + } else if(MenuItemPosition.PlacementStyle.LAST.equals(menuItemPosition.getPlacementStyle())){ + if(parentMenu != null) { + parentMenu.add(menuItem); + insertionPosition = parentMenu.getMenuComponentCount() -1; + } + else if(parentPopupMenu != null) { + parentPopupMenu.add(menuItem); + insertionPosition = parentPopupMenu.getComponentCount() - 1; + } + } + } + + return insertionPosition; + } + + /** + * Finds the menu item(s) having the same text under the same parent menu item and returns the position + * (first possible) whether the new menu item is supposed to be inserted. + * + * @param menuItem is the menu item that is supposed to be inserted + * @param parentMenuItems are all current menu items + * @return the position where the new menu item is supposed to be inserted + */ + private int groupMenuItem(final JMenuItem menuItem, final Component[] parentMenuItems) { + for(int i = 0; i < parentMenuItems.length; i++){ + final Component component = parentMenuItems[i]; + + if(component instanceof JMenuItem){ + final JMenuItem item = (JMenuItem) component; + + if(item instanceof ModelerMenuItem && item.getText().equalsIgnoreCase(menuItem.getText())){ + return i; + } + } + } + + return parentMenuItems.length; + } + + private ModelerMenuItem getMenuItem(final boolean checkable) { + if(checkable){ + return new CheckableMenuItem(); + } else { + return new DefaultMenuItem(); + } + } + + /** + * Finds the duplicity in menu item names and prepare the 'relatives' mechanism. + * If there are more than one item having the same text on it, then the set if relatives is set to an empty + * set. The last item having the same text on it have this set filled by references on the previous items + * having the same text (relatives). All menu items that do not have any duplicity in text have this set set + * to null. + * + * @param parentPopupMenu is the parent popup menu item + * @param parentMenu is the parent menu item + * @param displayName is the text that is supposed to be displayed on the menu item + * @return the set holding references to the relatives, null if there is no text duplicity + * @throws IllegalArgumentException when an obscurity in parent occurs + */ + private List isUniqueMenuItemLabel( + final JPopupMenu parentPopupMenu, final JMenu parentMenu, final String displayName) throws IllegalArgumentException{ + + if(parentMenu != null && parentPopupMenu != null){ + LOG.error("There can be just one parent menu item for new menu item insertion."); + throw new IllegalArgumentException("Obscure parent menu item."); + } + + final Component[] menuComponents; + if(parentPopupMenu != null){ + menuComponents = parentPopupMenu.getComponents(); + } else { + assert parentMenu != null; + menuComponents = parentMenu.getMenuComponents(); + } + + List relatives = null; + + for(final Component component : menuComponents){ + if(component instanceof JMenuItem){ + final JMenuItem menuItem = (JMenuItem) component; + + if(displayName.equals(menuItem.getText())){ + if(menuItem instanceof ModelerMenuItem){ + final ModelerMenuItem modelerMenuItem = (ModelerMenuItem) menuItem; + + relatives = modelerMenuItem.getListOfRelatives(); + modelerMenuItem.setListOfRelatives(new LinkedList()); + + if(relatives == null){ + relatives = new LinkedList(); + } + + relatives.add(modelerMenuItem); + } + } + } + } + + return relatives; + } + + /** + * Inserts the menu item. + * + * @param menuLevelItems is the parent menu item + * @param placementParts is the hierarchical position + * @param proModAction is the action to be inserted + * @param parentMenu menu parent + * @param parentMenuBar menu bar + * @param parentPopupMenu parent popup menu + * @param menuSeparator menu separator info + * @param menuItemPosition menu item position info + * @param checkable true if the action is supposed to be checkable + * @return true id no error occurred, false otherwise + */ + private InsertMenuItemResult insertIntoMenu( + final JMenuItem[] menuLevelItems, + final String[] placementParts, + final ProModAction proModAction, + final JMenu parentMenu, + final JMenuBar parentMenuBar, + final JPopupMenu parentPopupMenu, + final MenuSeparator menuSeparator, + final MenuItemPosition menuItemPosition, + final boolean checkable) { + // parent has to be clear + if((parentMenu != null && parentMenuBar != null) + || (parentMenu != null && parentPopupMenu != null) + || (parentMenuBar != null && parentPopupMenu != null)){ + LOG.error("Obscurity in parent of menu item"); + throw new IllegalArgumentException("Obscure parent menu item."); + } + + if(proModAction == null){ + LOG.error("Nullary action to be inserted."); + return InsertMenuItemResult.UNDEFINED_ACTION; + } + + if(!ModelerSession.getActionControlService().isRegisteredAction(proModAction)){ + LOG.error("Unregistered action, action identifier: " + proModAction.getActionIdentifier()); + return InsertMenuItemResult.NOT_REGISTERED_ACTION; + } + + if(placementParts.length == 0){ + if(parentMenu != null){ + return insertAction(parentMenu, null, proModAction, menuSeparator, menuItemPosition, checkable); + } else if (parentPopupMenu != null){ + return insertAction(null, parentPopupMenu, proModAction, menuSeparator, menuItemPosition, checkable); + } else { + LOG.error("No parent set for the menu item."); + return InsertMenuItemResult.WRONG_PLACEMENT; + } + } else { + for (final JMenuItem menuItem : menuLevelItems) { + if (menuItem.getText().equals(placementParts[0])) { + if (menuItem instanceof JMenu) { + final JMenu menu = (JMenu) menuItem; + + final JMenuItem[] nextMenuItems = getMenuItems(menu); + + return insertIntoMenu( + nextMenuItems, + Arrays.copyOfRange(placementParts, 1, placementParts.length), + proModAction, + menu, + null, + null, + menuSeparator, + menuItemPosition, + checkable + ); + } + } + } + + JMenu parent = parentMenu; + for (final String placementPart : placementParts) { + final JMenu menu = ModelerSession.getComponentFactoryService().createMenu(placementPart); + + if (parent != null) { + parent.add(menu); + } else if (parentMenuBar != null) { + parentMenuBar.add(menu); + } else if (parentPopupMenu != null) { + parentPopupMenu.add(menu); + } else { + LOG.error("There is no parent set to build the menu structure."); + throw new IllegalArgumentException("Obscure parent menu item."); + } + + parent = menu; + } + + return insertAction(parent, null, proModAction, menuSeparator, menuItemPosition, checkable); + } + } + + } diff --git a/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuService.java b/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuService.java index 8f84ab4..60380d2 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/menuService/MenuService.java @@ -1,255 +1,255 @@ -package cz.cvut.promod.services.menuService; - -import cz.cvut.promod.services.Service; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import cz.cvut.promod.services.menuService.utils.MenuItemPosition; -import cz.cvut.promod.services.menuService.utils.InsertMenuItemResult; - - -import javax.swing.*; - - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:45:27, 10.10.2009 - */ - -/** - * Menu Service allows developer to insert items into the main menu, project tree navigation popup menu - * or notation specific menus. - */ -public interface MenuService extends Service{ - - // Separator for hierarchical placement of menu items, e.g. "File;Export;Image" - public static final String PLACEMENT_DELIMITER = ";"; - - - // Determines whether a menu separator is supposed to be inserted (before or after a menu item) or not. - public static enum MenuSeparator { - AFTER, // insert menu separator before the item - BEFORE, // insert menu separator after the item - NONE // do not insert menu separator - } - - /** - * Inserts a new action to the main menu structure. - * - * @param proModAction is the action that will be triggered by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. Hierarchical position cannot be null or an empty string for main menu. - * - * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition - * - * @param menuSeparator determines whether a menu separator is supposed to be inserted after or before the menu - * item or not - * - * @param checkable if true, than the menu item is designated to be selectable (has a small checkbox) - * - * @return an value from InsertMenuItemResults enumeration - * - * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values - * and their meanings - */ - public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator, - final boolean checkable); - - /** - * Inserts a new action to the main menu structure. This menu item won't be checkable (does not have the little - * checkbox on it). - * - * @param proModAction is the action that will be triggered by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. Hierarchical position cannot be null or an empty string for main menu. - * - * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition - * - * @param menuSeparator determines whether a menu separator is supposed to be inserted after or before the menu - * item or not - * - * @return an value from InsertMenuItemResults enumeration - * - * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values - * and their meanings - */ - public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator); - - /** - * Inserts a new action to the main menu structure without any menu separator. - * - * @param proModAction is the action that will be triggered by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. Hierarchical position cannot be null or an empty string for main menu. - * - * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition - * - * @param checkable if true, than the menu item is designated to be selectable (has a small checkbox) - * - * @return an value from InsertMenuItemResults enumeration - * - * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values - * and their meanings - */ - public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final boolean checkable); - - /** - * Inserts a new action to the main menu structure without any menu separator. - * This menu item won't be checkable (does not have the little checkbox on it). - * - * @param proModAction is the action that will be triggered by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. Hierarchical position cannot be null or an empty string for main menu. - * - * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition - * - * @return an value from InsertMenuItemResults enumeration - * - * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values - * and their meanings - */ - public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition); - - - /** - * Inserts new action to the project navigation tree popup menu. - * This menu is invoked anytime the right mouse button is clicked on any items in the project navigation tree. - * - * @param proModAction that will be triggered when by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted - * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). - * - * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition - * - * @param menuSeparator insert any possible value (see InsertMenuSeparator enum) or null - * - * @return an value from InsertMenuItemResults enumeration - * - * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values - * and their meanings - */ - public InsertMenuItemResult insertProjectNavigationPopupMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator); - - /** - * Inserts new action to the project navigation tree popup menu without any menu separator. - * This menu is invoked anytime the right mouse button is clicked on any items in the project navigation tree. - * - * @param proModAction that will be triggered when by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted - * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). - * - * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition - * - * @return an value from InsertMenuItemResults enumeration - * - * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values - * and their meanings - */ - public InsertMenuItemResult insertProjectNavigationPopupMenuItem(final ProModAction proModAction, - final MenuItemPosition menuItemPosition); - - - /** - * Inserts new action to the notation specific popup menu. - * Not all notations support the popup menu feature. - * - * @param notationIdentifier is the identifier of notation to which popup menu is the menu item (action) - * supposed to be inserted. When one specifies the identifier of Modeler, the menu item will be the inserted - * into the project navigation tree popup menu. - * - * @param proModAction that will be triggered when by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted - * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). - * - * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition - * - * @param menuSeparator insert any possible value (see InsertMenuSeparator enum) or null - * - * @return an value from InsertMenuItemResults enumeration - * - * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values - * and their meanings - */ - public InsertMenuItemResult insertPopupMenuItem(final String notationIdentifier, - final ProModAction proModAction, - final MenuItemPosition menuItemPosition, - final MenuSeparator menuSeparator); - - /** - * Inserts new action to the notation specific popup menu without any menu separator. - * Not all notations support the popup menu feature. - * - * @param notationIdentifier is the identifier of notation to which popup menu is the menu item (action) - * supposed to be inserted. When one specifies the identifier of Modeler, the menu item will be the inserted - * into the project navigation tree popup menu. - * - * @param proModAction that will be triggered when by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted - * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). - * - * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition - * - * @return an value from InsertMenuItemResults enumeration - * - * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values - * and their meanings - */ - public InsertMenuItemResult insertPopupMenuItem(final String notationIdentifier, - final ProModAction proModAction, - final MenuItemPosition menuItemPosition); - /* - * Inserts a new action into given popup menu. This function can be used by notation using JIDE to handle their - * popup menus. - * - * @param parentMenu is the parent menu item of added action - * - * @param parentPopupMenu the popup menu to be extended by defined action - * - * @param proModAction that will be triggered when by the menu item, the action has to be registered by the - * ActionService before, promod action cannot have an empty string as it's name (text). - * - * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position - * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted - * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). - * - * @param checkable determines whether the menu item will be checkable or not - * - * @return an information about inserting success - */ - public InsertMenuItemResult insertAction(final JMenu parentMenu, - final JPopupMenu parentPopupMenu, - final ProModAction proModAction, - final MenuSeparator menuSeparator, - final MenuItemPosition menuItemPosition, - final boolean checkable); - - -} +package cz.cvut.promod.services.menuService; + +import cz.cvut.promod.services.Service; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import cz.cvut.promod.services.menuService.utils.MenuItemPosition; +import cz.cvut.promod.services.menuService.utils.InsertMenuItemResult; + + +import javax.swing.*; + + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:45:27, 10.10.2009 + */ + +/** + * Menu Service allows developer to insert items into the main menu, project tree navigation popup menu + * or notation specific menus. + */ +public interface MenuService extends Service{ + + // Separator for hierarchical placement of menu items, e.g. "File;Export;Image" + public static final String PLACEMENT_DELIMITER = ";"; + + + // Determines whether a menu separator is supposed to be inserted (before or after a menu item) or not. + public static enum MenuSeparator { + AFTER, // insert menu separator before the item + BEFORE, // insert menu separator after the item + NONE // do not insert menu separator + } + + /** + * Inserts a new action to the main menu structure. + * + * @param proModAction is the action that will be triggered by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. Hierarchical position cannot be null or an empty string for main menu. + * + * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition + * + * @param menuSeparator determines whether a menu separator is supposed to be inserted after or before the menu + * item or not + * + * @param checkable if true, than the menu item is designated to be selectable (has a small checkbox) + * + * @return an value from InsertMenuItemResults enumeration + * + * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values + * and their meanings + */ + public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator, + final boolean checkable); + + /** + * Inserts a new action to the main menu structure. This menu item won't be checkable (does not have the little + * checkbox on it). + * + * @param proModAction is the action that will be triggered by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. Hierarchical position cannot be null or an empty string for main menu. + * + * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition + * + * @param menuSeparator determines whether a menu separator is supposed to be inserted after or before the menu + * item or not + * + * @return an value from InsertMenuItemResults enumeration + * + * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values + * and their meanings + */ + public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator); + + /** + * Inserts a new action to the main menu structure without any menu separator. + * + * @param proModAction is the action that will be triggered by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. Hierarchical position cannot be null or an empty string for main menu. + * + * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition + * + * @param checkable if true, than the menu item is designated to be selectable (has a small checkbox) + * + * @return an value from InsertMenuItemResults enumeration + * + * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values + * and their meanings + */ + public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final boolean checkable); + + /** + * Inserts a new action to the main menu structure without any menu separator. + * This menu item won't be checkable (does not have the little checkbox on it). + * + * @param proModAction is the action that will be triggered by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. Hierarchical position cannot be null or an empty string for main menu. + * + * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition + * + * @return an value from InsertMenuItemResults enumeration + * + * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values + * and their meanings + */ + public InsertMenuItemResult insertMainMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition); + + + /** + * Inserts new action to the project navigation tree popup menu. + * This menu is invoked anytime the right mouse button is clicked on any items in the project navigation tree. + * + * @param proModAction that will be triggered when by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted + * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). + * + * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition + * + * @param menuSeparator insert any possible value (see InsertMenuSeparator enum) or null + * + * @return an value from InsertMenuItemResults enumeration + * + * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values + * and their meanings + */ + public InsertMenuItemResult insertProjectNavigationPopupMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator); + + /** + * Inserts new action to the project navigation tree popup menu without any menu separator. + * This menu is invoked anytime the right mouse button is clicked on any items in the project navigation tree. + * + * @param proModAction that will be triggered when by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted + * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). + * + * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition + * + * @return an value from InsertMenuItemResults enumeration + * + * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values + * and their meanings + */ + public InsertMenuItemResult insertProjectNavigationPopupMenuItem(final ProModAction proModAction, + final MenuItemPosition menuItemPosition); + + + /** + * Inserts new action to the notation specific popup menu. + * Not all notations support the popup menu feature. + * + * @param notationIdentifier is the identifier of notation to which popup menu is the menu item (action) + * supposed to be inserted. When one specifies the identifier of Modeler, the menu item will be the inserted + * into the project navigation tree popup menu. + * + * @param proModAction that will be triggered when by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted + * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). + * + * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition + * + * @param menuSeparator insert any possible value (see InsertMenuSeparator enum) or null + * + * @return an value from InsertMenuItemResults enumeration + * + * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values + * and their meanings + */ + public InsertMenuItemResult insertPopupMenuItem(final String notationIdentifier, + final ProModAction proModAction, + final MenuItemPosition menuItemPosition, + final MenuSeparator menuSeparator); + + /** + * Inserts new action to the notation specific popup menu without any menu separator. + * Not all notations support the popup menu feature. + * + * @param notationIdentifier is the identifier of notation to which popup menu is the menu item (action) + * supposed to be inserted. When one specifies the identifier of Modeler, the menu item will be the inserted + * into the project navigation tree popup menu. + * + * @param proModAction that will be triggered when by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted + * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). + * + * @see cz.cvut.promod.services.menuService.utils.MenuItemPosition + * + * @return an value from InsertMenuItemResults enumeration + * + * @see cz.cvut.promod.services.menuService.utils.InsertMenuItemResult for more details about return values + * and their meanings + */ + public InsertMenuItemResult insertPopupMenuItem(final String notationIdentifier, + final ProModAction proModAction, + final MenuItemPosition menuItemPosition); + /* + * Inserts a new action into given popup menu. This function can be used by notation using JIDE to handle their + * popup menus. + * + * @param parentMenu is the parent menu item of added action + * + * @param parentPopupMenu the popup menu to be extended by defined action + * + * @param proModAction that will be triggered when by the menu item, the action has to be registered by the + * ActionService before, promod action cannot have an empty string as it's name (text). + * + * @param menuItemPosition is an instance of MenuItemPosition specifying hierarchical, absolute or relative position + * of the menu item in menu. An empty string in hierarchical position means that the menu item will be inserted + * into the root of the popup menu (menu item that are immediately visible when the popup menu is shown). + * + * @param checkable determines whether the menu item will be checkable or not + * + * @return an information about inserting success + */ + public InsertMenuItemResult insertAction(final JMenu parentMenu, + final JPopupMenu parentPopupMenu, + final ProModAction proModAction, + final MenuSeparator menuSeparator, + final MenuItemPosition menuItemPosition, + final boolean checkable); + + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/CheckableMenuItem.java b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/CheckableMenuItem.java index 8028636..b3353f0 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/CheckableMenuItem.java +++ b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/CheckableMenuItem.java @@ -1,29 +1,29 @@ -package cz.cvut.promod.services.menuService.utils; - -import javax.swing.*; -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:25:00, 30.10.2009 - */ - -/** - * Is the implementation of checkable menu item (has a small checkbox) of menu item in ProMod. - */ -public class CheckableMenuItem extends JCheckBoxMenuItem implements ModelerMenuItem { - - private List relatives = null; - - - /** {@inheritDoc} */ - public List getListOfRelatives() { - return relatives; - } - - /** {@inheritDoc} */ - public void setListOfRelatives(final List relatives) { - this.relatives = relatives; - } -} +package cz.cvut.promod.services.menuService.utils; + +import javax.swing.*; +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:25:00, 30.10.2009 + */ + +/** + * Is the implementation of checkable menu item (has a small checkbox) of menu item in ProMod. + */ +public class CheckableMenuItem extends JCheckBoxMenuItem implements ModelerMenuItem { + + private List relatives = null; + + + /** {@inheritDoc} */ + public List getListOfRelatives() { + return relatives; + } + + /** {@inheritDoc} */ + public void setListOfRelatives(final List relatives) { + this.relatives = relatives; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/DefaultMenuItem.java b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/DefaultMenuItem.java index 24e6200..a5cf253 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/DefaultMenuItem.java +++ b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/DefaultMenuItem.java @@ -1,29 +1,29 @@ -package cz.cvut.promod.services.menuService.utils; - -import javax.swing.*; -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 18:11:38, 12.10.2009 - */ - -/** - * Is the implementation of uncheckable menu item (does not have a small checkbox) of menu item in ProMod. - */ -public class DefaultMenuItem extends JMenuItem implements ModelerMenuItem { - - private List relatives = null; - - - /** {@inheritDoc} */ - public List getListOfRelatives() { - return relatives; - } - - /** {@inheritDoc} */ - public void setListOfRelatives(final List relatives) { - this.relatives = relatives; - } -} +package cz.cvut.promod.services.menuService.utils; + +import javax.swing.*; +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 18:11:38, 12.10.2009 + */ + +/** + * Is the implementation of uncheckable menu item (does not have a small checkbox) of menu item in ProMod. + */ +public class DefaultMenuItem extends JMenuItem implements ModelerMenuItem { + + private List relatives = null; + + + /** {@inheritDoc} */ + public List getListOfRelatives() { + return relatives; + } + + /** {@inheritDoc} */ + public void setListOfRelatives(final List relatives) { + this.relatives = relatives; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/InsertMenuItemResult.java b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/InsertMenuItemResult.java index 0ca9be0..233687c 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/InsertMenuItemResult.java +++ b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/InsertMenuItemResult.java @@ -1,52 +1,52 @@ -package cz.cvut.promod.services.menuService.utils; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 10:53:22, 2.2.2010 - */ - -/** - * Possible results for inserting methods defined in MenuService. - */ -public enum InsertMenuItemResult { - - /** - * Menu item has been successfully inserted. - */ - SUCCESS, - - /** - * The action that was supposed to be inserted into the menu was not registered - * by the ActionService. All actions inserted by the methods defined in MenuService into - * any menu has been registered by the ActionService. - */ - NOT_REGISTERED_ACTION, - - /** - * Illegal or not valid placement information. - * Note, that for inserting menu items into the main menu the hierarchical position cannot be an empty string, but - * when one inserts menu items to the popup menus, the first level of this popup menu (visible immediately - * when the popup menu is shown) and then an empty string in hierarchical position is expected. - */ - WRONG_PLACEMENT, - - /** - * Popup menu for required notation is not available. Possible reasons are that there is not such a notation - * with given identifier or the notation doesn't support popup menu feature. - */ - POPUP_NOT_SUPPORTED, - - /** - * Undefined action cannot be inserted into any menu. The action cannot be null and the action name (text) - * cannot be null or an empty string. - */ - UNDEFINED_ACTION, - - /** - * It is not possible to insert two same actions (to comparison is used mark ==, so the references are compared), - * under one parent into any menu. So for example it is not possible to insert the same action twice under menu - * "File", etc. When this kind of situation occur that this error state is returned. - */ - DUPLICIT_ACTION -} +package cz.cvut.promod.services.menuService.utils; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 10:53:22, 2.2.2010 + */ + +/** + * Possible results for inserting methods defined in MenuService. + */ +public enum InsertMenuItemResult { + + /** + * Menu item has been successfully inserted. + */ + SUCCESS, + + /** + * The action that was supposed to be inserted into the menu was not registered + * by the ActionService. All actions inserted by the methods defined in MenuService into + * any menu has been registered by the ActionService. + */ + NOT_REGISTERED_ACTION, + + /** + * Illegal or not valid placement information. + * Note, that for inserting menu items into the main menu the hierarchical position cannot be an empty string, but + * when one inserts menu items to the popup menus, the first level of this popup menu (visible immediately + * when the popup menu is shown) and then an empty string in hierarchical position is expected. + */ + WRONG_PLACEMENT, + + /** + * Popup menu for required notation is not available. Possible reasons are that there is not such a notation + * with given identifier or the notation doesn't support popup menu feature. + */ + POPUP_NOT_SUPPORTED, + + /** + * Undefined action cannot be inserted into any menu. The action cannot be null and the action name (text) + * cannot be null or an empty string. + */ + UNDEFINED_ACTION, + + /** + * It is not possible to insert two same actions (to comparison is used mark ==, so the references are compared), + * under one parent into any menu. So for example it is not possible to insert the same action twice under menu + * "File", etc. When this kind of situation occur that this error state is returned. + */ + DUPLICIT_ACTION +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/MenuItemPosition.java b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/MenuItemPosition.java index 7d8ac64..664a8d6 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/MenuItemPosition.java +++ b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/MenuItemPosition.java @@ -1,163 +1,163 @@ -package cz.cvut.promod.services.menuService.utils; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:46:34, 2.2.2010 - */ - -/** - * Specifies the menu item hierarchical and relative or absolute position in menu. - */ -public final class MenuItemPosition{ - - private static final Logger LOG = Logger.getLogger(MenuItemPosition.class); - - /** - * Specifies relative menu item position - */ - public static enum PlacementStyle { - /** First item in menu. */ - FIRST, - - /** Last item in menu. */ - LAST, - - /** Group menu item having the same text. Last if there is no name duplicity. */ - GROUPED - } - - private final PositionInfo positionInfo; - private final String hierarchicalPlacement; - - /** - * Constructs new MenuItemPosition holding hierarchical placement information. - * - * @param hierarchicalPlacement is the info about hierarchical position for new menu item - */ - public MenuItemPosition(final String hierarchicalPlacement){ - positionInfo = new PositionInfo(); - this.hierarchicalPlacement = hierarchicalPlacement; - } - - /** - * Constructs new MenuItemPosition holding hierarchical placement information and relative position. - * - * @param hierarchicalPlacement is the info about hierarchical position for new menu item - * - * @param placementStyle defines relative menu item position in the menu - */ - public MenuItemPosition(final String hierarchicalPlacement, final PlacementStyle placementStyle){ - this(hierarchicalPlacement); - - positionInfo.setRelativePosition(placementStyle); - } - - /** - * Constructs new MenuItemPosition holding hierarchical placement information and absolute position. - * - * @param hierarchicalPlacement is the info about hierarchical position for new menu item - * - * @param position defines absolute menu item position in the menu - */ - public MenuItemPosition(final String hierarchicalPlacement, final int position){ - this(hierarchicalPlacement); - - if(position < 0){ - LOG.error("Wrong menu position for menu item. Position has been set to zero."); - positionInfo.setPosition(0); - } else { - positionInfo.setPosition(position); - } - } - - /** - * Returns required hierarchical placement information. - * - * @return hierarchical placement information - */ - public String getHierarchicalPlacement() { - return hierarchicalPlacement; - } - - /** - * Returns absolute position for menu item. - * - * @return absolute position - */ - public int getPosition() { - return positionInfo.getAbsolutePosition(); - } - - /** - * Returns relative position for menu item. - * - * @return relative position - */ - public PlacementStyle getPlacementStyle() { - return positionInfo.getRelativePosition(); - } - - /** - * Returns information about relative and/or absolute position. - * - * @return information about relative and/or absolute position - */ - public PositionInfo getPositionInfo() { - return positionInfo; - } - - /** - * Holds the absolute and/or relative position information. - */ - public static final class PositionInfo{ - - /** - * If position > 0 -> then use position (absolute positioning), else use placementStyle (relative positioning) - */ - private int position = -1; - - /** - * Relative positioning. - */ - private PlacementStyle placementStyle = PlacementStyle.LAST; - - /** - * Returns absolute positioning information. - * - * @return absolute positioning information - */ - public int getAbsolutePosition() { - return position; - } - - /** - * Returns relative positioning information. - * - * @return relative positioning information - */ - public PlacementStyle getRelativePosition() { - return placementStyle; - } - - /** - * Sets absolute positioning information. - * - * @param position is the new absolute position - */ - public void setPosition(final int position) { - this.position = position; - } - - /** - * Sets relative positioning information. - * - * @param placementStyle is the new relative position - */ - public void setRelativePosition(final PlacementStyle placementStyle) { - this.placementStyle = placementStyle; - } - } -} +package cz.cvut.promod.services.menuService.utils; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:46:34, 2.2.2010 + */ + +/** + * Specifies the menu item hierarchical and relative or absolute position in menu. + */ +public final class MenuItemPosition{ + + private static final Logger LOG = Logger.getLogger(MenuItemPosition.class); + + /** + * Specifies relative menu item position + */ + public static enum PlacementStyle { + /** First item in menu. */ + FIRST, + + /** Last item in menu. */ + LAST, + + /** Group menu item having the same text. Last if there is no name duplicity. */ + GROUPED + } + + private final PositionInfo positionInfo; + private final String hierarchicalPlacement; + + /** + * Constructs new MenuItemPosition holding hierarchical placement information. + * + * @param hierarchicalPlacement is the info about hierarchical position for new menu item + */ + public MenuItemPosition(final String hierarchicalPlacement){ + positionInfo = new PositionInfo(); + this.hierarchicalPlacement = hierarchicalPlacement; + } + + /** + * Constructs new MenuItemPosition holding hierarchical placement information and relative position. + * + * @param hierarchicalPlacement is the info about hierarchical position for new menu item + * + * @param placementStyle defines relative menu item position in the menu + */ + public MenuItemPosition(final String hierarchicalPlacement, final PlacementStyle placementStyle){ + this(hierarchicalPlacement); + + positionInfo.setRelativePosition(placementStyle); + } + + /** + * Constructs new MenuItemPosition holding hierarchical placement information and absolute position. + * + * @param hierarchicalPlacement is the info about hierarchical position for new menu item + * + * @param position defines absolute menu item position in the menu + */ + public MenuItemPosition(final String hierarchicalPlacement, final int position){ + this(hierarchicalPlacement); + + if(position < 0){ + LOG.error("Wrong menu position for menu item. Position has been set to zero."); + positionInfo.setPosition(0); + } else { + positionInfo.setPosition(position); + } + } + + /** + * Returns required hierarchical placement information. + * + * @return hierarchical placement information + */ + public String getHierarchicalPlacement() { + return hierarchicalPlacement; + } + + /** + * Returns absolute position for menu item. + * + * @return absolute position + */ + public int getPosition() { + return positionInfo.getAbsolutePosition(); + } + + /** + * Returns relative position for menu item. + * + * @return relative position + */ + public PlacementStyle getPlacementStyle() { + return positionInfo.getRelativePosition(); + } + + /** + * Returns information about relative and/or absolute position. + * + * @return information about relative and/or absolute position + */ + public PositionInfo getPositionInfo() { + return positionInfo; + } + + /** + * Holds the absolute and/or relative position information. + */ + public static final class PositionInfo{ + + /** + * If position > 0 -> then use position (absolute positioning), else use placementStyle (relative positioning) + */ + private int position = -1; + + /** + * Relative positioning. + */ + private PlacementStyle placementStyle = PlacementStyle.LAST; + + /** + * Returns absolute positioning information. + * + * @return absolute positioning information + */ + public int getAbsolutePosition() { + return position; + } + + /** + * Returns relative positioning information. + * + * @return relative positioning information + */ + public PlacementStyle getRelativePosition() { + return placementStyle; + } + + /** + * Sets absolute positioning information. + * + * @param position is the new absolute position + */ + public void setPosition(final int position) { + this.position = position; + } + + /** + * Sets relative positioning information. + * + * @param placementStyle is the new relative position + */ + public void setRelativePosition(final PlacementStyle placementStyle) { + this.placementStyle = placementStyle; + } + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/ModelerMenuItem.java b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/ModelerMenuItem.java index 00d8cff..c6370b0 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/ModelerMenuItem.java +++ b/IndependentModeler/src/cz/cvut/promod/services/menuService/utils/ModelerMenuItem.java @@ -1,36 +1,36 @@ -package cz.cvut.promod.services.menuService.utils; - -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:22:36, 30.10.2009 - */ - -/** - * Class that is a base class for all items in menus. - */ -public interface ModelerMenuItem { - - /** - * Returns the list of relative items. Relives are all items in menu that have the same name (text). - * All relatives return empty list (but not nullary), but one returns list containing references to all - * other relative items (to make it possible to set them not visible). - * - * @return If the item is supposed to be hidden when not related notation is selected, than this methods - * return an empty list, if it has no relatives then returns null, and if this is the item that is supposed - * to be shown (event if it is disabled anyway) that it returns the non empty list of relatives. - */ - public List getListOfRelatives(); - - /** - * Sets the list of relative items. Relives are all items in menu that have the same name (text). - * All relatives return empty list (but not nullary), but one returns list containing references to all - * other relative items (to make it possible to set them not visible). - * - * @param relatives is the list of relatives - */ - public void setListOfRelatives(List relatives); - -} +package cz.cvut.promod.services.menuService.utils; + +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:22:36, 30.10.2009 + */ + +/** + * Class that is a base class for all items in menus. + */ +public interface ModelerMenuItem { + + /** + * Returns the list of relative items. Relives are all items in menu that have the same name (text). + * All relatives return empty list (but not nullary), but one returns list containing references to all + * other relative items (to make it possible to set them not visible). + * + * @return If the item is supposed to be hidden when not related notation is selected, than this methods + * return an empty list, if it has no relatives then returns null, and if this is the item that is supposed + * to be shown (event if it is disabled anyway) that it returns the non empty list of relatives. + */ + public List getListOfRelatives(); + + /** + * Sets the list of relative items. Relives are all items in menu that have the same name (text). + * All relatives return empty list (but not nullary), but one returns list containing references to all + * other relative items (to make it possible to set them not visible). + * + * @param relatives is the list of relatives + */ + public void setListOfRelatives(List relatives); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/notationService/NotationService.java b/IndependentModeler/src/cz/cvut/promod/services/notationService/NotationService.java index a27de88..a837fc7 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/notationService/NotationService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/notationService/NotationService.java @@ -1,99 +1,99 @@ -package cz.cvut.promod.services.notationService; - -import cz.cvut.promod.services.Service; -import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; -import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModel; - -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:47:34, 10.10.2009 - */ - -/** - * Notation Service is a access point to all loaded notations and their related modules. - */ -public interface NotationService extends Service{ - - /** - * Returns a list of all notations. - * - * @return list of all notations - */ - public List getNotations(); - - /** - * Returns a list of all notation's identifiers. - * - * @return a list of all notation's identifiers - */ - public List getNotationsIdentifiers(); - - /** - * Returns a notation having the identifier specified. - * - * @param notationIdentifier is the plugin identifier of required notation - * - * @return a notation having the identifier specified or null if there is no such a notation - */ - public Notation getNotation(final String notationIdentifier); - - /** - * Returns an instance of NotationSpecificPlugins class containing the notation that is specified by the - * identifier and all modules related to this notation. - * - * @param notationIdentifier is the identifier of the notation - * - * @return an object holding the notation and all it's modules - */ - public NotationSpecificPlugins getNotationSpecificPlugins(final String notationIdentifier); - - /** - * Creates an empty notation specific diagram model. This model holds diagram specific information (graphical and - * other information). - * - * @param notationIdentifier is the notation identifier that is supposed to create the empty diagram model - * - * @return an empty diagram model of a required notation, null if there is not such a notation - */ - public DiagramModel createEmptyNotationModel(final String notationIdentifier); - - /** - * Checks whether there exists such a notation. - * - * @param notationIdentifier is the identifier of notation - * - * @return true if there is such a notation, false otherwise - */ - public boolean existNotation(final String notationIdentifier); - - /** - * Returns the file extension of diagrams of a specified notation. - * - * @param notationIdentifier is the identifier of notation - * - * @return the diagram's file extension of a specified notation, null there is no such a notation - */ - public String getNotationFileExtension(final String notationIdentifier); - - /** - * Returns identifier of a notation on the basis of this notation's file extension. - * - * @param notationFileExtension is the file extension - * - * @return notation identifier related to the file extension, null if there is no such a notation - */ - public String getNotationIdentifier(final String notationFileExtension); - - /** - * Returns the error information that have occurred during loading. - * - * @return list holding error information - */ - public List getErrors(); - -} +package cz.cvut.promod.services.notationService; + +import cz.cvut.promod.services.Service; +import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; +import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModel; + +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:47:34, 10.10.2009 + */ + +/** + * Notation Service is a access point to all loaded notations and their related modules. + */ +public interface NotationService extends Service{ + + /** + * Returns a list of all notations. + * + * @return list of all notations + */ + public List getNotations(); + + /** + * Returns a list of all notation's identifiers. + * + * @return a list of all notation's identifiers + */ + public List getNotationsIdentifiers(); + + /** + * Returns a notation having the identifier specified. + * + * @param notationIdentifier is the plugin identifier of required notation + * + * @return a notation having the identifier specified or null if there is no such a notation + */ + public Notation getNotation(final String notationIdentifier); + + /** + * Returns an instance of NotationSpecificPlugins class containing the notation that is specified by the + * identifier and all modules related to this notation. + * + * @param notationIdentifier is the identifier of the notation + * + * @return an object holding the notation and all it's modules + */ + public NotationSpecificPlugins getNotationSpecificPlugins(final String notationIdentifier); + + /** + * Creates an empty notation specific diagram model. This model holds diagram specific information (graphical and + * other information). + * + * @param notationIdentifier is the notation identifier that is supposed to create the empty diagram model + * + * @return an empty diagram model of a required notation, null if there is not such a notation + */ + public DiagramModel createEmptyNotationModel(final String notationIdentifier); + + /** + * Checks whether there exists such a notation. + * + * @param notationIdentifier is the identifier of notation + * + * @return true if there is such a notation, false otherwise + */ + public boolean existNotation(final String notationIdentifier); + + /** + * Returns the file extension of diagrams of a specified notation. + * + * @param notationIdentifier is the identifier of notation + * + * @return the diagram's file extension of a specified notation, null there is no such a notation + */ + public String getNotationFileExtension(final String notationIdentifier); + + /** + * Returns identifier of a notation on the basis of this notation's file extension. + * + * @param notationFileExtension is the file extension + * + * @return notation identifier related to the file extension, null if there is no such a notation + */ + public String getNotationIdentifier(final String notationFileExtension); + + /** + * Returns the error information that have occurred during loading. + * + * @return list holding error information + */ + public List getErrors(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/notationService/NotationServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/notationService/NotationServiceImpl.java index 794a904..4e95642 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/notationService/NotationServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/notationService/NotationServiceImpl.java @@ -1,131 +1,131 @@ -package cz.cvut.promod.services.notationService; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.localIOController.NotationLocalIOController; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModel; -import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; -import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; - -import java.util.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:49:53, 10.10.2009 - */ - -/** - * NotationService implementation. - */ -public class NotationServiceImpl implements NotationService{ - - private final List notationSpecificPluginsList; - final List errors; - - public NotationServiceImpl(final List notationSpecificPluginsList, - final List errors) { - - this.notationSpecificPluginsList = notationSpecificPluginsList; - this.errors = errors; - } - - /** {@inheritDoc} */ - public boolean check() { - return true; - } - - /** {@inheritDoc} */ - public List getNotations() { - final List notations = new LinkedList(); - - for(final NotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ - notations.add(notationSpecificPlugins.getNotation()); - } - - return notations; - } - - /** {@inheritDoc} */ - public Notation getNotation(final String notationIdentifier) { - for(final NotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ - final Notation notation = notationSpecificPlugins.getNotation(); - - if(notation.getIdentifier().equals(notationIdentifier)){ - return notation; - } - } - - return null; - } - - /** {@inheritDoc} */ - public List getNotationsIdentifiers() { - final List identifiers = new LinkedList(); - - for(final NotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ - identifiers.add(notationSpecificPlugins.getNotation().getIdentifier()); - } - - return identifiers; - } - - /** {@inheritDoc} */ - public NotationSpecificPlugins getNotationSpecificPlugins(final String notationIdentifier) { - for(final NotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ - if(notationSpecificPlugins.getNotation().getIdentifier().equals(notationIdentifier)){ - return notationSpecificPlugins; - } - } - - return null; - } - - /** {@inheritDoc} */ - public DiagramModel createEmptyNotationModel(final String notationIdentifier){ - if(existNotation(notationIdentifier)){ - return getNotation(notationIdentifier).getDiagramModelFactory().createEmptyDiagramModel(); - } - - return null; - } - - /** {@inheritDoc} */ - public boolean existNotation(final String notationIdentifier) { - return getNotation(notationIdentifier) != null; - } - - public String getNotationFileExtension(final String notationIdentifier) { - final Notation notation = getNotation(notationIdentifier); - - if(notation != null){ - final NotationLocalIOController notationLocalIOController = notation.getLocalIOController(); - - if(notationLocalIOController != null){ - return notationLocalIOController.getNotationFileExtension(); - } - } - - return null; - } - - public String getNotationIdentifier(final String notationFileExtension) { - if(notationFileExtension == null){ - return null; - } - - for(final Notation notation : getNotations()){ - if(notation.getLocalIOController().getNotationFileExtension().equals(notationFileExtension)){ - return notation.getIdentifier(); - } - } - - return null; - } - - /** - * {@inheritDoc} - */ - public List getErrors() { - return errors; - } -} +package cz.cvut.promod.services.notationService; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.localIOController.NotationLocalIOController; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModel; +import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; +import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; + +import java.util.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:49:53, 10.10.2009 + */ + +/** + * NotationService implementation. + */ +public class NotationServiceImpl implements NotationService{ + + private final List notationSpecificPluginsList; + final List errors; + + public NotationServiceImpl(final List notationSpecificPluginsList, + final List errors) { + + this.notationSpecificPluginsList = notationSpecificPluginsList; + this.errors = errors; + } + + /** {@inheritDoc} */ + public boolean check() { + return true; + } + + /** {@inheritDoc} */ + public List getNotations() { + final List notations = new LinkedList(); + + for(final NotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ + notations.add(notationSpecificPlugins.getNotation()); + } + + return notations; + } + + /** {@inheritDoc} */ + public Notation getNotation(final String notationIdentifier) { + for(final NotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ + final Notation notation = notationSpecificPlugins.getNotation(); + + if(notation.getIdentifier().equals(notationIdentifier)){ + return notation; + } + } + + return null; + } + + /** {@inheritDoc} */ + public List getNotationsIdentifiers() { + final List identifiers = new LinkedList(); + + for(final NotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ + identifiers.add(notationSpecificPlugins.getNotation().getIdentifier()); + } + + return identifiers; + } + + /** {@inheritDoc} */ + public NotationSpecificPlugins getNotationSpecificPlugins(final String notationIdentifier) { + for(final NotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ + if(notationSpecificPlugins.getNotation().getIdentifier().equals(notationIdentifier)){ + return notationSpecificPlugins; + } + } + + return null; + } + + /** {@inheritDoc} */ + public DiagramModel createEmptyNotationModel(final String notationIdentifier){ + if(existNotation(notationIdentifier)){ + return getNotation(notationIdentifier).getDiagramModelFactory().createEmptyDiagramModel(); + } + + return null; + } + + /** {@inheritDoc} */ + public boolean existNotation(final String notationIdentifier) { + return getNotation(notationIdentifier) != null; + } + + public String getNotationFileExtension(final String notationIdentifier) { + final Notation notation = getNotation(notationIdentifier); + + if(notation != null){ + final NotationLocalIOController notationLocalIOController = notation.getLocalIOController(); + + if(notationLocalIOController != null){ + return notationLocalIOController.getNotationFileExtension(); + } + } + + return null; + } + + public String getNotationIdentifier(final String notationFileExtension) { + if(notationFileExtension == null){ + return null; + } + + for(final Notation notation : getNotations()){ + if(notation.getLocalIOController().getNotationFileExtension().equals(notationFileExtension)){ + return notation.getIdentifier(); + } + } + + return null; + } + + /** + * {@inheritDoc} + */ + public List getErrors() { + return errors; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/PluginLoaderService.java b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/PluginLoaderService.java index bd69a07..0b0179e 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/PluginLoaderService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/PluginLoaderService.java @@ -1,99 +1,99 @@ -package cz.cvut.promod.services.pluginLoaderService; - -import cz.cvut.promod.services.Service; -import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; -import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; -import cz.cvut.promod.services.pluginLoaderService.utils.PluginDetails; -import cz.cvut.promod.plugin.extension.Extension; - -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 21:56:10, 12.10.2009 - */ - -/** - * PluginLoaderService's responsibility is loading/instantiating of plugins specified in the ProMod plugin file. - * This class is not supposed to be used by plugin developers at all. - */ -public interface PluginLoaderService extends Service{ - - /** - * An identifier of a plugin is not supposed to be an empty string or it's length is not supposed to exceed this - * constant. - */ - public static final int MAX_PLUGIN_IDENTIFIER_LENGTH = 36; - - - /** - * Loads definition of plugins from the file. The file is validate against the xsd schema file. - * - * @param pluginDefinitionFile is the file path that is supposed to contain the plugin definitions - * - * @return true if no error has occurred, false otherwise - */ - public boolean loadPlugInsDefinition(final String pluginDefinitionFile); - - /** - * Returns loaded information from the plugin definition file related to the notations and modules. - * - * The returned list is NOT supposed to be changed in any way (insert, delete, edit). - * - * @return info about notations and modules specified in plugin definition file - */ - public List getNotationModulesInstInfo(); - - - /** - * Returns loaded information from the plugin definition file related to the extensions. - * - * The returned list is NOT supposed to be changed in any way (insert, delete, edit). - * - * @return info about extensions specified in plugin definition file - */ - public List getExtensionInstInfo(); - - /** - * Performs plugin instantiation. Results of this methods are then available by 'getters' of this service. - * Plugins that are not possible to instantiate or plugins that are not valid won't be available be getters. - * See error (using getErrors() method) to see why any plugins are missing. - */ - public void instantiatePlugins(); - - /** - * Returns list of instantiated notations and modules. This list respects the order of notations and modules as - * is defined by the definition in the plugin definition file. - * - * All notations and/or modules that do NOT fulfil all requirements are omitted from this list. - * - * The returned list is NOT supposed to be changed in any way (insert, delete, edit). - * - * @return list of instantiated notations and modules - */ - public List getNotationSpecificPlugins(); - - /** - * Returns list of instantiated extensions. This list respects the order of extensions like - * is defined by the definition in the plugin definition file. - * - * The returned list is NOT supposed to be changed in any way (insert, delete, edit). - * - * All extensions that do NOT fulfil all requirements are omitted from this list. - * - * @return list of instantiated extensions - */ - public List getExtensions(); - - /** - * Returns a list holding information about errors that has occurred during plugin loading and instantiating. - * The key is the alias defined in the plugin definition file. ProMod application doesn't require uniqueness for - * this aliases, but it is strongly recommended. Otherwise it is very difficult to analyze the error log. - * - * The returned list is NOT supposed to be changed in any way (insert, delete, edit). - * - * @return list errors - */ - public List getErrors(); -} +package cz.cvut.promod.services.pluginLoaderService; + +import cz.cvut.promod.services.Service; +import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; +import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; +import cz.cvut.promod.services.pluginLoaderService.utils.PluginDetails; +import cz.cvut.promod.plugin.extension.Extension; + +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 21:56:10, 12.10.2009 + */ + +/** + * PluginLoaderService's responsibility is loading/instantiating of plugins specified in the ProMod plugin file. + * This class is not supposed to be used by plugin developers at all. + */ +public interface PluginLoaderService extends Service{ + + /** + * An identifier of a plugin is not supposed to be an empty string or it's length is not supposed to exceed this + * constant. + */ + public static final int MAX_PLUGIN_IDENTIFIER_LENGTH = 36; + + + /** + * Loads definition of plugins from the file. The file is validate against the xsd schema file. + * + * @param pluginDefinitionFile is the file path that is supposed to contain the plugin definitions + * + * @return true if no error has occurred, false otherwise + */ + public boolean loadPlugInsDefinition(final String pluginDefinitionFile); + + /** + * Returns loaded information from the plugin definition file related to the notations and modules. + * + * The returned list is NOT supposed to be changed in any way (insert, delete, edit). + * + * @return info about notations and modules specified in plugin definition file + */ + public List getNotationModulesInstInfo(); + + + /** + * Returns loaded information from the plugin definition file related to the extensions. + * + * The returned list is NOT supposed to be changed in any way (insert, delete, edit). + * + * @return info about extensions specified in plugin definition file + */ + public List getExtensionInstInfo(); + + /** + * Performs plugin instantiation. Results of this methods are then available by 'getters' of this service. + * Plugins that are not possible to instantiate or plugins that are not valid won't be available be getters. + * See error (using getErrors() method) to see why any plugins are missing. + */ + public void instantiatePlugins(); + + /** + * Returns list of instantiated notations and modules. This list respects the order of notations and modules as + * is defined by the definition in the plugin definition file. + * + * All notations and/or modules that do NOT fulfil all requirements are omitted from this list. + * + * The returned list is NOT supposed to be changed in any way (insert, delete, edit). + * + * @return list of instantiated notations and modules + */ + public List getNotationSpecificPlugins(); + + /** + * Returns list of instantiated extensions. This list respects the order of extensions like + * is defined by the definition in the plugin definition file. + * + * The returned list is NOT supposed to be changed in any way (insert, delete, edit). + * + * All extensions that do NOT fulfil all requirements are omitted from this list. + * + * @return list of instantiated extensions + */ + public List getExtensions(); + + /** + * Returns a list holding information about errors that has occurred during plugin loading and instantiating. + * The key is the alias defined in the plugin definition file. ProMod application doesn't require uniqueness for + * this aliases, but it is strongly recommended. Otherwise it is very difficult to analyze the error log. + * + * The returned list is NOT supposed to be changed in any way (insert, delete, edit). + * + * @return list errors + */ + public List getErrors(); +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/PluginLoaderServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/PluginLoaderServiceImpl.java index aad8847..03c0cc9 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/PluginLoaderServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/PluginLoaderServiceImpl.java @@ -1,975 +1,975 @@ -package cz.cvut.promod.services.pluginLoaderService; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.localIOController.NotationLocalIOController; -import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; -import cz.cvut.promod.plugin.Plugin; -import cz.cvut.promod.plugin.extension.Extension; -import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; -import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; -import cz.cvut.promod.services.pluginLoaderService.utils.PluginDetails; -import cz.cvut.promod.services.pluginLoaderService.utils.ModifiableNotationSpecificPlugins; -import cz.cvut.promod.services.pluginLoaderService.errorHandling.PluginLoaderErrorHandler; -import cz.cvut.promod.services.projectService.ProjectService; -import cz.cvut.promod.gui.ModelerModel; -import cz.cvut.promod.resources.Resources; - -import java.util.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import org.apache.log4j.Logger; -import org.xml.sax.SAXException; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.w3c.dom.Node; -import org.w3c.dom.NamedNodeMap; - - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Source; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:09:56, 12.10.2009 - */ - -/** - * Implementation of PluginLoaderService. - */ -public class PluginLoaderServiceImpl implements PluginLoaderService { - - private final Logger LOG = Logger.getLogger(PluginLoaderServiceImpl.class); - - /** - * Specifies what kind of plugins is being loaded. - * Only for inner services purposes. - */ - private static enum LoadPlugInType { - NOTATIONS_AND_MODULES, - EXTENSION - } - - private final static String ROOT_TAG = "promod-plugins"; - private final static String NOTATION_TAG = "notation"; - private final static String MODULE_TAG = "module"; - private final static String EXTENSION_TAG = "extension"; - - private final static String CLASS_ATTRIBUTE = "class"; - private final static String CONFIG_ATTRIBUTE = "config"; - private final static String ALIAS_ATTRIBUTE = "alias"; - - private final static String NOTATION_INTERFACE_QUALIFIED_NAME= "cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation"; - private final static String MODULE_INTERFACE_QUALIFIED_NAME= "cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module"; - private final static String IOCONTROLPLUGIN_INTERFACE_QUALIFIED_NAME= "cz.cvut.promod.plugin.extension.Extension"; - - private final List notationDetails; - private final List extensionDetails; - - private final List notationSpecificPluginsList; - private final List extensionList; - - /** - * Holds all errors that occur during plugin loading, instantiating or preparing to use. - */ - private final List errorList; - - private final Class notationClass; - private final Class moduleClass; - private final Class extenderClass; - - - public PluginLoaderServiceImpl() throws ClassNotFoundException{ - errorList = new LinkedList(); - - notationDetails = new LinkedList(); - extensionDetails = new LinkedList(); - - notationSpecificPluginsList = new LinkedList(); - extensionList = new LinkedList(); - - notationClass = Class.forName(NOTATION_INTERFACE_QUALIFIED_NAME); - moduleClass = Class.forName(MODULE_INTERFACE_QUALIFIED_NAME); - extenderClass = Class.forName(IOCONTROLPLUGIN_INTERFACE_QUALIFIED_NAME); - } - - /** {@inheritDoc} - * - * Not valid XML file won't be loaded. - * - * If there will be any need to load not certainly valid files in the future, it could be enough to skip the - * XML validation. There are even error messages already prepared. - */ - public boolean loadPlugInsDefinition(final String pluginDefinitionFile){ - final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - - final InputStream schemaInputStream = ClassLoader.getSystemResourceAsStream( - Resources.CONFIG + Resources.PLUGINS_XSD_FILE - ); - - LOG.info("Validating plugin definition file against xsd file."); - - documentBuilderFactory.setNamespaceAware(true); - documentBuilderFactory.setValidating(false); - - final Schema schema; - final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - final Source source = new StreamSource(schemaInputStream); - try { - schema = schemaFactory.newSchema(source); - - } catch (SAXException e) { - LOG.info("Skipping plugin definition file validation."); - final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); - error.reportError(PluginLoadErrors.ERRORS.xmlParsing, errorList); - return false; - } - - final Document document; - - try { - final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - - documentBuilder.setErrorHandler(new PluginLoaderErrorHandler()); - - document = documentBuilder.parse(new File(pluginDefinitionFile)); - - final Validator validator = schema.newValidator(); - - validator.validate(new DOMSource(document)); - - } catch (ParserConfigurationException e) { - LOG.error("XML Parser configuration has failed.", e); - final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); - error.reportError(PluginLoadErrors.ERRORS.xmlParsing, e.getMessage(), errorList); - return false; - - } catch (IOException e) { - LOG.error("An IO error has occurred when reading the plugin info xml file.", e); - final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); - error.reportError(PluginLoadErrors.ERRORS.xmlParsing, e.getMessage(), errorList); - return false; - - } catch (SAXException e) { - LOG.error("An SAX error has occurred when reading the plugin info xml file.", e); - final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); - error.reportError(PluginLoadErrors.ERRORS.xmlParsing, e.getMessage(), errorList); - return false; - - } catch (NullPointerException exception){ - LOG.error("Nullary info about the plugin specification.", exception); - final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); - error.reportError(PluginLoadErrors.ERRORS.xmlParsing, exception.getMessage(), errorList); - return false; - } - - return document != null && loadPluginDetails(document); - } - - /** - * Loads plugin details = aliases, classes, config files and save this information for future use, - * - * @param document is the DOM document of plugin definition file containing plugin details - * - * @return true if no error occurs, false otherwise - */ - private boolean loadPluginDetails(final Document document){ - final NodeList rootNodeList = document.getElementsByTagName(ROOT_TAG); - if(rootNodeList.getLength() != 1){ - LOG.error("More than one (or missing) root node in plugin xml file."); - final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); - error.reportError(PluginLoadErrors.ERRORS.xmlParsing, errorList); - return false; - } - - final Node rootNode = rootNodeList.item(0); - - final NodeList nodeList = rootNode.getChildNodes(); - - for(int i = 0; i < nodeList.getLength(); i++){ - final Node notationNode = nodeList.item(i); - - if(notationNode.getNodeName().equals(NOTATION_TAG)){ - NamedNodeMap attributes = notationNode.getAttributes(); - - final PluginDetails notationDetail = new PluginDetails( - readAttribute(attributes.getNamedItem(CLASS_ATTRIBUTE)), - readAttribute(attributes.getNamedItem(CONFIG_ATTRIBUTE)), - readAttribute(attributes.getNamedItem(ALIAS_ATTRIBUTE)) - ); - - final NodeList moduleList = notationNode.getChildNodes(); - - for(int j = 0; j < moduleList.getLength(); j++){ - final Node moduleNode = moduleList.item(j); - - if(moduleNode.getNodeName().equals(MODULE_TAG)){ - attributes = moduleNode.getAttributes(); - - final PluginDetails moduleDetail = new PluginDetails( - readAttribute(attributes.getNamedItem(CLASS_ATTRIBUTE)), - readAttribute(attributes.getNamedItem(CONFIG_ATTRIBUTE)), - readAttribute(attributes.getNamedItem(ALIAS_ATTRIBUTE)) - ); - - notationDetail.addPluginDetails(moduleDetail); - } - } - - notationDetails.add(notationDetail); - - } else if(notationNode.getNodeName().equals(EXTENSION_TAG)){ - final NamedNodeMap attributes = notationNode.getAttributes(); - - final PluginDetails extensionDetail = new PluginDetails( - readAttribute(attributes.getNamedItem(CLASS_ATTRIBUTE)), - readAttribute(attributes.getNamedItem(CONFIG_ATTRIBUTE)), - readAttribute(attributes.getNamedItem(ALIAS_ATTRIBUTE)) - ); - - extensionDetails.add(extensionDetail); - } - } - - return true; - } - - /** {@inheritDoc} */ - public List getNotationModulesInstInfo() { - return Collections.unmodifiableList(notationDetails); - } - - /** {@inheritDoc} */ - public List getExtensionInstInfo() { - return Collections.unmodifiableList(extensionDetails); - } - - /** - * Reads node's attribute. - * - * @param node is the attribute node - * - * @return value of the attribute it exists, null otherwise - */ - private String readAttribute(final Node node){ - if(node != null){ - return node.getNodeValue(); - } - - return null; - } - - /** {@inheritDoc} */ - public void instantiatePlugins() { - instantiatePlugins(LoadPlugInType.NOTATIONS_AND_MODULES); - instantiatePlugins(LoadPlugInType.EXTENSION); - } - - /** - * Instantiate plugins accordingly to the information loaded from plugin configuration file and store this instances - * for future use. - * - * @param loadPlugInType is the type of plugins that are supposed to be instantiated - * - * @see cz.cvut.promod.services.pluginLoaderService.PluginLoaderServiceImpl.LoadPlugInType - */ - private void instantiatePlugins(LoadPlugInType loadPlugInType){ - final List pluginDetailsList; - Class plugInTypeInterface = null; - - pluginDetailsList = getRequiredList(loadPlugInType); - - if(pluginDetailsList == null){ - return; - } - - for(final PluginDetails details : pluginDetailsList){ - String notationIdentifier = null; // when modules are being loaded, this holds the related notation id. - - PluginDetails pluginDetail = details; - - switch (loadPlugInType){ - case NOTATIONS_AND_MODULES: - plugInTypeInterface = notationClass; - break; - case EXTENSION: - plugInTypeInterface = extenderClass; - break; - } - - do{ - final String alias = pluginDetail.getAlias(); - - if(alias == null || alias.isEmpty()) { - LOG.error("Skipping loading of an plugin - not provided alias."); - break; - } - - final PluginLoadErrors error = new PluginLoadErrors(alias); - - final String fullClassName = pluginDetail.getClazz(); - - if(!isValidClassName(fullClassName)){ - LOG.error("Due to error(s) skipping loading of plugin defined by '" + pluginDetail + "' property."); - error.reportError(PluginLoadErrors.ERRORS.className, errorList); - break; - } - - error.setFullClassName(fullClassName); // set the non empty and non nullary class name - - final Class clazz = getPluginClass(fullClassName); - if(clazz == null) { - LOG.error("Due to error(s) skipping loading of " + alias + "."); - error.reportError(PluginLoadErrors.ERRORS.findClass, errorList); - break; - } - - if(!implementsInterfaces(clazz, plugInTypeInterface)){ - LOG.error("Due to error(s) skipping loading of " + clazz.getName() + "."); - error.reportError(PluginLoadErrors.ERRORS.classHierarchy, errorList); - break; - } - - final Plugin plugin = instantiatePlugin( - clazz, pluginDetail, error, notationIdentifier, plugInTypeInterface == moduleClass); - if(plugin == null) { - LOG.error("Due to error(s) skipping loading of " + clazz.getName() + "."); - break; - } - - //save the loaded plugin - if(!storePluginObject(plugInTypeInterface, plugin, error)){ - LOG.error("Due to error(s) skipping loading of " + clazz.getName() + "."); - } - - // instantiate modules - pluginDetail = details.pop(); - plugInTypeInterface = moduleClass; - - // store temporarily the notation identifier for instantiating of it's related modules - if(plugin instanceof Notation && notationIdentifier == null){ - notationIdentifier = plugin.getIdentifier(); - } - - } while(pluginDetail != null); - } - } - - /** - * Return required list of plugin details. - * - * @param loadPlugInType is the type of plugins - * - * @return required list or null if any error occurs - */ - private List getRequiredList(final LoadPlugInType loadPlugInType) { - switch (loadPlugInType){ - case NOTATIONS_AND_MODULES: - return notationDetails; - case EXTENSION: - return extensionDetails; - default: - LOG.error("Unknown plugIn type has been recognized."); - } - - return null; - } - - /** - * Checks the qualified class name. - * - * @param fullClassName is the qualified class name - * @return true if the fullClassName is not null or an empty string, false otherwise - */ - private boolean isValidClassName(final String fullClassName) { - if(fullClassName == null){ - LOG.error("Nullary plugin class name."); - return false; - } - - if(fullClassName.isEmpty()){ - LOG.error("Empty plugin class name."); - return false; - } - - return true; - } - - /** - * Returns an instance of Class class representing the plugin class. - * - * @param fullClassName is the qualified name of the class - * - * @return in instance of Class if the plugin class definition is accessible, false otherwise - */ - private Class getPluginClass(final String fullClassName){ - final Class clazz; - try { - // get plugin class - clazz = Class.forName(fullClassName); - - } catch (ClassNotFoundException exception) { - LOG.error("Wrong pluIn class definition, " + fullClassName + ".", exception); - return null; - - } catch (NoClassDefFoundError error){ - LOG.error("Wrong pluIn class definition, " + fullClassName + ".", error); - return null; - - } catch(LinkageError error){ - LOG.error("Wrong pluIn class definition, " + fullClassName + ".", error); - return null; - } - - - return clazz; - } - - /** - * Checks whether the plugin implements necessary interfaces (Notation, Module, etc.). - * - * @param clazz that is supposed to implement an interface specified by the second argument - * @param plugInTypeInterface the plugin specific interface (Notation, Module, etc.) - * - * @return true if necessary the clazz implements necessary interface, false otherwise - */ - private boolean implementsInterfaces(final Class clazz, final Class plugInTypeInterface){ - boolean implementsRequiredInterface = false; - for(final Class implementedInterface : clazz.getInterfaces()){ - if(plugInTypeInterface == implementedInterface){ - implementsRequiredInterface = true; - break; - } - } - - if(!implementsRequiredInterface){ - LOG.error("Plugin ("+ clazz.getName() +") doesn't implement required notation + (" + plugInTypeInterface.getSimpleName() + ")."); - } - - return implementsRequiredInterface; - } - - /** - * Instantiate a class provided as a argument of this method. - * - * @param clazz definition of class to be instantiated - * @param pluginDetails holds info about the plugin that is supposed to be instantiated - * @param error to report errors - * @param notationIdentifier is the identifier of notation, used when modules are being instantiated - * @param isModule indicates if the module is going to be instantiated or not - * @return an object of the class (plugin) if no error occurs, null otherwise - */ - private Plugin instantiatePlugin(final Class clazz, - final PluginDetails pluginDetails, - final PluginLoadErrors error, - final String notationIdentifier, - final boolean isModule){ - try { - Plugin plugin; - - final String configFilePath = pluginDetails.getConfig(); - final File configFile; - - if(configFilePath != null){ - // use constructor taking a file as argument - - configFile = new File(configFilePath); - - if(!checkConfigFile(configFile, pluginDetails.getAlias())){ - LOG.error("Configuration data provided is not a valid file. Skipping plugin instantiation, " + pluginDetails.getAlias() + "."); - error.reportError(PluginLoadErrors.ERRORS.instantiation, errorList); - return null; - - } - } else { - configFile = null; - } - - Constructor moduleFileIdentifierConstructor = null; - Constructor moduleIdentifierConstructor = null; - Constructor fileConstructor = null; - - for(final Constructor constructor : clazz.getConstructors()){ - final Class[] parameters = constructor.getParameterTypes(); - - if(isModule){ - // try to find special constructors for modules - - if((parameters.length == 2) && parameters[0].equals(File.class) && parameters[1].equals(String.class)){ - moduleFileIdentifierConstructor = constructor; - } - else if((parameters.length == 1) && parameters[0].equals(String.class)){ - moduleIdentifierConstructor = constructor; - } - } - - if((parameters.length == 1) && parameters[0].equals(File.class)){ - fileConstructor = constructor; - } - } - - if(moduleFileIdentifierConstructor != null){ - plugin = (Plugin) moduleFileIdentifierConstructor.newInstance(configFile, notationIdentifier); - - } else if (moduleIdentifierConstructor != null){ - plugin = (Plugin) moduleIdentifierConstructor.newInstance(notationIdentifier); - - } else if(fileConstructor != null){ - // there is a required constructor - plugin = (Plugin) fileConstructor.newInstance(configFile); - - } else { - // configuration data not provided, use parameter-less constructor - plugin = (Plugin) clazz.newInstance(); - } - - return plugin; - - } catch (InstantiationException e) { - LOG.error("PluginLoaderService could not instantiate plugin object, full class name: " + clazz.getName() + "."); - error.reportError(PluginLoadErrors.ERRORS.instantiation, e.getMessage(), errorList); - - } catch (IllegalAccessException e) { - LOG.error("PluginLoaderService could not access parameter-less constructor of plugin, full class name: " + clazz.getName() + "."); - error.reportError(PluginLoadErrors.ERRORS.instantiation, e.getMessage(), errorList); - - } catch (InvocationTargetException e) { - LOG.error("Nullary constructor error.", e); - error.reportError(PluginLoadErrors.ERRORS.instantiation, e.getMessage(), errorList); - } - - return null; - } - - /** - * Stores instantiated plugin for future use. - * - * @param loadPlugInType is the plugin type - * @param plugin is the object of plugin - * @param error to report errors - * - * @return true if no error(s) occurred, false otherwise - */ - private boolean storePluginObject(final Class loadPlugInType, - final Plugin plugin, - final PluginLoadErrors error) { - - if(plugin != null){ - - if(loadPlugInType == notationClass){ - final Notation notation = (Notation) plugin; - return storeNotation(notation, error); - } - else if(loadPlugInType == moduleClass){ - final Module module = (Module) plugin; - return storeModule(module, error); - } - else if(loadPlugInType == extenderClass){ - final Extension extension = (Extension) plugin; - return storeExtension(extension, error); - } - else { - LOG.error("Unknown plugin type."); - } - } - - return false; - } - - /** - * Stores loaded and instantiated extension for future use. - * - * @param extension is the newly loaded and instantiated extension - * @param error for error publishing - * @return true if no error has occurred and the extension has been saved, false otherwise - */ - private boolean storeExtension(final Extension extension, final PluginLoadErrors error) { - - if(!hasExtensionMandatoryData(extension, error)){ - return false; - } - - if(!existsExtension(extension.getIdentifier())){ - extensionList.add(extension); - - return true; - - } else { - LOG.error("Extension with duplicate identifier has been loaded. Skipping notation: " + extension.getIdentifier() + "."); - error.reportError(PluginLoadErrors.ERRORS.extensionIdentifierDuplicity, errorList); - } - - return false; - } - - /** - * Checks extension mandatory data. - * - * @param extension is the extension to be checked - * @param error for error publishing - * @return true if the extension fulfil requirements, false otherwise - */ - private boolean hasExtensionMandatoryData(final Extension extension, final PluginLoadErrors error){ - if(!hasPluginMandatoryData(extension, error)){ - LOG.error("Extension do not have all it's mandatory data."); - return false; - } - - return true; - } - - /** - * Returns the loaded extension. - * - * @param extensionIdentifier is the identifier of required extension - * @return loaded extension with given identifier, null if there is no such extension - */ - private Extension getExtension(final String extensionIdentifier){ - for(final Extension extension : extensionList){ - if(extension.getIdentifier().equals(extensionIdentifier)){ - return extension; - } - } - - return null; - } - - /** - * @param extensionIdentifier is the identifier of an extension - * @return true if such a extension with given identifier has been already loaded, false otherwise - */ - private boolean existsExtension(final String extensionIdentifier){ - return getExtension(extensionIdentifier) != null; - } - - /** - * Checks and the stores instantiated notation for future use. - * - * @param notation is the newly instantiated notation - * @param error for error publishing - * @return true if the notation was successfully store for future use, false if any error occurs - */ - private boolean storeNotation(final Notation notation, final PluginLoadErrors error) { - - if(!hasNotationMandatoryData(notation, error)){ - return false; - } - - if(!existUniqueNotationIdentifier(notation.getIdentifier())){ - notationSpecificPluginsList.add(new ModifiableNotationSpecificPlugins(notation)); - - return true; - - } else { - LOG.error("Notation with duplicate identifier has been loaded. Skipping notation: " + notation.getIdentifier() + "."); - error.reportError(PluginLoadErrors.ERRORS.notationIdentifierDuplicity, errorList); - } - - return false; - } - - /** - * Checks whether given notation identifier is equal to any other loaded notation's identifier. - * - * @param identifier is the identifier to be checked - * @return true if the identifier is unique, false otherwise - */ - private boolean existUniqueNotationIdentifier(final String identifier){ - for(final ModifiableNotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ - if(notationSpecificPlugins.getNotation().getIdentifier().equals(identifier)){ - return true; - } - } - - return false; - } - - /** - * Returns the required instance of NotationSpecificPlugins class. - * - * @param identifier is the identifier of notation which NotationSpecificPlugins instance should be found - * @return required instance of NotationSpecificPlugins class, null if there is no notation with given identifier - */ - private ModifiableNotationSpecificPlugins getNotationSpecificPlugins(final String identifier){ - for(final ModifiableNotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ - if(notationSpecificPlugins.getNotation().getIdentifier().equals(identifier)){ - return notationSpecificPlugins; - } - } - - return null; - } - - /** - * Check all necessary condition that have to be accomplished to accept the module. If no problem occurs, - * the module is stored and ready to use. - * - * @param module tested module - * @param error to report errors - * @return true if the module is acceptable and has been stored, false otherwise - */ - private boolean storeModule(final Module module, final PluginLoadErrors error) { - - if(!hasModuleMandatoryData(module, error)){ - return false; - } - - // check whether there is a notation to which is this module related - if(!existUniqueNotationIdentifier(module.getRelatedNotationIdentifier())){ - LOG.error("Module without related notation has been loaded. Skipping module - " - + module.getIdentifier() + ", related notation identifier - " + module.getRelatedNotationIdentifier() + "."); - - error.reportError(PluginLoadErrors.ERRORS.noRelatedNotationIdentifier, errorList); - - return false; - } - - // check whether the is already no module with the same module identifier for the same notation - final ModifiableNotationSpecificPlugins notationSpecificPlugins = getNotationSpecificPlugins(module.getRelatedNotationIdentifier()); - - if(notationSpecificPlugins.existModule(module.getIdentifier())){ - LOG.error("More than one module for the same notation have the same identifier"); - - error.reportError(PluginLoadErrors.ERRORS.moduleIdentifierDuplicity, errorList); - - return false; - } - - // if no error has not occurred so far, store the module - notationSpecificPlugins.addModule(module); - - return true; - } - - - /** - * Checks basic data of any instance of Plugin interface. - * - * @param plugin an instance of Plugin class to be checked. - * - * @param error to report errors - * @return true if and only if all mandatory data is present and correct, false otherwise - */ - private boolean hasPluginMandatoryData(final Plugin plugin, PluginLoadErrors error){ - if(plugin.getIdentifier() == null){ - LOG.error("Plugin identifier cannot be null."); - error.reportError(PluginLoadErrors.ERRORS.nullaryPluginIdentifier, errorList); - return false; - } - - if(plugin.getIdentifier().trim().isEmpty()){ - LOG.error("Plugin identifier cannot be an empty string (white characters don't count)."); - error.reportError(PluginLoadErrors.ERRORS.emptyPluginIdentifier, errorList); - return false; - } - - if(plugin.getIdentifier().length() > PluginLoaderService.MAX_PLUGIN_IDENTIFIER_LENGTH){ - LOG.error("Plugin identifier length has exceeded the max number of symbols."); - error.reportError(PluginLoadErrors.ERRORS.tooLongPluginIdentifier, errorList); - return false; - } - - if(plugin.getIdentifier().trim().equals(ModelerModel.MODELER_IDENTIFIER)){ - LOG.error("Plugin identifier cannot be a save as modeler identifier."); - error.reportError(PluginLoadErrors.ERRORS.likeModelerpluginIdentifier, errorList); - return false; - } - - if(plugin.getName() == null){ - LOG.error("Extension name cannot be null."); - error.reportError(PluginLoadErrors.ERRORS.nullaryName, errorList); - return false; - } - - if(plugin.getName().trim().isEmpty()){ - LOG.error("Extension name cannot be an empty string."); - error.reportError(PluginLoadErrors.ERRORS.emptyName, errorList); - return false; - } - - return true; - } - - /** - * Checks basic data of any instance of Notation interface. - * - * @param notation that's data will be checked. - * @param error to report errors - * @return true if and only if all mandatory data are available (don't has to be valid), false otherwise - */ - private boolean hasNotationMandatoryData(final Notation notation, final PluginLoadErrors error){ - if(!hasPluginMandatoryData(notation, error)){ - LOG.error("Notation do not have all it's mandatory data."); - return false; - } - - if(notation.getFullName() == null){ - LOG.error("Notation full name cannot be null."); - error.reportError(PluginLoadErrors.ERRORS.nullaryNotationName, errorList); - return false; - } - - if(notation.getFullName().trim().isEmpty()){ - LOG.error("Notation full name cannot be an empty string (white characters don't count)."); - error.reportError(PluginLoadErrors.ERRORS.emptyNotationName, errorList); - return false; - } - - if(notation.getDiagramModelFactory() == null){ - LOG.error("Notations has not provide an instance of DiagramModelFactory interface."); - error.reportError(PluginLoadErrors.ERRORS.noModelFactory, errorList); - return false; - } - - if(notation.getDiagramModelFactory().createEmptyDiagramModel() == null){ - LOG.error("Notations has not provided an correct instance of DiagramModelFactory interface."); - error.reportError(PluginLoadErrors.ERRORS.invalidModelFactory, errorList); - return false; - } - - if(notation.getAbbreviation() == null){ - LOG.error("Notation abbreviation cannot be null"); - error.reportError(PluginLoadErrors.ERRORS.nullaryAbbreviation, errorList); - return false; - } - - if(notation.getAbbreviation().trim().isEmpty()){ - LOG.error("Notation abbreviation cannot be an empty string (white characters don't count)."); - error.reportError(PluginLoadErrors.ERRORS.emptyAbbreviation, errorList); - return false; - } - - final NotationLocalIOController ioController = notation.getLocalIOController(); - - if(ioController == null){ - LOG.error("No implementation of NotationLocalIOController provided."); - error.reportError(PluginLoadErrors.ERRORS.ioController, errorList); - return false; - } - - if(ioController.getNotationFileExtension() == null){ - LOG.error("Notation file extension cannot be null"); - error.reportError(PluginLoadErrors.ERRORS.nullaryFileExtension, errorList); - return false; - } - - if(ioController.getNotationFileExtension().trim().isEmpty()){ - LOG.error("Notation file extension cannot be an empty string (white characters don't count)."); - error.reportError(PluginLoadErrors.ERRORS.emptyFileExtension, errorList); - return false; - } - - if(ioController.getNotationFileExtension().trim().equals(ProjectService.PROJECT_FILE_EXTENSION_NAME)){ - LOG.error("Notation file extension is equal with ProMod project file extension."); - error.reportError(PluginLoadErrors.ERRORS.projectFileLikeExtension, errorList); - return false; - } - - for(final ModifiableNotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ - if(notationSpecificPlugins.getNotation().getLocalIOController().getNotationFileExtension().equals( - ioController.getNotationFileExtension() - )){ - LOG.error("Notation file extension has the same extension like any earlier loaded notation."); - error.reportError(PluginLoadErrors.ERRORS.notationExtensionDuplicity, errorList); - return false; - } - } - - return true; - } - - /** - * Check mandatory module data. - * - * @param module to be checked - * @param error for error reporting - * @return true if no error occurred, false otherwise - */ - private boolean hasModuleMandatoryData(final Module module, final PluginLoadErrors error){ - if(!hasPluginMandatoryData(module, error)){ - LOG.error("Module do not have all it's mandatory data."); - return false; - } - - if(module.getRelatedNotationIdentifier() == null){ - LOG.error("Module's related notation identifier cannot be null"); - - error.reportError(PluginLoadErrors.ERRORS.nullaryRelatedNotationIdentifier, errorList); - } - - if(module.getRelatedNotationIdentifier().trim().isEmpty()){ - LOG.error("Module's related notation identifier cannot be an empty string (white characters don't count)."); - - error.reportError(PluginLoadErrors.ERRORS.emptyRelatedNotationIdentifier, errorList); - } - - return true; - } - - /** - * Check the configuration file of a plugin. - * - * @param configFile is the configuration file - * @param alias is the plugin alias for logging purposes - * - * @return true if no error occurs, false otherwise - */ - private boolean checkConfigFile(final File configFile, final String alias) { - if(!configFile.exists()){ - LOG.error("Config file doesn't exist for plugin marked as '" + alias + "'"); - return false; - } - - if(!configFile.isFile()){ - LOG.error("Config file is not a file for plugin marked as '" + alias + "'"); - return false; - } - - if(!configFile.canRead()){ - LOG.error("Config file is not readable for plugin marked as '" + alias + "'"); - return false; - } - - return true; - } - - /** {@inheritDoc} */ - public List getNotationSpecificPlugins() { - final List plugins = new LinkedList(); - - // ensures unmodifiable list of modules - for(ModifiableNotationSpecificPlugins plugin : notationSpecificPluginsList){ - plugins.add(new NotationSpecificPlugins(plugin.getNotation(), Collections.unmodifiableList(plugin.getModules()))); - } - - // ensures unmodifiable list of notations and modules - return Collections.unmodifiableList(plugins); - } - - /** {@inheritDoc} */ - public List getExtensions() { - return Collections.unmodifiableList(extensionList); - } - - /** {@inheritDoc} */ - public List getErrors() { - return Collections.unmodifiableList(errorList); - } - - /** {@inheritDoc} */ - public boolean check() { - return true; - } -} +package cz.cvut.promod.services.pluginLoaderService; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.localIOController.NotationLocalIOController; +import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; +import cz.cvut.promod.plugin.Plugin; +import cz.cvut.promod.plugin.extension.Extension; +import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; +import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; +import cz.cvut.promod.services.pluginLoaderService.utils.PluginDetails; +import cz.cvut.promod.services.pluginLoaderService.utils.ModifiableNotationSpecificPlugins; +import cz.cvut.promod.services.pluginLoaderService.errorHandling.PluginLoaderErrorHandler; +import cz.cvut.promod.services.projectService.ProjectService; +import cz.cvut.promod.gui.ModelerModel; +import cz.cvut.promod.resources.Resources; + +import java.util.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +import org.apache.log4j.Logger; +import org.xml.sax.SAXException; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.w3c.dom.Node; +import org.w3c.dom.NamedNodeMap; + + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Validator; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:09:56, 12.10.2009 + */ + +/** + * Implementation of PluginLoaderService. + */ +public class PluginLoaderServiceImpl implements PluginLoaderService { + + private final Logger LOG = Logger.getLogger(PluginLoaderServiceImpl.class); + + /** + * Specifies what kind of plugins is being loaded. + * Only for inner services purposes. + */ + private static enum LoadPlugInType { + NOTATIONS_AND_MODULES, + EXTENSION + } + + private final static String ROOT_TAG = "promod-plugins"; + private final static String NOTATION_TAG = "notation"; + private final static String MODULE_TAG = "module"; + private final static String EXTENSION_TAG = "extension"; + + private final static String CLASS_ATTRIBUTE = "class"; + private final static String CONFIG_ATTRIBUTE = "config"; + private final static String ALIAS_ATTRIBUTE = "alias"; + + private final static String NOTATION_INTERFACE_QUALIFIED_NAME= "cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation"; + private final static String MODULE_INTERFACE_QUALIFIED_NAME= "cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module"; + private final static String IOCONTROLPLUGIN_INTERFACE_QUALIFIED_NAME= "cz.cvut.promod.plugin.extension.Extension"; + + private final List notationDetails; + private final List extensionDetails; + + private final List notationSpecificPluginsList; + private final List extensionList; + + /** + * Holds all errors that occur during plugin loading, instantiating or preparing to use. + */ + private final List errorList; + + private final Class notationClass; + private final Class moduleClass; + private final Class extenderClass; + + + public PluginLoaderServiceImpl() throws ClassNotFoundException{ + errorList = new LinkedList(); + + notationDetails = new LinkedList(); + extensionDetails = new LinkedList(); + + notationSpecificPluginsList = new LinkedList(); + extensionList = new LinkedList(); + + notationClass = Class.forName(NOTATION_INTERFACE_QUALIFIED_NAME); + moduleClass = Class.forName(MODULE_INTERFACE_QUALIFIED_NAME); + extenderClass = Class.forName(IOCONTROLPLUGIN_INTERFACE_QUALIFIED_NAME); + } + + /** {@inheritDoc} + * + * Not valid XML file won't be loaded. + * + * If there will be any need to load not certainly valid files in the future, it could be enough to skip the + * XML validation. There are even error messages already prepared. + */ + public boolean loadPlugInsDefinition(final String pluginDefinitionFile){ + final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + + final InputStream schemaInputStream = ClassLoader.getSystemResourceAsStream( + Resources.CONFIG + Resources.PLUGINS_XSD_FILE + ); + + LOG.info("Validating plugin definition file against xsd file."); + + documentBuilderFactory.setNamespaceAware(true); + documentBuilderFactory.setValidating(false); + + final Schema schema; + final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + final Source source = new StreamSource(schemaInputStream); + try { + schema = schemaFactory.newSchema(source); + + } catch (SAXException e) { + LOG.info("Skipping plugin definition file validation."); + final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); + error.reportError(PluginLoadErrors.ERRORS.xmlParsing, errorList); + return false; + } + + final Document document; + + try { + final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + + documentBuilder.setErrorHandler(new PluginLoaderErrorHandler()); + + document = documentBuilder.parse(new File(pluginDefinitionFile)); + + final Validator validator = schema.newValidator(); + + validator.validate(new DOMSource(document)); + + } catch (ParserConfigurationException e) { + LOG.error("XML Parser configuration has failed.", e); + final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); + error.reportError(PluginLoadErrors.ERRORS.xmlParsing, e.getMessage(), errorList); + return false; + + } catch (IOException e) { + LOG.error("An IO error has occurred when reading the plugin info xml file.", e); + final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); + error.reportError(PluginLoadErrors.ERRORS.xmlParsing, e.getMessage(), errorList); + return false; + + } catch (SAXException e) { + LOG.error("An SAX error has occurred when reading the plugin info xml file.", e); + final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); + error.reportError(PluginLoadErrors.ERRORS.xmlParsing, e.getMessage(), errorList); + return false; + + } catch (NullPointerException exception){ + LOG.error("Nullary info about the plugin specification.", exception); + final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); + error.reportError(PluginLoadErrors.ERRORS.xmlParsing, exception.getMessage(), errorList); + return false; + } + + return document != null && loadPluginDetails(document); + } + + /** + * Loads plugin details = aliases, classes, config files and save this information for future use, + * + * @param document is the DOM document of plugin definition file containing plugin details + * + * @return true if no error occurs, false otherwise + */ + private boolean loadPluginDetails(final Document document){ + final NodeList rootNodeList = document.getElementsByTagName(ROOT_TAG); + if(rootNodeList.getLength() != 1){ + LOG.error("More than one (or missing) root node in plugin xml file."); + final PluginLoadErrors error = new PluginLoadErrors(ModelerModel.MODELER_IDENTIFIER); + error.reportError(PluginLoadErrors.ERRORS.xmlParsing, errorList); + return false; + } + + final Node rootNode = rootNodeList.item(0); + + final NodeList nodeList = rootNode.getChildNodes(); + + for(int i = 0; i < nodeList.getLength(); i++){ + final Node notationNode = nodeList.item(i); + + if(notationNode.getNodeName().equals(NOTATION_TAG)){ + NamedNodeMap attributes = notationNode.getAttributes(); + + final PluginDetails notationDetail = new PluginDetails( + readAttribute(attributes.getNamedItem(CLASS_ATTRIBUTE)), + readAttribute(attributes.getNamedItem(CONFIG_ATTRIBUTE)), + readAttribute(attributes.getNamedItem(ALIAS_ATTRIBUTE)) + ); + + final NodeList moduleList = notationNode.getChildNodes(); + + for(int j = 0; j < moduleList.getLength(); j++){ + final Node moduleNode = moduleList.item(j); + + if(moduleNode.getNodeName().equals(MODULE_TAG)){ + attributes = moduleNode.getAttributes(); + + final PluginDetails moduleDetail = new PluginDetails( + readAttribute(attributes.getNamedItem(CLASS_ATTRIBUTE)), + readAttribute(attributes.getNamedItem(CONFIG_ATTRIBUTE)), + readAttribute(attributes.getNamedItem(ALIAS_ATTRIBUTE)) + ); + + notationDetail.addPluginDetails(moduleDetail); + } + } + + notationDetails.add(notationDetail); + + } else if(notationNode.getNodeName().equals(EXTENSION_TAG)){ + final NamedNodeMap attributes = notationNode.getAttributes(); + + final PluginDetails extensionDetail = new PluginDetails( + readAttribute(attributes.getNamedItem(CLASS_ATTRIBUTE)), + readAttribute(attributes.getNamedItem(CONFIG_ATTRIBUTE)), + readAttribute(attributes.getNamedItem(ALIAS_ATTRIBUTE)) + ); + + extensionDetails.add(extensionDetail); + } + } + + return true; + } + + /** {@inheritDoc} */ + public List getNotationModulesInstInfo() { + return Collections.unmodifiableList(notationDetails); + } + + /** {@inheritDoc} */ + public List getExtensionInstInfo() { + return Collections.unmodifiableList(extensionDetails); + } + + /** + * Reads node's attribute. + * + * @param node is the attribute node + * + * @return value of the attribute it exists, null otherwise + */ + private String readAttribute(final Node node){ + if(node != null){ + return node.getNodeValue(); + } + + return null; + } + + /** {@inheritDoc} */ + public void instantiatePlugins() { + instantiatePlugins(LoadPlugInType.NOTATIONS_AND_MODULES); + instantiatePlugins(LoadPlugInType.EXTENSION); + } + + /** + * Instantiate plugins accordingly to the information loaded from plugin configuration file and store this instances + * for future use. + * + * @param loadPlugInType is the type of plugins that are supposed to be instantiated + * + * @see cz.cvut.promod.services.pluginLoaderService.PluginLoaderServiceImpl.LoadPlugInType + */ + private void instantiatePlugins(LoadPlugInType loadPlugInType){ + final List pluginDetailsList; + Class plugInTypeInterface = null; + + pluginDetailsList = getRequiredList(loadPlugInType); + + if(pluginDetailsList == null){ + return; + } + + for(final PluginDetails details : pluginDetailsList){ + String notationIdentifier = null; // when modules are being loaded, this holds the related notation id. + + PluginDetails pluginDetail = details; + + switch (loadPlugInType){ + case NOTATIONS_AND_MODULES: + plugInTypeInterface = notationClass; + break; + case EXTENSION: + plugInTypeInterface = extenderClass; + break; + } + + do{ + final String alias = pluginDetail.getAlias(); + + if(alias == null || alias.isEmpty()) { + LOG.error("Skipping loading of an plugin - not provided alias."); + break; + } + + final PluginLoadErrors error = new PluginLoadErrors(alias); + + final String fullClassName = pluginDetail.getClazz(); + + if(!isValidClassName(fullClassName)){ + LOG.error("Due to error(s) skipping loading of plugin defined by '" + pluginDetail + "' property."); + error.reportError(PluginLoadErrors.ERRORS.className, errorList); + break; + } + + error.setFullClassName(fullClassName); // set the non empty and non nullary class name + + final Class clazz = getPluginClass(fullClassName); + if(clazz == null) { + LOG.error("Due to error(s) skipping loading of " + alias + "."); + error.reportError(PluginLoadErrors.ERRORS.findClass, errorList); + break; + } + + if(!implementsInterfaces(clazz, plugInTypeInterface)){ + LOG.error("Due to error(s) skipping loading of " + clazz.getName() + "."); + error.reportError(PluginLoadErrors.ERRORS.classHierarchy, errorList); + break; + } + + final Plugin plugin = instantiatePlugin( + clazz, pluginDetail, error, notationIdentifier, plugInTypeInterface == moduleClass); + if(plugin == null) { + LOG.error("Due to error(s) skipping loading of " + clazz.getName() + "."); + break; + } + + //save the loaded plugin + if(!storePluginObject(plugInTypeInterface, plugin, error)){ + LOG.error("Due to error(s) skipping loading of " + clazz.getName() + "."); + } + + // instantiate modules + pluginDetail = details.pop(); + plugInTypeInterface = moduleClass; + + // store temporarily the notation identifier for instantiating of it's related modules + if(plugin instanceof Notation && notationIdentifier == null){ + notationIdentifier = plugin.getIdentifier(); + } + + } while(pluginDetail != null); + } + } + + /** + * Return required list of plugin details. + * + * @param loadPlugInType is the type of plugins + * + * @return required list or null if any error occurs + */ + private List getRequiredList(final LoadPlugInType loadPlugInType) { + switch (loadPlugInType){ + case NOTATIONS_AND_MODULES: + return notationDetails; + case EXTENSION: + return extensionDetails; + default: + LOG.error("Unknown plugIn type has been recognized."); + } + + return null; + } + + /** + * Checks the qualified class name. + * + * @param fullClassName is the qualified class name + * @return true if the fullClassName is not null or an empty string, false otherwise + */ + private boolean isValidClassName(final String fullClassName) { + if(fullClassName == null){ + LOG.error("Nullary plugin class name."); + return false; + } + + if(fullClassName.isEmpty()){ + LOG.error("Empty plugin class name."); + return false; + } + + return true; + } + + /** + * Returns an instance of Class class representing the plugin class. + * + * @param fullClassName is the qualified name of the class + * + * @return in instance of Class if the plugin class definition is accessible, false otherwise + */ + private Class getPluginClass(final String fullClassName){ + final Class clazz; + try { + // get plugin class + clazz = Class.forName(fullClassName); + + } catch (ClassNotFoundException exception) { + LOG.error("Wrong pluIn class definition, " + fullClassName + ".", exception); + return null; + + } catch (NoClassDefFoundError error){ + LOG.error("Wrong pluIn class definition, " + fullClassName + ".", error); + return null; + + } catch(LinkageError error){ + LOG.error("Wrong pluIn class definition, " + fullClassName + ".", error); + return null; + } + + + return clazz; + } + + /** + * Checks whether the plugin implements necessary interfaces (Notation, Module, etc.). + * + * @param clazz that is supposed to implement an interface specified by the second argument + * @param plugInTypeInterface the plugin specific interface (Notation, Module, etc.) + * + * @return true if necessary the clazz implements necessary interface, false otherwise + */ + private boolean implementsInterfaces(final Class clazz, final Class plugInTypeInterface){ + boolean implementsRequiredInterface = false; + for(final Class implementedInterface : clazz.getInterfaces()){ + if(plugInTypeInterface == implementedInterface){ + implementsRequiredInterface = true; + break; + } + } + + if(!implementsRequiredInterface){ + LOG.error("Plugin ("+ clazz.getName() +") doesn't implement required notation + (" + plugInTypeInterface.getSimpleName() + ")."); + } + + return implementsRequiredInterface; + } + + /** + * Instantiate a class provided as a argument of this method. + * + * @param clazz definition of class to be instantiated + * @param pluginDetails holds info about the plugin that is supposed to be instantiated + * @param error to report errors + * @param notationIdentifier is the identifier of notation, used when modules are being instantiated + * @param isModule indicates if the module is going to be instantiated or not + * @return an object of the class (plugin) if no error occurs, null otherwise + */ + private Plugin instantiatePlugin(final Class clazz, + final PluginDetails pluginDetails, + final PluginLoadErrors error, + final String notationIdentifier, + final boolean isModule){ + try { + Plugin plugin; + + final String configFilePath = pluginDetails.getConfig(); + final File configFile; + + if(configFilePath != null){ + // use constructor taking a file as argument + + configFile = new File(configFilePath); + + if(!checkConfigFile(configFile, pluginDetails.getAlias())){ + LOG.error("Configuration data provided is not a valid file. Skipping plugin instantiation, " + pluginDetails.getAlias() + "."); + error.reportError(PluginLoadErrors.ERRORS.instantiation, errorList); + return null; + + } + } else { + configFile = null; + } + + Constructor moduleFileIdentifierConstructor = null; + Constructor moduleIdentifierConstructor = null; + Constructor fileConstructor = null; + + for(final Constructor constructor : clazz.getConstructors()){ + final Class[] parameters = constructor.getParameterTypes(); + + if(isModule){ + // try to find special constructors for modules + + if((parameters.length == 2) && parameters[0].equals(File.class) && parameters[1].equals(String.class)){ + moduleFileIdentifierConstructor = constructor; + } + else if((parameters.length == 1) && parameters[0].equals(String.class)){ + moduleIdentifierConstructor = constructor; + } + } + + if((parameters.length == 1) && parameters[0].equals(File.class)){ + fileConstructor = constructor; + } + } + + if(moduleFileIdentifierConstructor != null){ + plugin = (Plugin) moduleFileIdentifierConstructor.newInstance(configFile, notationIdentifier); + + } else if (moduleIdentifierConstructor != null){ + plugin = (Plugin) moduleIdentifierConstructor.newInstance(notationIdentifier); + + } else if(fileConstructor != null){ + // there is a required constructor + plugin = (Plugin) fileConstructor.newInstance(configFile); + + } else { + // configuration data not provided, use parameter-less constructor + plugin = (Plugin) clazz.newInstance(); + } + + return plugin; + + } catch (InstantiationException e) { + LOG.error("PluginLoaderService could not instantiate plugin object, full class name: " + clazz.getName() + "."); + error.reportError(PluginLoadErrors.ERRORS.instantiation, e.getMessage(), errorList); + + } catch (IllegalAccessException e) { + LOG.error("PluginLoaderService could not access parameter-less constructor of plugin, full class name: " + clazz.getName() + "."); + error.reportError(PluginLoadErrors.ERRORS.instantiation, e.getMessage(), errorList); + + } catch (InvocationTargetException e) { + LOG.error("Nullary constructor error.", e); + error.reportError(PluginLoadErrors.ERRORS.instantiation, e.getMessage(), errorList); + } + + return null; + } + + /** + * Stores instantiated plugin for future use. + * + * @param loadPlugInType is the plugin type + * @param plugin is the object of plugin + * @param error to report errors + * + * @return true if no error(s) occurred, false otherwise + */ + private boolean storePluginObject(final Class loadPlugInType, + final Plugin plugin, + final PluginLoadErrors error) { + + if(plugin != null){ + + if(loadPlugInType == notationClass){ + final Notation notation = (Notation) plugin; + return storeNotation(notation, error); + } + else if(loadPlugInType == moduleClass){ + final Module module = (Module) plugin; + return storeModule(module, error); + } + else if(loadPlugInType == extenderClass){ + final Extension extension = (Extension) plugin; + return storeExtension(extension, error); + } + else { + LOG.error("Unknown plugin type."); + } + } + + return false; + } + + /** + * Stores loaded and instantiated extension for future use. + * + * @param extension is the newly loaded and instantiated extension + * @param error for error publishing + * @return true if no error has occurred and the extension has been saved, false otherwise + */ + private boolean storeExtension(final Extension extension, final PluginLoadErrors error) { + + if(!hasExtensionMandatoryData(extension, error)){ + return false; + } + + if(!existsExtension(extension.getIdentifier())){ + extensionList.add(extension); + + return true; + + } else { + LOG.error("Extension with duplicate identifier has been loaded. Skipping notation: " + extension.getIdentifier() + "."); + error.reportError(PluginLoadErrors.ERRORS.extensionIdentifierDuplicity, errorList); + } + + return false; + } + + /** + * Checks extension mandatory data. + * + * @param extension is the extension to be checked + * @param error for error publishing + * @return true if the extension fulfil requirements, false otherwise + */ + private boolean hasExtensionMandatoryData(final Extension extension, final PluginLoadErrors error){ + if(!hasPluginMandatoryData(extension, error)){ + LOG.error("Extension do not have all it's mandatory data."); + return false; + } + + return true; + } + + /** + * Returns the loaded extension. + * + * @param extensionIdentifier is the identifier of required extension + * @return loaded extension with given identifier, null if there is no such extension + */ + private Extension getExtension(final String extensionIdentifier){ + for(final Extension extension : extensionList){ + if(extension.getIdentifier().equals(extensionIdentifier)){ + return extension; + } + } + + return null; + } + + /** + * @param extensionIdentifier is the identifier of an extension + * @return true if such a extension with given identifier has been already loaded, false otherwise + */ + private boolean existsExtension(final String extensionIdentifier){ + return getExtension(extensionIdentifier) != null; + } + + /** + * Checks and the stores instantiated notation for future use. + * + * @param notation is the newly instantiated notation + * @param error for error publishing + * @return true if the notation was successfully store for future use, false if any error occurs + */ + private boolean storeNotation(final Notation notation, final PluginLoadErrors error) { + + if(!hasNotationMandatoryData(notation, error)){ + return false; + } + + if(!existUniqueNotationIdentifier(notation.getIdentifier())){ + notationSpecificPluginsList.add(new ModifiableNotationSpecificPlugins(notation)); + + return true; + + } else { + LOG.error("Notation with duplicate identifier has been loaded. Skipping notation: " + notation.getIdentifier() + "."); + error.reportError(PluginLoadErrors.ERRORS.notationIdentifierDuplicity, errorList); + } + + return false; + } + + /** + * Checks whether given notation identifier is equal to any other loaded notation's identifier. + * + * @param identifier is the identifier to be checked + * @return true if the identifier is unique, false otherwise + */ + private boolean existUniqueNotationIdentifier(final String identifier){ + for(final ModifiableNotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ + if(notationSpecificPlugins.getNotation().getIdentifier().equals(identifier)){ + return true; + } + } + + return false; + } + + /** + * Returns the required instance of NotationSpecificPlugins class. + * + * @param identifier is the identifier of notation which NotationSpecificPlugins instance should be found + * @return required instance of NotationSpecificPlugins class, null if there is no notation with given identifier + */ + private ModifiableNotationSpecificPlugins getNotationSpecificPlugins(final String identifier){ + for(final ModifiableNotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ + if(notationSpecificPlugins.getNotation().getIdentifier().equals(identifier)){ + return notationSpecificPlugins; + } + } + + return null; + } + + /** + * Check all necessary condition that have to be accomplished to accept the module. If no problem occurs, + * the module is stored and ready to use. + * + * @param module tested module + * @param error to report errors + * @return true if the module is acceptable and has been stored, false otherwise + */ + private boolean storeModule(final Module module, final PluginLoadErrors error) { + + if(!hasModuleMandatoryData(module, error)){ + return false; + } + + // check whether there is a notation to which is this module related + if(!existUniqueNotationIdentifier(module.getRelatedNotationIdentifier())){ + LOG.error("Module without related notation has been loaded. Skipping module - " + + module.getIdentifier() + ", related notation identifier - " + module.getRelatedNotationIdentifier() + "."); + + error.reportError(PluginLoadErrors.ERRORS.noRelatedNotationIdentifier, errorList); + + return false; + } + + // check whether the is already no module with the same module identifier for the same notation + final ModifiableNotationSpecificPlugins notationSpecificPlugins = getNotationSpecificPlugins(module.getRelatedNotationIdentifier()); + + if(notationSpecificPlugins.existModule(module.getIdentifier())){ + LOG.error("More than one module for the same notation have the same identifier"); + + error.reportError(PluginLoadErrors.ERRORS.moduleIdentifierDuplicity, errorList); + + return false; + } + + // if no error has not occurred so far, store the module + notationSpecificPlugins.addModule(module); + + return true; + } + + + /** + * Checks basic data of any instance of Plugin interface. + * + * @param plugin an instance of Plugin class to be checked. + * + * @param error to report errors + * @return true if and only if all mandatory data is present and correct, false otherwise + */ + private boolean hasPluginMandatoryData(final Plugin plugin, PluginLoadErrors error){ + if(plugin.getIdentifier() == null){ + LOG.error("Plugin identifier cannot be null."); + error.reportError(PluginLoadErrors.ERRORS.nullaryPluginIdentifier, errorList); + return false; + } + + if(plugin.getIdentifier().trim().isEmpty()){ + LOG.error("Plugin identifier cannot be an empty string (white characters don't count)."); + error.reportError(PluginLoadErrors.ERRORS.emptyPluginIdentifier, errorList); + return false; + } + + if(plugin.getIdentifier().length() > PluginLoaderService.MAX_PLUGIN_IDENTIFIER_LENGTH){ + LOG.error("Plugin identifier length has exceeded the max number of symbols."); + error.reportError(PluginLoadErrors.ERRORS.tooLongPluginIdentifier, errorList); + return false; + } + + if(plugin.getIdentifier().trim().equals(ModelerModel.MODELER_IDENTIFIER)){ + LOG.error("Plugin identifier cannot be a save as modeler identifier."); + error.reportError(PluginLoadErrors.ERRORS.likeModelerpluginIdentifier, errorList); + return false; + } + + if(plugin.getName() == null){ + LOG.error("Extension name cannot be null."); + error.reportError(PluginLoadErrors.ERRORS.nullaryName, errorList); + return false; + } + + if(plugin.getName().trim().isEmpty()){ + LOG.error("Extension name cannot be an empty string."); + error.reportError(PluginLoadErrors.ERRORS.emptyName, errorList); + return false; + } + + return true; + } + + /** + * Checks basic data of any instance of Notation interface. + * + * @param notation that's data will be checked. + * @param error to report errors + * @return true if and only if all mandatory data are available (don't has to be valid), false otherwise + */ + private boolean hasNotationMandatoryData(final Notation notation, final PluginLoadErrors error){ + if(!hasPluginMandatoryData(notation, error)){ + LOG.error("Notation do not have all it's mandatory data."); + return false; + } + + if(notation.getFullName() == null){ + LOG.error("Notation full name cannot be null."); + error.reportError(PluginLoadErrors.ERRORS.nullaryNotationName, errorList); + return false; + } + + if(notation.getFullName().trim().isEmpty()){ + LOG.error("Notation full name cannot be an empty string (white characters don't count)."); + error.reportError(PluginLoadErrors.ERRORS.emptyNotationName, errorList); + return false; + } + + if(notation.getDiagramModelFactory() == null){ + LOG.error("Notations has not provide an instance of DiagramModelFactory interface."); + error.reportError(PluginLoadErrors.ERRORS.noModelFactory, errorList); + return false; + } + + if(notation.getDiagramModelFactory().createEmptyDiagramModel() == null){ + LOG.error("Notations has not provided an correct instance of DiagramModelFactory interface."); + error.reportError(PluginLoadErrors.ERRORS.invalidModelFactory, errorList); + return false; + } + + if(notation.getAbbreviation() == null){ + LOG.error("Notation abbreviation cannot be null"); + error.reportError(PluginLoadErrors.ERRORS.nullaryAbbreviation, errorList); + return false; + } + + if(notation.getAbbreviation().trim().isEmpty()){ + LOG.error("Notation abbreviation cannot be an empty string (white characters don't count)."); + error.reportError(PluginLoadErrors.ERRORS.emptyAbbreviation, errorList); + return false; + } + + final NotationLocalIOController ioController = notation.getLocalIOController(); + + if(ioController == null){ + LOG.error("No implementation of NotationLocalIOController provided."); + error.reportError(PluginLoadErrors.ERRORS.ioController, errorList); + return false; + } + + if(ioController.getNotationFileExtension() == null){ + LOG.error("Notation file extension cannot be null"); + error.reportError(PluginLoadErrors.ERRORS.nullaryFileExtension, errorList); + return false; + } + + if(ioController.getNotationFileExtension().trim().isEmpty()){ + LOG.error("Notation file extension cannot be an empty string (white characters don't count)."); + error.reportError(PluginLoadErrors.ERRORS.emptyFileExtension, errorList); + return false; + } + + if(ioController.getNotationFileExtension().trim().equals(ProjectService.PROJECT_FILE_EXTENSION_NAME)){ + LOG.error("Notation file extension is equal with ProMod project file extension."); + error.reportError(PluginLoadErrors.ERRORS.projectFileLikeExtension, errorList); + return false; + } + + for(final ModifiableNotationSpecificPlugins notationSpecificPlugins : notationSpecificPluginsList){ + if(notationSpecificPlugins.getNotation().getLocalIOController().getNotationFileExtension().equals( + ioController.getNotationFileExtension() + )){ + LOG.error("Notation file extension has the same extension like any earlier loaded notation."); + error.reportError(PluginLoadErrors.ERRORS.notationExtensionDuplicity, errorList); + return false; + } + } + + return true; + } + + /** + * Check mandatory module data. + * + * @param module to be checked + * @param error for error reporting + * @return true if no error occurred, false otherwise + */ + private boolean hasModuleMandatoryData(final Module module, final PluginLoadErrors error){ + if(!hasPluginMandatoryData(module, error)){ + LOG.error("Module do not have all it's mandatory data."); + return false; + } + + if(module.getRelatedNotationIdentifier() == null){ + LOG.error("Module's related notation identifier cannot be null"); + + error.reportError(PluginLoadErrors.ERRORS.nullaryRelatedNotationIdentifier, errorList); + } + + if(module.getRelatedNotationIdentifier().trim().isEmpty()){ + LOG.error("Module's related notation identifier cannot be an empty string (white characters don't count)."); + + error.reportError(PluginLoadErrors.ERRORS.emptyRelatedNotationIdentifier, errorList); + } + + return true; + } + + /** + * Check the configuration file of a plugin. + * + * @param configFile is the configuration file + * @param alias is the plugin alias for logging purposes + * + * @return true if no error occurs, false otherwise + */ + private boolean checkConfigFile(final File configFile, final String alias) { + if(!configFile.exists()){ + LOG.error("Config file doesn't exist for plugin marked as '" + alias + "'"); + return false; + } + + if(!configFile.isFile()){ + LOG.error("Config file is not a file for plugin marked as '" + alias + "'"); + return false; + } + + if(!configFile.canRead()){ + LOG.error("Config file is not readable for plugin marked as '" + alias + "'"); + return false; + } + + return true; + } + + /** {@inheritDoc} */ + public List getNotationSpecificPlugins() { + final List plugins = new LinkedList(); + + // ensures unmodifiable list of modules + for(ModifiableNotationSpecificPlugins plugin : notationSpecificPluginsList){ + plugins.add(new NotationSpecificPlugins(plugin.getNotation(), Collections.unmodifiableList(plugin.getModules()))); + } + + // ensures unmodifiable list of notations and modules + return Collections.unmodifiableList(plugins); + } + + /** {@inheritDoc} */ + public List getExtensions() { + return Collections.unmodifiableList(extensionList); + } + + /** {@inheritDoc} */ + public List getErrors() { + return Collections.unmodifiableList(errorList); + } + + /** {@inheritDoc} */ + public boolean check() { + return true; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/errorHandling/PluginLoaderErrorHandler.java b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/errorHandling/PluginLoaderErrorHandler.java index cdce60b..78f91f0 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/errorHandling/PluginLoaderErrorHandler.java +++ b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/errorHandling/PluginLoaderErrorHandler.java @@ -1,37 +1,37 @@ -package cz.cvut.promod.services.pluginLoaderService.errorHandling; - -import org.xml.sax.ErrorHandler; -import org.xml.sax.SAXParseException; -import org.xml.sax.SAXException; -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:56:47, 5.2.2010 - */ - -/** - * Deals with SAX parsing warnings & errors. - */ -public class PluginLoaderErrorHandler implements ErrorHandler { - - private static final Logger LOG = Logger.getLogger(PluginLoaderErrorHandler.class); - - /** {@inheritDoc} */ - public void warning(SAXParseException exception) throws SAXException { - LOG.warn("Plugin loader XSD validating and parsing warning.", exception); - } - - /** {@inheritDoc} */ - public void error(SAXParseException exception) throws SAXException { - LOG.warn("Plugin loader XSD validating and parsing error.", exception); - throw new SAXException(exception); - } - - /** {@inheritDoc} */ - public void fatalError(SAXParseException exception) throws SAXException { - LOG.warn("Plugin loader XSD validating and parsing fatal error.", exception); - throw new SAXException(exception); - } -} +package cz.cvut.promod.services.pluginLoaderService.errorHandling; + +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXParseException; +import org.xml.sax.SAXException; +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:56:47, 5.2.2010 + */ + +/** + * Deals with SAX parsing warnings & errors. + */ +public class PluginLoaderErrorHandler implements ErrorHandler { + + private static final Logger LOG = Logger.getLogger(PluginLoaderErrorHandler.class); + + /** {@inheritDoc} */ + public void warning(SAXParseException exception) throws SAXException { + LOG.warn("Plugin loader XSD validating and parsing warning.", exception); + } + + /** {@inheritDoc} */ + public void error(SAXParseException exception) throws SAXException { + LOG.warn("Plugin loader XSD validating and parsing error.", exception); + throw new SAXException(exception); + } + + /** {@inheritDoc} */ + public void fatalError(SAXParseException exception) throws SAXException { + LOG.warn("Plugin loader XSD validating and parsing fatal error.", exception); + throw new SAXException(exception); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/ModifiableNotationSpecificPlugins.java b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/ModifiableNotationSpecificPlugins.java index 468d773..6d10457 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/ModifiableNotationSpecificPlugins.java +++ b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/ModifiableNotationSpecificPlugins.java @@ -1,94 +1,94 @@ -package cz.cvut.promod.services.pluginLoaderService.utils; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; -import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; - -import java.util.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 0:32:00, 22.4.2010 - */ - -/** - * Implementation very similar to the NotationSpecificPlugins class, but this one is used just - * for application start-up purposes and it is possible to add or removes modules. - * - * Only PluginLoaderService uses this class. - */ -public class ModifiableNotationSpecificPlugins { - - private final Notation notation; - - private final List modules; - - - /** - * Constructs new ModifiableNotationSpecificPlugins for the specified notation. - * - * @param notation is the notation - */ - public ModifiableNotationSpecificPlugins(final Notation notation){ - this.notation = notation; - - modules = new LinkedList(); - } - - /** - * Adds a new module related to the notation. - * - * @param module new module - */ - public void addModule(final Module module){ - modules.add(module); - } - - /** - * Returns notation object. - * - * @return notation object - */ - public Notation getNotation() { - return notation; - } - - /** - * Returns list of notation in the same order as they were specified in plugin configuration file and have been - * instantiated. - * - * @return list of modules - */ - public List getModules() { - return modules; - } - - /** - * Returns already stored module according to it's identifier. - * - * @param moduleIdentifier is the identifier of required module - * @return module, if any with given identifier is found, null otherwise - */ - public Module getModule(final String moduleIdentifier){ - for(final Module module : modules){ - if(module.getIdentifier().equals(moduleIdentifier)){ - return module; - } - } - - return null; - } - - /** - * Checks whether a module with given identifier has been already loaded and stored. - * - * @param moduleIdentifier is the required module's identifier - * @return true, if such a module has already been loaded and stored, false otherwise - */ - public boolean existModule(final String moduleIdentifier){ - return getModule(moduleIdentifier) != null; - - } - -} +package cz.cvut.promod.services.pluginLoaderService.utils; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; +import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; + +import java.util.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 0:32:00, 22.4.2010 + */ + +/** + * Implementation very similar to the NotationSpecificPlugins class, but this one is used just + * for application start-up purposes and it is possible to add or removes modules. + * + * Only PluginLoaderService uses this class. + */ +public class ModifiableNotationSpecificPlugins { + + private final Notation notation; + + private final List modules; + + + /** + * Constructs new ModifiableNotationSpecificPlugins for the specified notation. + * + * @param notation is the notation + */ + public ModifiableNotationSpecificPlugins(final Notation notation){ + this.notation = notation; + + modules = new LinkedList(); + } + + /** + * Adds a new module related to the notation. + * + * @param module new module + */ + public void addModule(final Module module){ + modules.add(module); + } + + /** + * Returns notation object. + * + * @return notation object + */ + public Notation getNotation() { + return notation; + } + + /** + * Returns list of notation in the same order as they were specified in plugin configuration file and have been + * instantiated. + * + * @return list of modules + */ + public List getModules() { + return modules; + } + + /** + * Returns already stored module according to it's identifier. + * + * @param moduleIdentifier is the identifier of required module + * @return module, if any with given identifier is found, null otherwise + */ + public Module getModule(final String moduleIdentifier){ + for(final Module module : modules){ + if(module.getIdentifier().equals(moduleIdentifier)){ + return module; + } + } + + return null; + } + + /** + * Checks whether a module with given identifier has been already loaded and stored. + * + * @param moduleIdentifier is the required module's identifier + * @return true, if such a module has already been loaded and stored, false otherwise + */ + public boolean existModule(final String moduleIdentifier){ + return getModule(moduleIdentifier) != null; + + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/NotationSpecificPlugins.java b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/NotationSpecificPlugins.java index 937ec97..b17725f 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/NotationSpecificPlugins.java +++ b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/NotationSpecificPlugins.java @@ -1,109 +1,109 @@ -package cz.cvut.promod.services.pluginLoaderService.utils; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; -import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; - -import java.util.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:34:23, 12.10.2009 - */ - -/** - * NotationSpecificPlugins is holder for notation and it's related modules. - * - * It is not possible to change the list holding modules. - */ -public final class NotationSpecificPlugins { - - private final Notation notation; - - private final List modules; - - - /** - * Constructs new NotationSpecificPlugins for the specified notation. - * - * @param notation is the notation - * @param modules unchangeable list of plugins - */ - public NotationSpecificPlugins(final Notation notation, final List modules){ - this.notation = notation; - - this.modules = modules; - } - - /** - * Returns notation object. - * - * @return notation object - */ - public Notation getNotation() { - return notation; - } - - /** - * Returns list of notation in the same order as they were specified in plugin configuration file and have been - * instantiated. - * - * @return list of modules - */ - public List getModules() { - return modules; - } - - /** - * Returns already stored module according to it's identifier. - * - * @param moduleIdentifier is the identifier of required module - * @return module, if any with given identifier is found, null otherwise - */ - public Module getModule(final String moduleIdentifier){ - for(final Module module : modules){ - if(module.getIdentifier().equals(moduleIdentifier)){ - return module; - } - } - - return null; - } - - /** - * Checks whether a module with given identifier has been already loaded and stored. - * - * @param moduleIdentifier is the required module's identifier - * @return true, if such a module has already been loaded and stored, false otherwise - */ - public boolean existModule(final String moduleIdentifier){ - return getModule(moduleIdentifier) != null; - - } - - /** - * Returns dockable frame data defined by the notation and all it's related modules. - * - * @return dockable frame data defined by the notation and all it's related modules - */ - public Collection getDockableFramesData(){ - final Collection dockableFrameData = new HashSet(); - - final Set notationFrameData = getNotation().getDockableFrames(); - - if(notationFrameData != null){ - dockableFrameData.addAll(notationFrameData); - } - - for(final Module module : getModules()){ - final Set moduleFrameData = module.getDockableFrames(); - - if(moduleFrameData != null){ - dockableFrameData.addAll(module.getDockableFrames()); - } - } - - return dockableFrameData; - } -} +package cz.cvut.promod.services.pluginLoaderService.utils; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; +import cz.cvut.promod.plugin.notationSpecificPlugIn.DockableFrameData; + +import java.util.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:34:23, 12.10.2009 + */ + +/** + * NotationSpecificPlugins is holder for notation and it's related modules. + * + * It is not possible to change the list holding modules. + */ +public final class NotationSpecificPlugins { + + private final Notation notation; + + private final List modules; + + + /** + * Constructs new NotationSpecificPlugins for the specified notation. + * + * @param notation is the notation + * @param modules unchangeable list of plugins + */ + public NotationSpecificPlugins(final Notation notation, final List modules){ + this.notation = notation; + + this.modules = modules; + } + + /** + * Returns notation object. + * + * @return notation object + */ + public Notation getNotation() { + return notation; + } + + /** + * Returns list of notation in the same order as they were specified in plugin configuration file and have been + * instantiated. + * + * @return list of modules + */ + public List getModules() { + return modules; + } + + /** + * Returns already stored module according to it's identifier. + * + * @param moduleIdentifier is the identifier of required module + * @return module, if any with given identifier is found, null otherwise + */ + public Module getModule(final String moduleIdentifier){ + for(final Module module : modules){ + if(module.getIdentifier().equals(moduleIdentifier)){ + return module; + } + } + + return null; + } + + /** + * Checks whether a module with given identifier has been already loaded and stored. + * + * @param moduleIdentifier is the required module's identifier + * @return true, if such a module has already been loaded and stored, false otherwise + */ + public boolean existModule(final String moduleIdentifier){ + return getModule(moduleIdentifier) != null; + + } + + /** + * Returns dockable frame data defined by the notation and all it's related modules. + * + * @return dockable frame data defined by the notation and all it's related modules + */ + public Collection getDockableFramesData(){ + final Collection dockableFrameData = new HashSet(); + + final Set notationFrameData = getNotation().getDockableFrames(); + + if(notationFrameData != null){ + dockableFrameData.addAll(notationFrameData); + } + + for(final Module module : getModules()){ + final Set moduleFrameData = module.getDockableFrames(); + + if(moduleFrameData != null){ + dockableFrameData.addAll(module.getDockableFrames()); + } + } + + return dockableFrameData; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/PluginDetails.java b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/PluginDetails.java index 5108ea1..c77717e 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/PluginDetails.java +++ b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/PluginDetails.java @@ -1,103 +1,103 @@ -package cz.cvut.promod.services.pluginLoaderService.utils; - -import java.util.List; -import java.util.LinkedList; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:50:27, 4.2.2010 - */ - -/** - * Holds loaded info about the plugin(s) from the plugin configuration file. - */ -public class PluginDetails{ - - private final String clazz; - - private final String config; - - private final String alias; - - private final List modules; - - /** - * Constructs new PluginDetails object. - * - * @param clazz is the plugin's class ful qualified name - * @param config is the plugin's configuration file - * @param alias is the plugin's alias - */ - public PluginDetails(final String clazz, final String config, final String alias) { - this.clazz = clazz; - this.config = config; - this.alias = alias; - - modules = new LinkedList(); - } - - /** - * Notations have it's modules, these modules are stored in list - * - * Do not use with extensions! - * - * @param pluginDetails is the plugin detail of the module - */ - public void addPluginDetails(final PluginDetails pluginDetails){ - modules.add(pluginDetails); - } - - /** - * Returns the full qualified class name. - * - * @return full qualified class name - */ - public String getClazz() { - return clazz; - } - - /** - * Returns the plugin's configuration class. - * - * @return plugin's configuration file - */ - public String getConfig() { - return config; - } - - /** - * Returns the plugin's alias. - * - * @return plugin's alias - */ - public String getAlias() { - return alias; - } - - /** - * Returns all modules of the notation. - * - * Do not use with extensions! - * - * @return the list of notation's modules. - */ - public List getModules() { - return modules; - } - - /** - * Pops loaded module = returns module in style FIFO - * - * Do not use with extensions. - * - * @return the most earlier loaded module in the list - */ - public PluginDetails pop() { - if(modules.size() != 0){ - return modules.remove(0); - } - - return null; - } -} +package cz.cvut.promod.services.pluginLoaderService.utils; + +import java.util.List; +import java.util.LinkedList; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:50:27, 4.2.2010 + */ + +/** + * Holds loaded info about the plugin(s) from the plugin configuration file. + */ +public class PluginDetails{ + + private final String clazz; + + private final String config; + + private final String alias; + + private final List modules; + + /** + * Constructs new PluginDetails object. + * + * @param clazz is the plugin's class ful qualified name + * @param config is the plugin's configuration file + * @param alias is the plugin's alias + */ + public PluginDetails(final String clazz, final String config, final String alias) { + this.clazz = clazz; + this.config = config; + this.alias = alias; + + modules = new LinkedList(); + } + + /** + * Notations have it's modules, these modules are stored in list + * + * Do not use with extensions! + * + * @param pluginDetails is the plugin detail of the module + */ + public void addPluginDetails(final PluginDetails pluginDetails){ + modules.add(pluginDetails); + } + + /** + * Returns the full qualified class name. + * + * @return full qualified class name + */ + public String getClazz() { + return clazz; + } + + /** + * Returns the plugin's configuration class. + * + * @return plugin's configuration file + */ + public String getConfig() { + return config; + } + + /** + * Returns the plugin's alias. + * + * @return plugin's alias + */ + public String getAlias() { + return alias; + } + + /** + * Returns all modules of the notation. + * + * Do not use with extensions! + * + * @return the list of notation's modules. + */ + public List getModules() { + return modules; + } + + /** + * Pops loaded module = returns module in style FIFO + * + * Do not use with extensions. + * + * @return the most earlier loaded module in the list + */ + public PluginDetails pop() { + if(modules.size() != 0){ + return modules.remove(0); + } + + return null; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/PluginLoadErrors.java b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/PluginLoadErrors.java index 518d68e..4bf35ab 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/PluginLoadErrors.java +++ b/IndependentModeler/src/cz/cvut/promod/services/pluginLoaderService/utils/PluginLoadErrors.java @@ -1,331 +1,331 @@ -package cz.cvut.promod.services.pluginLoaderService.utils; - -import cz.cvut.promod.services.ModelerSession; - -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 13:59:06, 12.12.2009 - */ - -/** - * PluginLoadErrors class make possible to collect error that occur during plugin loading and instantiating - * and publish them later. - */ -public class PluginLoadErrors { - - public static final String MISSING_XSD_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.missing.xsd"); - public static final String NO_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.noError"); - public static final String XML_PARSING_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.xmlParsing"); - public static final String CLASS_NAME_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.className"); - public static final String FIND_CLASS_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.findClass"); - public static final String CLASS_HIERARCHY_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.classHierarchy"); - public static final String INSTANTIATION_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.instantiation"); - public static final String NULLARY_NOTATION_NAME_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryNotationName"); - public static final String EMPTY_NOTATION_NAME = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyNotationName"); - public static final String NO_MODEL_FACTORY_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.noModelFactory"); - public static final String INVALID_MODEL_FACTORY_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.invalidModelFactory"); - public static final String NULLARY_ABBREVIATION_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryAbbreviation"); - public static final String EMPTY_ABREVIATION_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyAbbreviation"); - public static final String IO_CONTROLLER_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.ioController"); - public static final String NULLARY_FILE_EXTENSION_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryFileExtension"); - public static final String EMPTY_FILE_EXTENSION_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyFileExtension"); - public static final String NOTATION_IDENTIFIER_DUPLICITY = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.notationIdentifierDuplicity"); - public static final String NULLARY_PLUGIN_IDENTIFIER = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryPluginIdentifier"); - public static final String LIKE_MODELER_PLUGIN_IDENTIFIER_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.likeModelerpluginIdentifier"); - public static final String EMPTY_PLUGIN_IDENTIFIER_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyPluginIdentifier"); - public static final String NO_RELATED_NOTATION_IDENTIFIER = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.noRelatedNotationIdentifier"); - public static final String NULLARY_RELATED_NOTATION_IDENTIFIER_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryRelatedNotationIdentifier"); - public static final String EMPTY_RELATED_NOTATION_IDENTIFIER_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyRelatedNotationIdentifier"); - public static final String MODULE_IDENTIFIER_DUPLICITY_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.moduleIdentifierDuplicity"); - public static final String EXTENSION_IDENIFIER_DUPLICITY_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.extensionIdentifierDuplicity"); - public static final String PROJECT_FILE_LIKE_EXTENSION = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.projectFileLikeNotation"); - public static final String DUPLICITY_EXTENSION = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.notationExtensionDuplicity"); - public static final String TOO_LONG_IDENTIFIER = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.too.long.identifier"); - public static final String NULLARY_NAME_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryPluginName"); - public static final String EMPTY_NAME_ERROR = - ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyPluginName"); - - private final String alias; // alias as is in the properties file where all plugin are - - private String fullClassName = null; - - public enum ERRORS { - /** initial value, no error has occurred */ - noError, - - /** not possible to parse plugin definition file, file doesn't fulfil the xsd schema is one of possible reasons */ - missingXSD, - - /** not possible to parse plugin definition file, file doesn't fulfil the xsd schema is one of possible reasons */ - xmlParsing, - - /** invalid class name, null or empty */ - className, - - /** ClassLoader couldn't find the class */ - findClass, - - /** class does NOT implement necessary interface (Notation, Module, ...) */ - classHierarchy, - - /** and error during class instantiation has occurred */ - instantiation, - - /** notation returns nullary notation name */ - nullaryNotationName, - - /** notation returns an empty string as it's notation name */ - emptyNotationName, - - /** notation doesn't provide ModelFactory definition */ - noModelFactory, - - /** notation doesn't provide valid ModelFactory definition */ - invalidModelFactory, - - /** notation returns nullary abbreviation */ - nullaryAbbreviation, - - /** notation returns an empty String as it's abbreviation */ - emptyAbbreviation, - - /** notation doesn't provide IOController definition */ - ioController, - - /** notation's ioController provides nullary file extension */ - nullaryFileExtension, - - /** notation's ioController provides an empty string as it's file extension */ - emptyFileExtension, - - /** notation has the same file extension like the ProMod project file */ - projectFileLikeExtension, - - /** notation has the same file extension like the ProMod project file */ - notationExtensionDuplicity, - - /** notation has the same identifier as another notation that has been already loaded */ - notationIdentifierDuplicity, - - /** nullary plugin name */ - nullaryName, - - /** an empty string for plugin name */ - emptyName, - - /** plugin returns nullary identifier */ - nullaryPluginIdentifier, - - /** plugin returns identifier that is same like modeler identifier */ - likeModelerpluginIdentifier, - - /** plugin returns an empty string as it's identifier */ - emptyPluginIdentifier, - - /** plugin returns an too long identifier */ - tooLongPluginIdentifier, - - /** module provides no existing notation identifier */ - noRelatedNotationIdentifier, - - /** module provides nullary related notation identifier */ - nullaryRelatedNotationIdentifier, - - /** module provides an empty string as related notation identifier */ - emptyRelatedNotationIdentifier, - - /** more than one module for the same notation have the same identifier */ - moduleIdentifierDuplicity, - - /** extension has the same identifier as another extension that has been already loaded */ - extensionIdentifierDuplicity, - } - - private ERRORS error = ERRORS.noError; - - private String message = null; - - /** - * Constructs new PluginLoadErrors for plugin with alias. - * - * @param alias is the plugin's alias - */ - public PluginLoadErrors(final String alias) { - this.alias = alias; - } - - /** - * Stores error type that has occurred and adds the error to the list of errors. - * - * @param error is the error that has occurred - * @param errorList is the list of errors - */ - public void reportError(final ERRORS error, final List errorList){ - this.error = error; - errorList.add(this); - } - - /** - * Stores error type that has occurred with additional message specification and - * adds the error to the list of errors. - * - * @param error is the error that has occurred - * @param message is detail info about the error - * @param errorList is the list of errors - */ - public void reportError(final ERRORS error, final String message, final List errorList){ - this.error = error; - this.message = message; - errorList.add(this); - } - - /** - * Returns the error type. - * - * @return error type - */ - public ERRORS getError() { - return error; - } - - /** - * Returns translation for the error. - * - * @return translated error information - */ - public String getTranslatedError(){ - switch (error){ - case missingXSD: - return MISSING_XSD_ERROR; - case noError: - return NO_ERROR; - case xmlParsing: - return XML_PARSING_ERROR; - case className: - return CLASS_NAME_ERROR; - case findClass: - return FIND_CLASS_ERROR; - case classHierarchy: - return CLASS_HIERARCHY_ERROR; - case instantiation: - return INSTANTIATION_ERROR; - case nullaryNotationName: - return NULLARY_NOTATION_NAME_ERROR; - case emptyNotationName: - return EMPTY_NOTATION_NAME; - case noModelFactory: - return NO_MODEL_FACTORY_ERROR; - case invalidModelFactory: - return INVALID_MODEL_FACTORY_ERROR; - case nullaryAbbreviation: - return NULLARY_ABBREVIATION_ERROR; - case emptyAbbreviation: - return EMPTY_ABREVIATION_ERROR; - case ioController: - return IO_CONTROLLER_ERROR; - case nullaryFileExtension: - return NULLARY_FILE_EXTENSION_ERROR; - case emptyFileExtension: - return EMPTY_FILE_EXTENSION_ERROR; - case notationIdentifierDuplicity: - return NOTATION_IDENTIFIER_DUPLICITY; - case nullaryPluginIdentifier: - return NULLARY_PLUGIN_IDENTIFIER; - case likeModelerpluginIdentifier: - return LIKE_MODELER_PLUGIN_IDENTIFIER_ERROR; - case emptyPluginIdentifier: - return EMPTY_PLUGIN_IDENTIFIER_ERROR; - case noRelatedNotationIdentifier: - return NO_RELATED_NOTATION_IDENTIFIER; - case nullaryRelatedNotationIdentifier: - return NULLARY_RELATED_NOTATION_IDENTIFIER_ERROR; - case emptyRelatedNotationIdentifier: - return EMPTY_RELATED_NOTATION_IDENTIFIER_ERROR; - case moduleIdentifierDuplicity: - return MODULE_IDENTIFIER_DUPLICITY_ERROR; - case extensionIdentifierDuplicity: - return EXTENSION_IDENIFIER_DUPLICITY_ERROR; - case nullaryName: - return NULLARY_NAME_ERROR; - case emptyName: - return EMPTY_NAME_ERROR; - case projectFileLikeExtension: - return PROJECT_FILE_LIKE_EXTENSION; - case notationExtensionDuplicity: - return DUPLICITY_EXTENSION; - case tooLongPluginIdentifier: - return TOO_LONG_IDENTIFIER; - default: - return error.toString(); - } - } - - /** - * Returns the detail message about the error - * - * @return detail info about the error - */ - public String getMessage() { - return message; - } - - /** - * Returns the plugin's alias - * - * @return plugin's alias - */ - public String getAlias() { - return alias; - } - - /** - * Sets the plugin's class qualified name for better detail about the pertinent error - * - * @param fullClassName is the plugin's class qualified name - */ - public void setFullClassName(final String fullClassName) { - this.fullClassName = fullClassName; - } - - /** - * Returns the plugin's class qualified name for better detail about the pertinent error - * - * @return plugin's class qualified name for better detail about the pertinent error - */ - public String getFullClassName() { - return fullClassName; - } - -} +package cz.cvut.promod.services.pluginLoaderService.utils; + +import cz.cvut.promod.services.ModelerSession; + +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 13:59:06, 12.12.2009 + */ + +/** + * PluginLoadErrors class make possible to collect error that occur during plugin loading and instantiating + * and publish them later. + */ +public class PluginLoadErrors { + + public static final String MISSING_XSD_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.missing.xsd"); + public static final String NO_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.noError"); + public static final String XML_PARSING_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.xmlParsing"); + public static final String CLASS_NAME_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.className"); + public static final String FIND_CLASS_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.findClass"); + public static final String CLASS_HIERARCHY_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.classHierarchy"); + public static final String INSTANTIATION_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.instantiation"); + public static final String NULLARY_NOTATION_NAME_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryNotationName"); + public static final String EMPTY_NOTATION_NAME = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyNotationName"); + public static final String NO_MODEL_FACTORY_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.noModelFactory"); + public static final String INVALID_MODEL_FACTORY_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.invalidModelFactory"); + public static final String NULLARY_ABBREVIATION_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryAbbreviation"); + public static final String EMPTY_ABREVIATION_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyAbbreviation"); + public static final String IO_CONTROLLER_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.ioController"); + public static final String NULLARY_FILE_EXTENSION_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryFileExtension"); + public static final String EMPTY_FILE_EXTENSION_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyFileExtension"); + public static final String NOTATION_IDENTIFIER_DUPLICITY = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.notationIdentifierDuplicity"); + public static final String NULLARY_PLUGIN_IDENTIFIER = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryPluginIdentifier"); + public static final String LIKE_MODELER_PLUGIN_IDENTIFIER_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.likeModelerpluginIdentifier"); + public static final String EMPTY_PLUGIN_IDENTIFIER_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyPluginIdentifier"); + public static final String NO_RELATED_NOTATION_IDENTIFIER = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.noRelatedNotationIdentifier"); + public static final String NULLARY_RELATED_NOTATION_IDENTIFIER_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryRelatedNotationIdentifier"); + public static final String EMPTY_RELATED_NOTATION_IDENTIFIER_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyRelatedNotationIdentifier"); + public static final String MODULE_IDENTIFIER_DUPLICITY_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.moduleIdentifierDuplicity"); + public static final String EXTENSION_IDENIFIER_DUPLICITY_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.extensionIdentifierDuplicity"); + public static final String PROJECT_FILE_LIKE_EXTENSION = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.projectFileLikeNotation"); + public static final String DUPLICITY_EXTENSION = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.notationExtensionDuplicity"); + public static final String TOO_LONG_IDENTIFIER = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.too.long.identifier"); + public static final String NULLARY_NAME_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.nullaryPluginName"); + public static final String EMPTY_NAME_ERROR = + ModelerSession.getCommonResourceBundle().getString("pluginLoaderService.error.emptyPluginName"); + + private final String alias; // alias as is in the properties file where all plugin are + + private String fullClassName = null; + + public enum ERRORS { + /** initial value, no error has occurred */ + noError, + + /** not possible to parse plugin definition file, file doesn't fulfil the xsd schema is one of possible reasons */ + missingXSD, + + /** not possible to parse plugin definition file, file doesn't fulfil the xsd schema is one of possible reasons */ + xmlParsing, + + /** invalid class name, null or empty */ + className, + + /** ClassLoader couldn't find the class */ + findClass, + + /** class does NOT implement necessary interface (Notation, Module, ...) */ + classHierarchy, + + /** and error during class instantiation has occurred */ + instantiation, + + /** notation returns nullary notation name */ + nullaryNotationName, + + /** notation returns an empty string as it's notation name */ + emptyNotationName, + + /** notation doesn't provide ModelFactory definition */ + noModelFactory, + + /** notation doesn't provide valid ModelFactory definition */ + invalidModelFactory, + + /** notation returns nullary abbreviation */ + nullaryAbbreviation, + + /** notation returns an empty String as it's abbreviation */ + emptyAbbreviation, + + /** notation doesn't provide IOController definition */ + ioController, + + /** notation's ioController provides nullary file extension */ + nullaryFileExtension, + + /** notation's ioController provides an empty string as it's file extension */ + emptyFileExtension, + + /** notation has the same file extension like the ProMod project file */ + projectFileLikeExtension, + + /** notation has the same file extension like the ProMod project file */ + notationExtensionDuplicity, + + /** notation has the same identifier as another notation that has been already loaded */ + notationIdentifierDuplicity, + + /** nullary plugin name */ + nullaryName, + + /** an empty string for plugin name */ + emptyName, + + /** plugin returns nullary identifier */ + nullaryPluginIdentifier, + + /** plugin returns identifier that is same like modeler identifier */ + likeModelerpluginIdentifier, + + /** plugin returns an empty string as it's identifier */ + emptyPluginIdentifier, + + /** plugin returns an too long identifier */ + tooLongPluginIdentifier, + + /** module provides no existing notation identifier */ + noRelatedNotationIdentifier, + + /** module provides nullary related notation identifier */ + nullaryRelatedNotationIdentifier, + + /** module provides an empty string as related notation identifier */ + emptyRelatedNotationIdentifier, + + /** more than one module for the same notation have the same identifier */ + moduleIdentifierDuplicity, + + /** extension has the same identifier as another extension that has been already loaded */ + extensionIdentifierDuplicity, + } + + private ERRORS error = ERRORS.noError; + + private String message = null; + + /** + * Constructs new PluginLoadErrors for plugin with alias. + * + * @param alias is the plugin's alias + */ + public PluginLoadErrors(final String alias) { + this.alias = alias; + } + + /** + * Stores error type that has occurred and adds the error to the list of errors. + * + * @param error is the error that has occurred + * @param errorList is the list of errors + */ + public void reportError(final ERRORS error, final List errorList){ + this.error = error; + errorList.add(this); + } + + /** + * Stores error type that has occurred with additional message specification and + * adds the error to the list of errors. + * + * @param error is the error that has occurred + * @param message is detail info about the error + * @param errorList is the list of errors + */ + public void reportError(final ERRORS error, final String message, final List errorList){ + this.error = error; + this.message = message; + errorList.add(this); + } + + /** + * Returns the error type. + * + * @return error type + */ + public ERRORS getError() { + return error; + } + + /** + * Returns translation for the error. + * + * @return translated error information + */ + public String getTranslatedError(){ + switch (error){ + case missingXSD: + return MISSING_XSD_ERROR; + case noError: + return NO_ERROR; + case xmlParsing: + return XML_PARSING_ERROR; + case className: + return CLASS_NAME_ERROR; + case findClass: + return FIND_CLASS_ERROR; + case classHierarchy: + return CLASS_HIERARCHY_ERROR; + case instantiation: + return INSTANTIATION_ERROR; + case nullaryNotationName: + return NULLARY_NOTATION_NAME_ERROR; + case emptyNotationName: + return EMPTY_NOTATION_NAME; + case noModelFactory: + return NO_MODEL_FACTORY_ERROR; + case invalidModelFactory: + return INVALID_MODEL_FACTORY_ERROR; + case nullaryAbbreviation: + return NULLARY_ABBREVIATION_ERROR; + case emptyAbbreviation: + return EMPTY_ABREVIATION_ERROR; + case ioController: + return IO_CONTROLLER_ERROR; + case nullaryFileExtension: + return NULLARY_FILE_EXTENSION_ERROR; + case emptyFileExtension: + return EMPTY_FILE_EXTENSION_ERROR; + case notationIdentifierDuplicity: + return NOTATION_IDENTIFIER_DUPLICITY; + case nullaryPluginIdentifier: + return NULLARY_PLUGIN_IDENTIFIER; + case likeModelerpluginIdentifier: + return LIKE_MODELER_PLUGIN_IDENTIFIER_ERROR; + case emptyPluginIdentifier: + return EMPTY_PLUGIN_IDENTIFIER_ERROR; + case noRelatedNotationIdentifier: + return NO_RELATED_NOTATION_IDENTIFIER; + case nullaryRelatedNotationIdentifier: + return NULLARY_RELATED_NOTATION_IDENTIFIER_ERROR; + case emptyRelatedNotationIdentifier: + return EMPTY_RELATED_NOTATION_IDENTIFIER_ERROR; + case moduleIdentifierDuplicity: + return MODULE_IDENTIFIER_DUPLICITY_ERROR; + case extensionIdentifierDuplicity: + return EXTENSION_IDENIFIER_DUPLICITY_ERROR; + case nullaryName: + return NULLARY_NAME_ERROR; + case emptyName: + return EMPTY_NAME_ERROR; + case projectFileLikeExtension: + return PROJECT_FILE_LIKE_EXTENSION; + case notationExtensionDuplicity: + return DUPLICITY_EXTENSION; + case tooLongPluginIdentifier: + return TOO_LONG_IDENTIFIER; + default: + return error.toString(); + } + } + + /** + * Returns the detail message about the error + * + * @return detail info about the error + */ + public String getMessage() { + return message; + } + + /** + * Returns the plugin's alias + * + * @return plugin's alias + */ + public String getAlias() { + return alias; + } + + /** + * Sets the plugin's class qualified name for better detail about the pertinent error + * + * @param fullClassName is the plugin's class qualified name + */ + public void setFullClassName(final String fullClassName) { + this.fullClassName = fullClassName; + } + + /** + * Returns the plugin's class qualified name for better detail about the pertinent error + * + * @return plugin's class qualified name for better detail about the pertinent error + */ + public String getFullClassName() { + return fullClassName; + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectControlService.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectControlService.java index 2b2001c..9542124 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectControlService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectControlService.java @@ -1,285 +1,285 @@ -package cz.cvut.promod.services.projectService; - -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; -import cz.cvut.promod.services.projectService.treeProjectNode.listener.ProjectDiagramListener; -import cz.cvut.promod.services.projectService.results.AddProjectItemResult; -import cz.cvut.promod.services.projectService.results.LoadProjectResult; -import cz.cvut.promod.services.projectService.results.SaveProjectResult; - -import javax.swing.tree.*; -import java.util.List; -import java.io.File; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:48:28, 10.10.2009 - */ -public interface ProjectControlService extends ProjectService{ - - /** - * Returns the model used by the project navigation tree. - * - * One is supposed to avoid using this model. Use other methods to changes tree state! - * - * @return project navigation tree model - */ - public DefaultTreeModel getProjectTreeModel(); - - /** - * Set the required item in the project navigation tree. - * - * @param treePath is the tree path to be selected in the project navigation tree - */ - public void setSelectedItem(final TreePath treePath); - - /** - * Adds new project item to the project navigation tree. Do not store anything on the file system (for this use - * synchronization). - * - * Be careful that project name can have any project name (not null or empty), but some illegal - * names wont be possible to save to the file system during synchronization. - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils to check correctness of name - * - * @param projectRoot is the project root of the project that is supposed to be added to the project navigation - * tree. The display name cannot be null, an empty string and cannot contain any disallowed symbols. - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more info about disallowed symbols - * - * @param select if true, the newly added project item (project) will be selected in project tree navigation - * - * @return an object of AddProjectItemResult representing result of the operation - * - * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result - * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error - * message - */ - public AddProjectItemResult addProject(final ProjectRoot projectRoot, final boolean select); - - - /** - * Adds a new subfolder with given name to the required tree path in the project navigation tree. - * The required tree path has to be a valid tree in the project navigation tree and the last path - * component is supposed to be a project container (project root or a subfolder). One can never add - * subfolder under a diagram node. - * - * @param subFolderName is the name for the new subfolder, cannot by nullary or an empty string. It cannot contains - * any disallowed symbols as well. - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about disallowed symbols - * - * @param parentTreePath is the tree path to the parent node, under that is the the new subfolder supposed to - * be added. Has to be valid. - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about path validity - * - * @param select if true, the newly added subfolder node will be selected in project tree navigation - * - * @return an object of AddProjectItemResult representing result of the operation - * - * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result - * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error - * message - */ - public AddProjectItemResult addSubFolder(final String subFolderName, - final TreePath parentTreePath, - final boolean select); - - /** - * Adds a new subfolder with given name to the tree path of the closest project container in the project - * navigation tree. - * - * @param subFolderName is the name for the new subfolder, cannot by nullary or an empty string. It cannot contains - * any disallowed symbols as well. - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about disallowed symbols - * - * @param select if true, the newly added subfolder node will be selected in project tree navigation - * - * @return an object of AddProjectItemResult representing result of the operation - * - * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result - * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error - * message - */ - public AddProjectItemResult addSubFolder(final String subFolderName, final boolean select); - - /** - * Adds a new project diagram under specified parent node to the project navigation tree. One cannot save - * 2 diagrams with the same name and the same notation under one parent node. - * - * Note: It is possible to insert more than just one diagram having the same name under one parent node - * in the project navigation tree, but each of these diagrams has to be of a different notation - * - * @param projectDiagram is the project diagram that is supposed to be inserted to the project navigation tree. The - * name cannot contain any disallowed symbols. - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about disallowed symbols - * - * @param parentTreePath is the path to the parent node, under that is the project diagram supposed to be inserted. - * The tree path has to be valid and the last path component has to be a project container (project root or - * subfolder) - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about path validity - * - * @param select if true, the newly added diagram node will be selected in project tree navigation - * - * @return an object of AddProjectItemResult representing result of the operation - * - * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result - * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error - * message - */ - public AddProjectItemResult addDiagram(final ProjectDiagram projectDiagram, - final TreePath parentTreePath, - final boolean select); - - /** - * Adds a new project diagram to the tree path of the closest project container in the project - * navigation tree. - * - * Note: It is possible to insert more than just one diagram having the same name under one parent node - * in the project navigation tree, but each of these diagrams has to be of a different notation - * - * @param projectDiagram is the project diagram that is supposed to be inserted to the project navigation tree. The - * name cannot contain any disallowed symbols. - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about disallowed symbols - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about path validity - * - * @param select if true, the newly added diagram node will be selected in project tree navigation - * - * @return an object of AddProjectItemResult representing result of the operation - * - * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result - * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error - * message - */ - public AddProjectItemResult addDiagram(final ProjectDiagram projectDiagram, - final boolean select); - - /** - * Removes project item specified by the argument from the project navigation tree. - * - * If the project item that is supposed to be deleted is currently selected or it's any child, - * then the parent of this item will selected automatically. - * - * If the item to be deleted is or contains some project diagrams, then REMOVE event of this items - * is automatically dispatched. - * - * The project diagram is automatically removed. - * - * @param treePath specifies the project item, that is supposed to be removed - * - * @return file system path to the item, that was deleted, null if any error occurs - */ - public String removeProjectItem(final TreePath treePath); - - /** - * Synchronization from the project navigation tree to the file system. - * - * It is possible to run this sync only from EventDispatcherThread. - * - * @param treePath is the tree path to the root of the sub-tree that is supposed to be synchronized. - * If the last path component's user's object is any instance if ProjectDiagram, the synchronization is - * performed only on this diagram. If the last path component's user object is any implementation of - * ProjectContainer interface than this node is taken as the root of the sub-tree where will be - * synchronization performed. - * - * @param addProjectItems indicates whether new items are supposed to be created on the file system if there are missing - * @param overwriteProjectItems indicates whether diagrams that already exists on the file system are supposed to be overwritten - * @param deleteProjectItems indicates whether no project items (files or diagrams) are supposed to be deleted from file system - * one should be very careful when using this flag, because all deletion are un-doable. - * @param cancelable if true, the the synchronization can be canceled by the user - * @return true if no error has occurred during synchronization, false otherwise - */ - public boolean synchronize(final TreePath treePath, - final boolean addProjectItems, - final boolean overwriteProjectItems, - final boolean deleteProjectItems, - final boolean cancelable); - - /** - * Synchronization from the file system to the project navigation. - * - * It is possible to run this sync only from EventDispatcherThread. - * - * @param projectFile is the actual project file of the project, the placement of the project file is the - * file system location from where the synchronization starts (can be specify by the path offset) - * @param pathOffset is the specification of a particular directory extending the project file location from where - * the synchronization supposed to start. E.g. the project file location is D:\Project\MyProject.pmp. The path - * offset is overview/diagrams. So the synchronization will start from the location D:\Project\overview\diagrams. - * @param addProjectItems indicates whether new items are supposed to be created in the project navigation if there are missing - * @param overwriteProjectItems indicates whether diagrams that already exists in the project navigation are supposed to be overwritten - * @param deleteProjectItems indicates whether no project items are supposed to be deleted from the project navigation during synchronization - * @param cancelable if true, the the synchronization can be canceled by the user - * @return true if no error has occurred during synchronization, false otherwise - */ - public boolean synchronize(final File projectFile, - final List pathOffset, - final boolean addProjectItems, - final boolean overwriteProjectItems, - final boolean deleteProjectItems, - final boolean cancelable); - - /** - * Save the project root represented by the tree path to the project root. - * This method automatically overwrites the old file, if any exists. One should always use - * something like new File().exists() to be sure. If the required - * directory structure doesn't exist then this structure is automatically created for you. - * - * Note, that this method uses a static method of ProjectFileSave class - * - * @see cz.cvut.promod.services.projectService.localIO.ProjectFileSaver to save the project with formatting - * enabled. One can use this static method straight instead of using this method. Then, you can let the - * saver omit the formatting to lower RAM consumption and increase performance. - * - * @param projectTreePath is the tree path to the project root in project navigation tree. The tree path has to be - * valid and tha last path component has to be a valid project root - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about tree path validity - * - * @return a value defined by the SaveProjectResult enumeration - * - * @see cz.cvut.promod.services.projectService.results.SaveProjectResult for more details about return values - * and it's conditions - */ - public SaveProjectResult saveProject(final TreePath projectTreePath); - - - /** - * Loads the project diagram and returns and object of LoadProjectResult class. - * - * @see cz.cvut.promod.services.projectService.results.LoadProjectResult - * - * @param projectFile is the file specifynig the ProMod project file - * - * @return an object of LoadProjectResult class holding the project root and other info - */ - public LoadProjectResult loadProject(final File projectFile); - - /** - * Switch one project diagram for another. All listeners that have been registered with the old project diagram - * will be registered with the new diagram diagram. - * - * If any of the project diagrams is null then this method will have no effect. - * - * @param oldProjectDiagram is the old project diagram - * @param newProjectDiagram is the new project diagram - */ - public void switchChangePublisher(final ProjectDiagram oldProjectDiagram, final ProjectDiagram newProjectDiagram); - - /** - * Switch one project diagram listener for another. - * - * If any of the project diagram listeners is null then this method will have no effect. - * - * @param oldProjectDiagramListener is the old project diagram listener - * @param newProjectDiagramListener is the new project diagram listener - */ - public void switchChangeListener(final ProjectDiagramListener oldProjectDiagramListener, final ProjectDiagramListener newProjectDiagramListener); - -} +package cz.cvut.promod.services.projectService; + +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; +import cz.cvut.promod.services.projectService.treeProjectNode.listener.ProjectDiagramListener; +import cz.cvut.promod.services.projectService.results.AddProjectItemResult; +import cz.cvut.promod.services.projectService.results.LoadProjectResult; +import cz.cvut.promod.services.projectService.results.SaveProjectResult; + +import javax.swing.tree.*; +import java.util.List; +import java.io.File; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:48:28, 10.10.2009 + */ +public interface ProjectControlService extends ProjectService{ + + /** + * Returns the model used by the project navigation tree. + * + * One is supposed to avoid using this model. Use other methods to changes tree state! + * + * @return project navigation tree model + */ + public DefaultTreeModel getProjectTreeModel(); + + /** + * Set the required item in the project navigation tree. + * + * @param treePath is the tree path to be selected in the project navigation tree + */ + public void setSelectedItem(final TreePath treePath); + + /** + * Adds new project item to the project navigation tree. Do not store anything on the file system (for this use + * synchronization). + * + * Be careful that project name can have any project name (not null or empty), but some illegal + * names wont be possible to save to the file system during synchronization. + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils to check correctness of name + * + * @param projectRoot is the project root of the project that is supposed to be added to the project navigation + * tree. The display name cannot be null, an empty string and cannot contain any disallowed symbols. + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more info about disallowed symbols + * + * @param select if true, the newly added project item (project) will be selected in project tree navigation + * + * @return an object of AddProjectItemResult representing result of the operation + * + * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result + * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error + * message + */ + public AddProjectItemResult addProject(final ProjectRoot projectRoot, final boolean select); + + + /** + * Adds a new subfolder with given name to the required tree path in the project navigation tree. + * The required tree path has to be a valid tree in the project navigation tree and the last path + * component is supposed to be a project container (project root or a subfolder). One can never add + * subfolder under a diagram node. + * + * @param subFolderName is the name for the new subfolder, cannot by nullary or an empty string. It cannot contains + * any disallowed symbols as well. + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about disallowed symbols + * + * @param parentTreePath is the tree path to the parent node, under that is the the new subfolder supposed to + * be added. Has to be valid. + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about path validity + * + * @param select if true, the newly added subfolder node will be selected in project tree navigation + * + * @return an object of AddProjectItemResult representing result of the operation + * + * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result + * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error + * message + */ + public AddProjectItemResult addSubFolder(final String subFolderName, + final TreePath parentTreePath, + final boolean select); + + /** + * Adds a new subfolder with given name to the tree path of the closest project container in the project + * navigation tree. + * + * @param subFolderName is the name for the new subfolder, cannot by nullary or an empty string. It cannot contains + * any disallowed symbols as well. + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about disallowed symbols + * + * @param select if true, the newly added subfolder node will be selected in project tree navigation + * + * @return an object of AddProjectItemResult representing result of the operation + * + * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result + * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error + * message + */ + public AddProjectItemResult addSubFolder(final String subFolderName, final boolean select); + + /** + * Adds a new project diagram under specified parent node to the project navigation tree. One cannot save + * 2 diagrams with the same name and the same notation under one parent node. + * + * Note: It is possible to insert more than just one diagram having the same name under one parent node + * in the project navigation tree, but each of these diagrams has to be of a different notation + * + * @param projectDiagram is the project diagram that is supposed to be inserted to the project navigation tree. The + * name cannot contain any disallowed symbols. + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about disallowed symbols + * + * @param parentTreePath is the path to the parent node, under that is the project diagram supposed to be inserted. + * The tree path has to be valid and the last path component has to be a project container (project root or + * subfolder) + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about path validity + * + * @param select if true, the newly added diagram node will be selected in project tree navigation + * + * @return an object of AddProjectItemResult representing result of the operation + * + * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result + * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error + * message + */ + public AddProjectItemResult addDiagram(final ProjectDiagram projectDiagram, + final TreePath parentTreePath, + final boolean select); + + /** + * Adds a new project diagram to the tree path of the closest project container in the project + * navigation tree. + * + * Note: It is possible to insert more than just one diagram having the same name under one parent node + * in the project navigation tree, but each of these diagrams has to be of a different notation + * + * @param projectDiagram is the project diagram that is supposed to be inserted to the project navigation tree. The + * name cannot contain any disallowed symbols. + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about disallowed symbols + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about path validity + * + * @param select if true, the newly added diagram node will be selected in project tree navigation + * + * @return an object of AddProjectItemResult representing result of the operation + * + * @see cz.cvut.promod.services.projectService.results.AddProjectItemResult for more detail info about the result + * @see cz.cvut.promod.services.projectService.results.AddProjectItemStatus for more details about relevant error + * message + */ + public AddProjectItemResult addDiagram(final ProjectDiagram projectDiagram, + final boolean select); + + /** + * Removes project item specified by the argument from the project navigation tree. + * + * If the project item that is supposed to be deleted is currently selected or it's any child, + * then the parent of this item will selected automatically. + * + * If the item to be deleted is or contains some project diagrams, then REMOVE event of this items + * is automatically dispatched. + * + * The project diagram is automatically removed. + * + * @param treePath specifies the project item, that is supposed to be removed + * + * @return file system path to the item, that was deleted, null if any error occurs + */ + public String removeProjectItem(final TreePath treePath); + + /** + * Synchronization from the project navigation tree to the file system. + * + * It is possible to run this sync only from EventDispatcherThread. + * + * @param treePath is the tree path to the root of the sub-tree that is supposed to be synchronized. + * If the last path component's user's object is any instance if ProjectDiagram, the synchronization is + * performed only on this diagram. If the last path component's user object is any implementation of + * ProjectContainer interface than this node is taken as the root of the sub-tree where will be + * synchronization performed. + * + * @param addProjectItems indicates whether new items are supposed to be created on the file system if there are missing + * @param overwriteProjectItems indicates whether diagrams that already exists on the file system are supposed to be overwritten + * @param deleteProjectItems indicates whether no project items (files or diagrams) are supposed to be deleted from file system + * one should be very careful when using this flag, because all deletion are un-doable. + * @param cancelable if true, the the synchronization can be canceled by the user + * @return true if no error has occurred during synchronization, false otherwise + */ + public boolean synchronize(final TreePath treePath, + final boolean addProjectItems, + final boolean overwriteProjectItems, + final boolean deleteProjectItems, + final boolean cancelable); + + /** + * Synchronization from the file system to the project navigation. + * + * It is possible to run this sync only from EventDispatcherThread. + * + * @param projectFile is the actual project file of the project, the placement of the project file is the + * file system location from where the synchronization starts (can be specify by the path offset) + * @param pathOffset is the specification of a particular directory extending the project file location from where + * the synchronization supposed to start. E.g. the project file location is D:\Project\MyProject.pmp. The path + * offset is overview/diagrams. So the synchronization will start from the location D:\Project\overview\diagrams. + * @param addProjectItems indicates whether new items are supposed to be created in the project navigation if there are missing + * @param overwriteProjectItems indicates whether diagrams that already exists in the project navigation are supposed to be overwritten + * @param deleteProjectItems indicates whether no project items are supposed to be deleted from the project navigation during synchronization + * @param cancelable if true, the the synchronization can be canceled by the user + * @return true if no error has occurred during synchronization, false otherwise + */ + public boolean synchronize(final File projectFile, + final List pathOffset, + final boolean addProjectItems, + final boolean overwriteProjectItems, + final boolean deleteProjectItems, + final boolean cancelable); + + /** + * Save the project root represented by the tree path to the project root. + * This method automatically overwrites the old file, if any exists. One should always use + * something like new File().exists() to be sure. If the required + * directory structure doesn't exist then this structure is automatically created for you. + * + * Note, that this method uses a static method of ProjectFileSave class + * + * @see cz.cvut.promod.services.projectService.localIO.ProjectFileSaver to save the project with formatting + * enabled. One can use this static method straight instead of using this method. Then, you can let the + * saver omit the formatting to lower RAM consumption and increase performance. + * + * @param projectTreePath is the tree path to the project root in project navigation tree. The tree path has to be + * valid and tha last path component has to be a valid project root + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils for more details about tree path validity + * + * @return a value defined by the SaveProjectResult enumeration + * + * @see cz.cvut.promod.services.projectService.results.SaveProjectResult for more details about return values + * and it's conditions + */ + public SaveProjectResult saveProject(final TreePath projectTreePath); + + + /** + * Loads the project diagram and returns and object of LoadProjectResult class. + * + * @see cz.cvut.promod.services.projectService.results.LoadProjectResult + * + * @param projectFile is the file specifynig the ProMod project file + * + * @return an object of LoadProjectResult class holding the project root and other info + */ + public LoadProjectResult loadProject(final File projectFile); + + /** + * Switch one project diagram for another. All listeners that have been registered with the old project diagram + * will be registered with the new diagram diagram. + * + * If any of the project diagrams is null then this method will have no effect. + * + * @param oldProjectDiagram is the old project diagram + * @param newProjectDiagram is the new project diagram + */ + public void switchChangePublisher(final ProjectDiagram oldProjectDiagram, final ProjectDiagram newProjectDiagram); + + /** + * Switch one project diagram listener for another. + * + * If any of the project diagram listeners is null then this method will have no effect. + * + * @param oldProjectDiagramListener is the old project diagram listener + * @param newProjectDiagramListener is the new project diagram listener + */ + public void switchChangeListener(final ProjectDiagramListener oldProjectDiagramListener, final ProjectDiagramListener newProjectDiagramListener); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectControlServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectControlServiceImpl.java index 3b93484..6e6f250 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectControlServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectControlServiceImpl.java @@ -1,823 +1,823 @@ -package cz.cvut.promod.services.projectService; - -import javax.swing.tree.*; -import javax.swing.*; -import javax.xml.stream.XMLStreamException; -import javax.xml.transform.TransformerException; - -import org.apache.log4j.Logger; - -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.CancellationException; -import java.io.*; - -import cz.cvut.promod.services.projectService.treeProjectNode.*; -import cz.cvut.promod.services.projectService.treeProjectNode.listener.ProjectDiagramListener; -import cz.cvut.promod.services.projectService.localIO.ProjectFileSaver; -import cz.cvut.promod.services.projectService.localIO.ProjectFileLoader; -import cz.cvut.promod.services.projectService.syncWorkers.SyncFromFSWorker; -import cz.cvut.promod.services.projectService.syncWorkers.SyncFromPNWorker; -import cz.cvut.promod.services.projectService.dialogs.SyncDialog; -import cz.cvut.promod.services.projectService.results.AddProjectItemResult; -import cz.cvut.promod.services.projectService.results.LoadProjectResult; -import cz.cvut.promod.services.projectService.results.AddProjectItemStatus; -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.results.SaveProjectResult; -import cz.cvut.promod.services.ModelerSession; -import com.jgoodies.binding.beans.Model; -import com.jgoodies.binding.value.ValueModel; -import com.jgoodies.binding.PresentationModel; -import foxtrot.Task; -import foxtrot.Worker; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:50:24, 10.10.2009 - */ - -/** - * ProjectControlService implementation.. - */ -public class ProjectControlServiceImpl extends Model implements ProjectControlService, ProjectDiagramListener{ - - private final Logger LOG = Logger.getLogger(ProjectControlServiceImpl.class); - - private static final String SYNC_FROM_PN_TITLE_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.fromPN.title"); - - private final DefaultTreeModel treeModel; - private final DefaultMutableTreeNode rootNode; - - public static final String PROPERTY_SELECTED_TREE_PATH = "selectedTreePath"; - private TreePath selectedTreePath; - - private final TreePath rootTreePath; - - private final Map> listenerMap; - - - public ProjectControlServiceImpl(){ - rootNode = new DefaultMutableTreeNode("ProjectsRoot"); - this.treeModel = new DefaultTreeModel(rootNode); - - rootTreePath = new TreePath(rootNode); - - listenerMap = new HashMap>(); - } - - /** {@inheritDoc} */ - public boolean check() { - return true; - } - - /** {@inheritDoc} */ - public String getSelectedProjectNotationIndentifier() { - final ProjectDiagram projectDiagram; - - try{ - if(getSelectedTreePath() != null){ - projectDiagram = (ProjectDiagram) ((DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent()).getUserObject(); - } else { - return null; - } - - } catch (final Exception exception){ - return null; - } - - return projectDiagram.getNotationIdentifier(); - } - - /** {@inheritDoc} */ - public DefaultTreeModel getProjectTreeModel() { - return treeModel; - } - - /** {@inheritDoc} */ - public AddProjectItemResult addProject(final ProjectRoot projectRoot, final boolean select) { - - final String projectName = projectRoot.getDisplayName(); - - if(!ProjectServiceUtils.isSyntacticallyCorrectName(projectName)){ - LOG.error("Invalid project name or project name containing disallowed symbol(s), project name: " + projectName); - return new AddProjectItemResult(AddProjectItemStatus.INVALID_NAME, null); - } - - if(!ProjectServiceUtils.isUniqueProjectContainerDisplayName(rootNode, projectName)){ - LOG.error("An attempt to add project with existing name has occurred."); - return new AddProjectItemResult(AddProjectItemStatus.NAME_DUPLICITY, null); - } - - final DefaultMutableTreeNode projectNode = new DefaultMutableTreeNode(projectRoot); - - treeModel.insertNodeInto(projectNode, rootNode, rootNode.getChildCount()); - - final TreePath treePath = new TreePath(rootNode).pathByAddingChild(projectNode); - - if(select){ - setSelectedItem(treePath); - } - - return - new AddProjectItemResult(AddProjectItemStatus.SUCCESS, treePath); - } - - /** {@inheritDoc} */ - public void setSelectedItem(TreePath treePath) { - if(treePath == null){ - LOG.error("Nullary path to select"); - return; - } - if(treePath.equals(rootTreePath)){ - LOG.debug("An attempt to select project tree root node has occurred. Selected items will be set to null."); - treePath = null; - } - if(getSelectedTreePath() == null){ - if(getSelectedTreePath() != treePath){ - this.selectedTreePath = treePath; - firePropertyChange(PROPERTY_SELECTED_TREE_PATH, null, getSelectedTreePath()); - } - } - else if( !getSelectedTreePath().equals(treePath)){ - final TreePath oldSelectedTreePath = this.getSelectedTreePath(); - this.selectedTreePath = treePath; - firePropertyChange(PROPERTY_SELECTED_TREE_PATH, oldSelectedTreePath, getSelectedTreePath()); - } - } - - /** {@inheritDoc} */ - public List getProjects(){ - final List projects = new LinkedList(); - - for(final TreePath treePath : getProjectPaths()){ - final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - - try{ - final ProjectRoot projectRoot = (ProjectRoot) projectNode.getUserObject(); - - projects.add(projectRoot); - - } catch (ClassCastException exception){ - LOG.fatal("Root node of project is not ProjectRoot."); - } - - } - - return projects; - } - - /** {@inheritDoc} */ - public List getProjectPaths() { - final List projectItems = new LinkedList(); - - for(int i = 0; i < rootNode.getChildCount(); i++){ - final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) rootNode.getChildAt(i); - - final TreePath treePath = new TreePath(rootNode); - projectItems.add(treePath.pathByAddingChild(projectNode)); - } - - return projectItems; - } - - /** {@inheritDoc} */ - public ProjectRoot getProject(String projectName) { - final TreePath treePath = getProjectPath(projectName); - - if(treePath != null){ - final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - - try{ - return (ProjectRoot) projectNode.getUserObject(); - - } catch (ClassCastException exception){ - LOG.fatal("Root node of project is not ProjectRoot."); - } - } - - return null; - } - - /** {@inheritDoc} */ - public DefaultMutableTreeNode getProjectTreeNode(final String projectName) { - final TreePath projectTreePath = getProjectPath(projectName); - - if(projectTreePath == null){ - return null; - } - - try{ - return (DefaultMutableTreeNode) projectTreePath.getLastPathComponent(); - } catch (ClassCastException exception){ - LOG.error("(Impossible to cast tree node to an instance of DefaultMutableTreeNode."); - return null; - } - } - - /** {@inheritDoc} */ - public TreePath getProjectPath(final String projectName) { - for(final TreePath treePath : getProjectPaths()){ - final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - - try{ - final ProjectRoot projectRoot = (ProjectRoot) projectNode.getUserObject(); - - if(projectRoot.getDisplayName().equals(projectName)){ - return treePath; - } - - } catch (ClassCastException exception){ - LOG.fatal("Root node of project is not ProjectRoot."); - } - } - - return null; - } - - /** {@inheritDoc} */ - public boolean isOpenedProject(String projectName) { - return getProjectPath(projectName) != null; - } - - /** {@inheritDoc} */ - public TreePath getSelectedTreePath() { - return selectedTreePath; - } - - /** {@inheritDoc} */ - public ValueModel getSelectedItem() { - final PresentationModel presentationModel = new PresentationModel(this); - - return presentationModel.getModel(PROPERTY_SELECTED_TREE_PATH); - } - - /** {@inheritDoc} */ - public AddProjectItemResult addSubFolder(final String subFolderName, final boolean select) { - if(getSelectedTreePath() != null){ - DefaultMutableTreeNode parent = (DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent(); - TreePath parentTreePath = getSelectedTreePath(); - - while(!ProjectServiceUtils.isProjectContainer(parent)){ - parentTreePath = parentTreePath.getParentPath(); - parent = (DefaultMutableTreeNode) parentTreePath.getLastPathComponent(); - - if(parent == rootNode){ - //any strange behavior occurred, should never happened, testing & debugging - LOG.error("No project container to place new subfolder"); - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - } - - return addSubFolder(subFolderName, parentTreePath, select); - - } - - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - - /** {@inheritDoc} */ - public AddProjectItemResult addSubFolder(final String subFolderName, - final TreePath parentTreePath, - final boolean select) { - - if(!ProjectServiceUtils.isSyntacticallyCorrectName(subFolderName)){ - LOG.error("Invalid subfolder name or name containing disallowed symbol(s), project name: " + subFolderName); - return new AddProjectItemResult(AddProjectItemStatus.INVALID_NAME, null); - } - - if(parentTreePath == null){ - LOG.error("Nullary parent tree path when adding new subfolder."); - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - - if(!ProjectServiceUtils.isValidTreePath(parentTreePath)){ - LOG.error("Parent tre e path is not valid."); - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - - if(!ProjectServiceUtils.isProjectContainer((DefaultMutableTreeNode) parentTreePath.getLastPathComponent())){ - LOG.error("Parent node is not a project container."); - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - - final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) parentTreePath.getLastPathComponent(); - - if(!ProjectServiceUtils.isUniqueProjectContainerDisplayName(parent, subFolderName)){ - LOG.error("An attempt to add subfolder to a level, where an item with the same display name has been already inserted."); - return new AddProjectItemResult(AddProjectItemStatus.NAME_DUPLICITY, null); - } - - final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(); - final ProjectSubFolder projectSubFolder = new ProjectSubFolder(subFolderName); - newNode.setUserObject(projectSubFolder); - - treeModel.insertNodeInto(newNode, parent, parent.getChildCount()); - - final TreePath treePath = parentTreePath.pathByAddingChild(newNode); - - if(select){ - //select and expand to the newly added node in project tree - setSelectedItem(treePath); - } - - LOG.info("New subfolder '" + projectSubFolder.getDisplayName() + "' has been added."); - - return new AddProjectItemResult(AddProjectItemStatus.SUCCESS, treePath); - } - - /** {@inheritDoc} */ - public AddProjectItemResult addDiagram(final ProjectDiagram projectDiagram, - final boolean select) { - - if(getSelectedTreePath() != null){ - DefaultMutableTreeNode parent = (DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent(); - TreePath parentTreePath = getSelectedTreePath(); - - while(!ProjectServiceUtils.isProjectContainer(parent)){ - parentTreePath = parentTreePath.getParentPath(); - parent = (DefaultMutableTreeNode) parentTreePath.getLastPathComponent(); - } - - return addDiagram(projectDiagram, parentTreePath, select); - } - - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - - /** {@inheritDoc} */ - public AddProjectItemResult addDiagram(final ProjectDiagram projectDiagram, - final TreePath parentTreePath, - final boolean select) { - - if(projectDiagram == null){ - return new AddProjectItemResult(AddProjectItemStatus.INVALID_ITEM_DATA, null); - } - - final String displayName = projectDiagram.getDisplayName(); - if(!ProjectServiceUtils.isSyntacticallyCorrectName(projectDiagram.getDisplayName())){ - LOG.error("Diagram name contains disallowed symbol(s), project name: " + projectDiagram.getDisplayName()); - return new AddProjectItemResult(AddProjectItemStatus.INVALID_NAME, null); - } - - final String notationIdentifier = projectDiagram.getNotationIdentifier(); - if(notationIdentifier == null || !ModelerSession.getNotationService().existNotation(notationIdentifier)){ - LOG.error("An attempt to create a new diagram with no existing notation identifier has occurred."); - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_NOTATION, null); - } - - if(parentTreePath == null){ - LOG.error("Nullary parent when adding new diagram"); - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - - if(!ProjectServiceUtils.isValidTreePath(parentTreePath)){ - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - - final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)parentTreePath.getLastPathComponent(); - - if(!ProjectServiceUtils.isProjectContainer(parent)){ - LOG.error("Last tree path component is not a project container"); - return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); - } - - final ProjectItem parentProjectItem = (ProjectItem) parent.getUserObject(); - - - if(!ProjectServiceUtils.isUniqueProjectDiagramName(parent, projectDiagram)){ - LOG.error("An attempt to add new diagram to a level, where an item with the same display name and notation has been already inserted."); - return new AddProjectItemResult(AddProjectItemStatus.NAME_DUPLICITY, null); - } - - final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(); - - newNode.setUserObject(projectDiagram); - - treeModel.insertNodeInto(newNode, parent, parent.getChildCount()); - - final TreePath treePath = parentTreePath.pathByAddingChild(newNode); - - //select and expand to the newly added node in project tree - if(select){ - setSelectedItem(treePath); - } - - LOG.info("New diagram has been added, " + parentProjectItem.getDisplayName() + " -> " + displayName + ", notation: "+ notationIdentifier + "."); - - return new AddProjectItemResult(AddProjectItemStatus.SUCCESS, treePath); - } - - /** {@inheritDoc} */ - public String removeProjectItem(final TreePath treePath) { - final String fileSystemPath = ProjectServiceUtils.getFileSystemPathToProjectItem(treePath); - - if(fileSystemPath == null){ - LOG.error("File system path to the project item couldn't be calculated."); - return null; - } - - final DefaultMutableTreeNode node; - try{ - node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - } catch (ClassCastException exception){ - LOG.error("All components in the project tree have to be an instance of the DefaultMutableTreeNode class."); - return null; - } - - // if the item or it's any child is currently selected, then select item's parent item - if(ProjectServiceUtils.isTreePathExtension(treePath, getSelectedTreePath())){ - LOG.debug("Selecting parent of the project tree item, that will be deleted."); - - setSelectedItem(treePath.getParentPath()); - } - - // publish change - if(ProjectServiceUtils.isProjectDiagram(node)){ - publishRemoveEvent(node); - - } else if(ProjectServiceUtils.isProjectContainer(node)){ - publishRemoveEvent(node); - } - - treeModel.removeNodeFromParent(node); - - LOG.info("Project item has been deleted: " + node); - - return fileSystemPath; - } - - /** - * Recursivlly goes through project items hierarchy and dispatch the remove event. - * - * It removes the automatically removes the project diagram listeners records. - * - * @param node where it is supposed to start - */ - private void publishRemoveEvent(final DefaultMutableTreeNode node) { - if(ProjectServiceUtils.isProjectDiagram(node)){ - final ProjectDiagram projectDiagram = (ProjectDiagram) node.getUserObject(); - - projectDiagram.publishChange(ProjectDiagramChange.ChangeType.REMOVED_FROM_NAVIGATION, null); - listenerMap.remove(projectDiagram); - - } else { - for(int i = 0; i < node.getChildCount(); i++){ - publishRemoveEvent((DefaultMutableTreeNode) node.getChildAt(i)); - } - } - } - - /** {@inheritDoc} */ - public TreePath getSelectedProjectPath() { - if(getSelectedTreePath() == null){ - return null; - } - - DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent(); - TreePath treePath = getSelectedTreePath(); - - while(!(treeNode.getUserObject() instanceof ProjectRoot)){ - treePath = treePath.getParentPath(); - treeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - } - - return treePath; - } - - /** {@inheritDoc} */ - public ProjectRoot getSelectedProject() { - if(getSelectedProjectPath() == null){ - return null; - } - - try{ - final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) getSelectedProjectPath().getLastPathComponent(); - return (ProjectRoot) projectNode.getUserObject(); - } catch (final ClassCastException exception){ - LOG.error("Wrong class casting during looking for selected project."); - } - - return null; - } - - /** {@inheritDoc} */ - public TreePath getSelectedDiagramPath() { - if(getSelectedTreePath() == null){ - return null; - } - - final DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent(); - - if(defaultMutableTreeNode.getUserObject() instanceof ProjectDiagram){ - return getSelectedTreePath(); - } - - return null; - } - - /** {@inheritDoc} */ - public ProjectDiagram getSelectedDiagram() { - if(getSelectedDiagramPath() == null){ - return null; - } - - return (ProjectDiagram) ((DefaultMutableTreeNode) getSelectedDiagramPath().getLastPathComponent()).getUserObject(); - } - - /** {@inheritDoc} */ - public SaveProjectResult saveProject(final TreePath projectTreePath){ - - try { - ProjectFileSaver.saveProject(projectTreePath, true); - - } catch (IllegalArgumentException e){ - LOG.error("Not valid project root tree path."); - return SaveProjectResult.INVALID_TREE_PATH; - - } catch (XMLStreamException e) { - LOG.error("An error during xml streaming has occurred.", e); - return SaveProjectResult.XML_ERROR; - - } catch (FileNotFoundException e) { - LOG.error("No or wrong file to store project root file.", e); - return SaveProjectResult.IOERROR; - - } catch (IOException e) { - LOG.error("IOError during saving project root file.", e); - return SaveProjectResult.IOERROR; - - } catch (TransformerException e) { - LOG.error("Xml transformation (formatting) error.", e); - return SaveProjectResult.XML_ERROR; - } - - return SaveProjectResult.SUCCESS; - } - - /** {@inheritDoc} */ - public LoadProjectResult loadProject(final File projectFile) { - return ProjectFileLoader.loadProjectFile(projectFile); - } - - /** - * For more info about concurrency system used see the implementation of - * synchronize(final File projectFile, final List pathOffset, ...) method. - * - * {@inheritDoc} */ - public boolean synchronize(final TreePath treePath, - final boolean addProjectItems, - final boolean overwriteProjectItems, - final boolean deleteProjectItems, - final boolean cancable) { - - if(!SwingUtilities.isEventDispatchThread()){ - LOG.error("Not possible to run synchronization in a different thread than EventDispatcherThread."); - return false; - } - - if(!(addProjectItems || overwriteProjectItems || deleteProjectItems)){ - LOG.info("Synchronization invoked but with no rights to add, overwrite or delete items from the file system."); - return true; - } - - final boolean retValue; - - final SyncDialog syncDialog = new SyncDialog(SYNC_FROM_PN_TITLE_LABEL); - - final SyncFromPNWorker syncFromPNWorker = new SyncFromPNWorker( - treePath, addProjectItems, overwriteProjectItems, deleteProjectItems, - syncDialog - ); - - if(cancable){ - syncDialog.setSyncWorker(syncFromPNWorker); - } - - syncFromPNWorker.execute(); - - try { - retValue = (Boolean) Worker.post(new Task(){ - public Object run() throws Exception { - - try { - return syncFromPNWorker.get(); - - } catch (InterruptedException e) { - LOG.error("The synchronization from the project navigation has been interrupted.", e); - } catch (ExecutionException e) { - LOG.error("There is no return value available.", e); - } catch (CancellationException e){ - LOG.info("Synchronization has been canceled.", e); - } catch (Exception e){ - LOG.error("Unknown synchronization error.", e); - } - return false; - - } - }); - - } catch (Exception e) { - LOG.error("Synchronous Foxtror thread invocation has failed. ProMod can be in a unstable state now.", e); - return false; - } - - return retValue; - } - - /** {@inheritDoc} */ - public boolean synchronize(final File projectFile, - final List pathOffset, - final boolean addProjectItems, - final boolean overwriteProjectItems, - final boolean deleteProjectItems, - final boolean cancelable) { - - if(!SwingUtilities.isEventDispatchThread()){ - LOG.error("Not possible to run synchronization in a different thread than EventDispatcherThread."); - return false; - } - - if(!(addProjectItems || overwriteProjectItems || deleteProjectItems)){ - LOG.info("Synchronization invoked but with no rights to add, overwrite or delete items from the project navigation."); - return true; - } - - final boolean retValue; - - final SyncDialog syncDialog = new SyncDialog( - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.fromFS.title") - ); - - final SyncFromFSWorker syncFromFSWorker = new SyncFromFSWorker( - projectFile, - pathOffset, - addProjectItems, overwriteProjectItems, deleteProjectItems, - syncDialog); - - // enable possibility to cancel long running synchronization - if(cancelable){ - syncDialog.setSyncWorker(syncFromFSWorker); - } - - /* - Runs the synchronization in SwingWorker thread. This is asynchronous call and EDT continues during the - synchronization takes a place. - This thread in it's doInbackgroud() method schedules the show of SyncDialog using SwingUtilities.invokeLater(). - When this SwingWorker thread finishes, then it schedules it's done() method using SwingUtilities.invokeLater() - too. It is so ensured that the SyncDialog is always disposed (in the done() method) after it has been already - shown. - */ - syncFromFSWorker.execute(); - - - /* - This is kind of hack, how to ensure, that the synchronize method never finishes earlier that the synchronization - is done (synchronization in the SwingWorker thread) (by success, failure or has been canceled). For this is - used SYNCHRONOUS call of Foxtror framework. New task is scheduled and this try block waits for the end of the - synchronization in the SwingWorker (blocking call of SwingWorker#get() ). - */ - try { - retValue = (Boolean) Worker.post(new Task(){ - public Object run() throws Exception { - - try { - return syncFromFSWorker.get(); - - } catch (InterruptedException e) { - LOG.error("The synchronization from the file system has been interrupted.", e); - } catch (ExecutionException e) { - LOG.error("There is no return value available.", e); - } catch (CancellationException e){ - LOG.info("Synchronization has been canceled.", e); - } catch (Exception e){ - LOG.error("Uknown synchronization error.", e); - } - - return false; - } - }); - - } catch (Exception e) { - LOG.error("Synchronous Foxtror thread invocation has failed. ProMod can be in unstable state now.", e); - return false; - } - - return retValue; - } - - /** {@inheritDoc} */ - public void registerDiagramListener(final ProjectDiagram projectDiagram, final ProjectDiagramListener listener) { - if((projectDiagram == null) || (listener == null)){ - LOG.error("Nullary project diagram or listener to be unregistered"); - return; - } - - if(listenerMap.containsKey(projectDiagram)){ - final Set set = listenerMap.get(projectDiagram); - set.add(listener); - - return; - } - - projectDiagram.addChangeListener(this); - - final Set list = new HashSet(); - list.add(listener); - listenerMap.put(projectDiagram, list); - } - - /** - * {@inheritDoc} - * - * Can be used for special event on demand dispatching. - * One has to be very very careful when using this method himself. There are many consequences. - */ - public void changePerformed(final ProjectDiagramChange change) { - if((change == null) || (change.getProjectDiagram() == null) || change.getChangeType() == null){ - return; - } - - final ProjectDiagram sourceDiagram = change.getProjectDiagram(); - - if(listenerMap.containsKey(sourceDiagram)){ - final Set set = listenerMap.get(sourceDiagram); - - for(final ProjectDiagramListener listener : set){ - // forward change - listener.changePerformed(change); - } - - } else { - LOG.debug("No registered listeners for diagram: " + sourceDiagram.getDisplayName()); - } - - switch (change.getChangeType()){ - case REMOVED_FROM_NAVIGATION: - LOG.info("Removing diagram from map of listeners: " + sourceDiagram.getDisplayName()); - listenerMap.remove(sourceDiagram); - break; - } - } - - /** {@inheritDoc} */ - public void unRegisterDiagramListener(final ProjectDiagram projectDiagram, final ProjectDiagramListener listener) { - if((projectDiagram == null) || (listener == null)){ - LOG.error("Nullary info for un-registering listeners."); - return; - } - - if(listenerMap.containsKey(projectDiagram)){ - final Set set = listenerMap.get(projectDiagram); - set.remove(listener); - } - } - - /** {@inheritDoc} */ - public void unRegisterListener(final ProjectDiagramListener listener) { - if(listener == null){ - LOG.error("Nullary info for un-registering listeners."); - return; - } - - for(final ProjectDiagram projectDiagram : listenerMap.keySet()){ - unRegisterDiagramListener(projectDiagram, listener); - } - } - - /** {@inheritDoc} */ - public void switchChangePublisher(final ProjectDiagram oldProjectDiagram, final ProjectDiagram newProjectDiagram) { - if(oldProjectDiagram == null || newProjectDiagram == null){ - return; - } - - if(listenerMap.containsKey(oldProjectDiagram)){ - if(listenerMap.containsKey(newProjectDiagram)){ - LOG.info("New project diagram is already registered as change publisher"); - - } else { - listenerMap.put(newProjectDiagram, listenerMap.get(oldProjectDiagram)); - listenerMap.remove(oldProjectDiagram); - - newProjectDiagram.publishChange(ProjectDiagramChange.ChangeType.PROJECT_DIAGRAM_REPLACED, oldProjectDiagram); - } - - } - } - - /** {@inheritDoc} */ - public void switchChangeListener(ProjectDiagramListener oldProjectDiagramListener, ProjectDiagramListener newProjectDiagramListener) { - if(oldProjectDiagramListener == null || newProjectDiagramListener == null){ - return; - } - - for(final Set listenerSet : listenerMap.values()){ - if(listenerSet.contains(oldProjectDiagramListener)){ - listenerSet.remove(oldProjectDiagramListener); - listenerSet.add(newProjectDiagramListener); - LOG.info("Listener has been changed. Old: " + oldProjectDiagramListener.toString() +", new:" + newProjectDiagramListener.toString() ); - } - } - } -} +package cz.cvut.promod.services.projectService; + +import javax.swing.tree.*; +import javax.swing.*; +import javax.xml.stream.XMLStreamException; +import javax.xml.transform.TransformerException; + +import org.apache.log4j.Logger; + +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.CancellationException; +import java.io.*; + +import cz.cvut.promod.services.projectService.treeProjectNode.*; +import cz.cvut.promod.services.projectService.treeProjectNode.listener.ProjectDiagramListener; +import cz.cvut.promod.services.projectService.localIO.ProjectFileSaver; +import cz.cvut.promod.services.projectService.localIO.ProjectFileLoader; +import cz.cvut.promod.services.projectService.syncWorkers.SyncFromFSWorker; +import cz.cvut.promod.services.projectService.syncWorkers.SyncFromPNWorker; +import cz.cvut.promod.services.projectService.dialogs.SyncDialog; +import cz.cvut.promod.services.projectService.results.AddProjectItemResult; +import cz.cvut.promod.services.projectService.results.LoadProjectResult; +import cz.cvut.promod.services.projectService.results.AddProjectItemStatus; +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.results.SaveProjectResult; +import cz.cvut.promod.services.ModelerSession; +import com.jgoodies.binding.beans.Model; +import com.jgoodies.binding.value.ValueModel; +import com.jgoodies.binding.PresentationModel; +import foxtrot.Task; +import foxtrot.Worker; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:50:24, 10.10.2009 + */ + +/** + * ProjectControlService implementation.. + */ +public class ProjectControlServiceImpl extends Model implements ProjectControlService, ProjectDiagramListener{ + + private final Logger LOG = Logger.getLogger(ProjectControlServiceImpl.class); + + private static final String SYNC_FROM_PN_TITLE_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.fromPN.title"); + + private final DefaultTreeModel treeModel; + private final DefaultMutableTreeNode rootNode; + + public static final String PROPERTY_SELECTED_TREE_PATH = "selectedTreePath"; + private TreePath selectedTreePath; + + private final TreePath rootTreePath; + + private final Map> listenerMap; + + + public ProjectControlServiceImpl(){ + rootNode = new DefaultMutableTreeNode("ProjectsRoot"); + this.treeModel = new DefaultTreeModel(rootNode); + + rootTreePath = new TreePath(rootNode); + + listenerMap = new HashMap>(); + } + + /** {@inheritDoc} */ + public boolean check() { + return true; + } + + /** {@inheritDoc} */ + public String getSelectedProjectNotationIndentifier() { + final ProjectDiagram projectDiagram; + + try{ + if(getSelectedTreePath() != null){ + projectDiagram = (ProjectDiagram) ((DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent()).getUserObject(); + } else { + return null; + } + + } catch (final Exception exception){ + return null; + } + + return projectDiagram.getNotationIdentifier(); + } + + /** {@inheritDoc} */ + public DefaultTreeModel getProjectTreeModel() { + return treeModel; + } + + /** {@inheritDoc} */ + public AddProjectItemResult addProject(final ProjectRoot projectRoot, final boolean select) { + + final String projectName = projectRoot.getDisplayName(); + + if(!ProjectServiceUtils.isSyntacticallyCorrectName(projectName)){ + LOG.error("Invalid project name or project name containing disallowed symbol(s), project name: " + projectName); + return new AddProjectItemResult(AddProjectItemStatus.INVALID_NAME, null); + } + + if(!ProjectServiceUtils.isUniqueProjectContainerDisplayName(rootNode, projectName)){ + LOG.error("An attempt to add project with existing name has occurred."); + return new AddProjectItemResult(AddProjectItemStatus.NAME_DUPLICITY, null); + } + + final DefaultMutableTreeNode projectNode = new DefaultMutableTreeNode(projectRoot); + + treeModel.insertNodeInto(projectNode, rootNode, rootNode.getChildCount()); + + final TreePath treePath = new TreePath(rootNode).pathByAddingChild(projectNode); + + if(select){ + setSelectedItem(treePath); + } + + return + new AddProjectItemResult(AddProjectItemStatus.SUCCESS, treePath); + } + + /** {@inheritDoc} */ + public void setSelectedItem(TreePath treePath) { + if(treePath == null){ + LOG.error("Nullary path to select"); + return; + } + if(treePath.equals(rootTreePath)){ + LOG.debug("An attempt to select project tree root node has occurred. Selected items will be set to null."); + treePath = null; + } + if(getSelectedTreePath() == null){ + if(getSelectedTreePath() != treePath){ + this.selectedTreePath = treePath; + firePropertyChange(PROPERTY_SELECTED_TREE_PATH, null, getSelectedTreePath()); + } + } + else if( !getSelectedTreePath().equals(treePath)){ + final TreePath oldSelectedTreePath = this.getSelectedTreePath(); + this.selectedTreePath = treePath; + firePropertyChange(PROPERTY_SELECTED_TREE_PATH, oldSelectedTreePath, getSelectedTreePath()); + } + } + + /** {@inheritDoc} */ + public List getProjects(){ + final List projects = new LinkedList(); + + for(final TreePath treePath : getProjectPaths()){ + final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + + try{ + final ProjectRoot projectRoot = (ProjectRoot) projectNode.getUserObject(); + + projects.add(projectRoot); + + } catch (ClassCastException exception){ + LOG.fatal("Root node of project is not ProjectRoot."); + } + + } + + return projects; + } + + /** {@inheritDoc} */ + public List getProjectPaths() { + final List projectItems = new LinkedList(); + + for(int i = 0; i < rootNode.getChildCount(); i++){ + final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) rootNode.getChildAt(i); + + final TreePath treePath = new TreePath(rootNode); + projectItems.add(treePath.pathByAddingChild(projectNode)); + } + + return projectItems; + } + + /** {@inheritDoc} */ + public ProjectRoot getProject(String projectName) { + final TreePath treePath = getProjectPath(projectName); + + if(treePath != null){ + final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + + try{ + return (ProjectRoot) projectNode.getUserObject(); + + } catch (ClassCastException exception){ + LOG.fatal("Root node of project is not ProjectRoot."); + } + } + + return null; + } + + /** {@inheritDoc} */ + public DefaultMutableTreeNode getProjectTreeNode(final String projectName) { + final TreePath projectTreePath = getProjectPath(projectName); + + if(projectTreePath == null){ + return null; + } + + try{ + return (DefaultMutableTreeNode) projectTreePath.getLastPathComponent(); + } catch (ClassCastException exception){ + LOG.error("(Impossible to cast tree node to an instance of DefaultMutableTreeNode."); + return null; + } + } + + /** {@inheritDoc} */ + public TreePath getProjectPath(final String projectName) { + for(final TreePath treePath : getProjectPaths()){ + final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + + try{ + final ProjectRoot projectRoot = (ProjectRoot) projectNode.getUserObject(); + + if(projectRoot.getDisplayName().equals(projectName)){ + return treePath; + } + + } catch (ClassCastException exception){ + LOG.fatal("Root node of project is not ProjectRoot."); + } + } + + return null; + } + + /** {@inheritDoc} */ + public boolean isOpenedProject(String projectName) { + return getProjectPath(projectName) != null; + } + + /** {@inheritDoc} */ + public TreePath getSelectedTreePath() { + return selectedTreePath; + } + + /** {@inheritDoc} */ + public ValueModel getSelectedItem() { + final PresentationModel presentationModel = new PresentationModel(this); + + return presentationModel.getModel(PROPERTY_SELECTED_TREE_PATH); + } + + /** {@inheritDoc} */ + public AddProjectItemResult addSubFolder(final String subFolderName, final boolean select) { + if(getSelectedTreePath() != null){ + DefaultMutableTreeNode parent = (DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent(); + TreePath parentTreePath = getSelectedTreePath(); + + while(!ProjectServiceUtils.isProjectContainer(parent)){ + parentTreePath = parentTreePath.getParentPath(); + parent = (DefaultMutableTreeNode) parentTreePath.getLastPathComponent(); + + if(parent == rootNode){ + //any strange behavior occurred, should never happened, testing & debugging + LOG.error("No project container to place new subfolder"); + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + } + + return addSubFolder(subFolderName, parentTreePath, select); + + } + + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + + /** {@inheritDoc} */ + public AddProjectItemResult addSubFolder(final String subFolderName, + final TreePath parentTreePath, + final boolean select) { + + if(!ProjectServiceUtils.isSyntacticallyCorrectName(subFolderName)){ + LOG.error("Invalid subfolder name or name containing disallowed symbol(s), project name: " + subFolderName); + return new AddProjectItemResult(AddProjectItemStatus.INVALID_NAME, null); + } + + if(parentTreePath == null){ + LOG.error("Nullary parent tree path when adding new subfolder."); + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + + if(!ProjectServiceUtils.isValidTreePath(parentTreePath)){ + LOG.error("Parent tre e path is not valid."); + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + + if(!ProjectServiceUtils.isProjectContainer((DefaultMutableTreeNode) parentTreePath.getLastPathComponent())){ + LOG.error("Parent node is not a project container."); + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + + final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) parentTreePath.getLastPathComponent(); + + if(!ProjectServiceUtils.isUniqueProjectContainerDisplayName(parent, subFolderName)){ + LOG.error("An attempt to add subfolder to a level, where an item with the same display name has been already inserted."); + return new AddProjectItemResult(AddProjectItemStatus.NAME_DUPLICITY, null); + } + + final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(); + final ProjectSubFolder projectSubFolder = new ProjectSubFolder(subFolderName); + newNode.setUserObject(projectSubFolder); + + treeModel.insertNodeInto(newNode, parent, parent.getChildCount()); + + final TreePath treePath = parentTreePath.pathByAddingChild(newNode); + + if(select){ + //select and expand to the newly added node in project tree + setSelectedItem(treePath); + } + + LOG.info("New subfolder '" + projectSubFolder.getDisplayName() + "' has been added."); + + return new AddProjectItemResult(AddProjectItemStatus.SUCCESS, treePath); + } + + /** {@inheritDoc} */ + public AddProjectItemResult addDiagram(final ProjectDiagram projectDiagram, + final boolean select) { + + if(getSelectedTreePath() != null){ + DefaultMutableTreeNode parent = (DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent(); + TreePath parentTreePath = getSelectedTreePath(); + + while(!ProjectServiceUtils.isProjectContainer(parent)){ + parentTreePath = parentTreePath.getParentPath(); + parent = (DefaultMutableTreeNode) parentTreePath.getLastPathComponent(); + } + + return addDiagram(projectDiagram, parentTreePath, select); + } + + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + + /** {@inheritDoc} */ + public AddProjectItemResult addDiagram(final ProjectDiagram projectDiagram, + final TreePath parentTreePath, + final boolean select) { + + if(projectDiagram == null){ + return new AddProjectItemResult(AddProjectItemStatus.INVALID_ITEM_DATA, null); + } + + final String displayName = projectDiagram.getDisplayName(); + if(!ProjectServiceUtils.isSyntacticallyCorrectName(projectDiagram.getDisplayName())){ + LOG.error("Diagram name contains disallowed symbol(s), project name: " + projectDiagram.getDisplayName()); + return new AddProjectItemResult(AddProjectItemStatus.INVALID_NAME, null); + } + + final String notationIdentifier = projectDiagram.getNotationIdentifier(); + if(notationIdentifier == null || !ModelerSession.getNotationService().existNotation(notationIdentifier)){ + LOG.error("An attempt to create a new diagram with no existing notation identifier has occurred."); + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_NOTATION, null); + } + + if(parentTreePath == null){ + LOG.error("Nullary parent when adding new diagram"); + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + + if(!ProjectServiceUtils.isValidTreePath(parentTreePath)){ + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + + final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)parentTreePath.getLastPathComponent(); + + if(!ProjectServiceUtils.isProjectContainer(parent)){ + LOG.error("Last tree path component is not a project container"); + return new AddProjectItemResult(AddProjectItemStatus.ILLEGAL_PARENT, null); + } + + final ProjectItem parentProjectItem = (ProjectItem) parent.getUserObject(); + + + if(!ProjectServiceUtils.isUniqueProjectDiagramName(parent, projectDiagram)){ + LOG.error("An attempt to add new diagram to a level, where an item with the same display name and notation has been already inserted."); + return new AddProjectItemResult(AddProjectItemStatus.NAME_DUPLICITY, null); + } + + final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(); + + newNode.setUserObject(projectDiagram); + + treeModel.insertNodeInto(newNode, parent, parent.getChildCount()); + + final TreePath treePath = parentTreePath.pathByAddingChild(newNode); + + //select and expand to the newly added node in project tree + if(select){ + setSelectedItem(treePath); + } + + LOG.info("New diagram has been added, " + parentProjectItem.getDisplayName() + " -> " + displayName + ", notation: "+ notationIdentifier + "."); + + return new AddProjectItemResult(AddProjectItemStatus.SUCCESS, treePath); + } + + /** {@inheritDoc} */ + public String removeProjectItem(final TreePath treePath) { + final String fileSystemPath = ProjectServiceUtils.getFileSystemPathToProjectItem(treePath); + + if(fileSystemPath == null){ + LOG.error("File system path to the project item couldn't be calculated."); + return null; + } + + final DefaultMutableTreeNode node; + try{ + node = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + } catch (ClassCastException exception){ + LOG.error("All components in the project tree have to be an instance of the DefaultMutableTreeNode class."); + return null; + } + + // if the item or it's any child is currently selected, then select item's parent item + if(ProjectServiceUtils.isTreePathExtension(treePath, getSelectedTreePath())){ + LOG.debug("Selecting parent of the project tree item, that will be deleted."); + + setSelectedItem(treePath.getParentPath()); + } + + // publish change + if(ProjectServiceUtils.isProjectDiagram(node)){ + publishRemoveEvent(node); + + } else if(ProjectServiceUtils.isProjectContainer(node)){ + publishRemoveEvent(node); + } + + treeModel.removeNodeFromParent(node); + + LOG.info("Project item has been deleted: " + node); + + return fileSystemPath; + } + + /** + * Recursivlly goes through project items hierarchy and dispatch the remove event. + * + * It removes the automatically removes the project diagram listeners records. + * + * @param node where it is supposed to start + */ + private void publishRemoveEvent(final DefaultMutableTreeNode node) { + if(ProjectServiceUtils.isProjectDiagram(node)){ + final ProjectDiagram projectDiagram = (ProjectDiagram) node.getUserObject(); + + projectDiagram.publishChange(ProjectDiagramChange.ChangeType.REMOVED_FROM_NAVIGATION, null); + listenerMap.remove(projectDiagram); + + } else { + for(int i = 0; i < node.getChildCount(); i++){ + publishRemoveEvent((DefaultMutableTreeNode) node.getChildAt(i)); + } + } + } + + /** {@inheritDoc} */ + public TreePath getSelectedProjectPath() { + if(getSelectedTreePath() == null){ + return null; + } + + DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent(); + TreePath treePath = getSelectedTreePath(); + + while(!(treeNode.getUserObject() instanceof ProjectRoot)){ + treePath = treePath.getParentPath(); + treeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + } + + return treePath; + } + + /** {@inheritDoc} */ + public ProjectRoot getSelectedProject() { + if(getSelectedProjectPath() == null){ + return null; + } + + try{ + final DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) getSelectedProjectPath().getLastPathComponent(); + return (ProjectRoot) projectNode.getUserObject(); + } catch (final ClassCastException exception){ + LOG.error("Wrong class casting during looking for selected project."); + } + + return null; + } + + /** {@inheritDoc} */ + public TreePath getSelectedDiagramPath() { + if(getSelectedTreePath() == null){ + return null; + } + + final DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) getSelectedTreePath().getLastPathComponent(); + + if(defaultMutableTreeNode.getUserObject() instanceof ProjectDiagram){ + return getSelectedTreePath(); + } + + return null; + } + + /** {@inheritDoc} */ + public ProjectDiagram getSelectedDiagram() { + if(getSelectedDiagramPath() == null){ + return null; + } + + return (ProjectDiagram) ((DefaultMutableTreeNode) getSelectedDiagramPath().getLastPathComponent()).getUserObject(); + } + + /** {@inheritDoc} */ + public SaveProjectResult saveProject(final TreePath projectTreePath){ + + try { + ProjectFileSaver.saveProject(projectTreePath, true); + + } catch (IllegalArgumentException e){ + LOG.error("Not valid project root tree path."); + return SaveProjectResult.INVALID_TREE_PATH; + + } catch (XMLStreamException e) { + LOG.error("An error during xml streaming has occurred.", e); + return SaveProjectResult.XML_ERROR; + + } catch (FileNotFoundException e) { + LOG.error("No or wrong file to store project root file.", e); + return SaveProjectResult.IOERROR; + + } catch (IOException e) { + LOG.error("IOError during saving project root file.", e); + return SaveProjectResult.IOERROR; + + } catch (TransformerException e) { + LOG.error("Xml transformation (formatting) error.", e); + return SaveProjectResult.XML_ERROR; + } + + return SaveProjectResult.SUCCESS; + } + + /** {@inheritDoc} */ + public LoadProjectResult loadProject(final File projectFile) { + return ProjectFileLoader.loadProjectFile(projectFile); + } + + /** + * For more info about concurrency system used see the implementation of + * synchronize(final File projectFile, final List pathOffset, ...) method. + * + * {@inheritDoc} */ + public boolean synchronize(final TreePath treePath, + final boolean addProjectItems, + final boolean overwriteProjectItems, + final boolean deleteProjectItems, + final boolean cancable) { + + if(!SwingUtilities.isEventDispatchThread()){ + LOG.error("Not possible to run synchronization in a different thread than EventDispatcherThread."); + return false; + } + + if(!(addProjectItems || overwriteProjectItems || deleteProjectItems)){ + LOG.info("Synchronization invoked but with no rights to add, overwrite or delete items from the file system."); + return true; + } + + final boolean retValue; + + final SyncDialog syncDialog = new SyncDialog(SYNC_FROM_PN_TITLE_LABEL); + + final SyncFromPNWorker syncFromPNWorker = new SyncFromPNWorker( + treePath, addProjectItems, overwriteProjectItems, deleteProjectItems, + syncDialog + ); + + if(cancable){ + syncDialog.setSyncWorker(syncFromPNWorker); + } + + syncFromPNWorker.execute(); + + try { + retValue = (Boolean) Worker.post(new Task(){ + public Object run() throws Exception { + + try { + return syncFromPNWorker.get(); + + } catch (InterruptedException e) { + LOG.error("The synchronization from the project navigation has been interrupted.", e); + } catch (ExecutionException e) { + LOG.error("There is no return value available.", e); + } catch (CancellationException e){ + LOG.info("Synchronization has been canceled.", e); + } catch (Exception e){ + LOG.error("Unknown synchronization error.", e); + } + return false; + + } + }); + + } catch (Exception e) { + LOG.error("Synchronous Foxtror thread invocation has failed. ProMod can be in a unstable state now.", e); + return false; + } + + return retValue; + } + + /** {@inheritDoc} */ + public boolean synchronize(final File projectFile, + final List pathOffset, + final boolean addProjectItems, + final boolean overwriteProjectItems, + final boolean deleteProjectItems, + final boolean cancelable) { + + if(!SwingUtilities.isEventDispatchThread()){ + LOG.error("Not possible to run synchronization in a different thread than EventDispatcherThread."); + return false; + } + + if(!(addProjectItems || overwriteProjectItems || deleteProjectItems)){ + LOG.info("Synchronization invoked but with no rights to add, overwrite or delete items from the project navigation."); + return true; + } + + final boolean retValue; + + final SyncDialog syncDialog = new SyncDialog( + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.fromFS.title") + ); + + final SyncFromFSWorker syncFromFSWorker = new SyncFromFSWorker( + projectFile, + pathOffset, + addProjectItems, overwriteProjectItems, deleteProjectItems, + syncDialog); + + // enable possibility to cancel long running synchronization + if(cancelable){ + syncDialog.setSyncWorker(syncFromFSWorker); + } + + /* + Runs the synchronization in SwingWorker thread. This is asynchronous call and EDT continues during the + synchronization takes a place. + This thread in it's doInbackgroud() method schedules the show of SyncDialog using SwingUtilities.invokeLater(). + When this SwingWorker thread finishes, then it schedules it's done() method using SwingUtilities.invokeLater() + too. It is so ensured that the SyncDialog is always disposed (in the done() method) after it has been already + shown. + */ + syncFromFSWorker.execute(); + + + /* + This is kind of hack, how to ensure, that the synchronize method never finishes earlier that the synchronization + is done (synchronization in the SwingWorker thread) (by success, failure or has been canceled). For this is + used SYNCHRONOUS call of Foxtror framework. New task is scheduled and this try block waits for the end of the + synchronization in the SwingWorker (blocking call of SwingWorker#get() ). + */ + try { + retValue = (Boolean) Worker.post(new Task(){ + public Object run() throws Exception { + + try { + return syncFromFSWorker.get(); + + } catch (InterruptedException e) { + LOG.error("The synchronization from the file system has been interrupted.", e); + } catch (ExecutionException e) { + LOG.error("There is no return value available.", e); + } catch (CancellationException e){ + LOG.info("Synchronization has been canceled.", e); + } catch (Exception e){ + LOG.error("Uknown synchronization error.", e); + } + + return false; + } + }); + + } catch (Exception e) { + LOG.error("Synchronous Foxtror thread invocation has failed. ProMod can be in unstable state now.", e); + return false; + } + + return retValue; + } + + /** {@inheritDoc} */ + public void registerDiagramListener(final ProjectDiagram projectDiagram, final ProjectDiagramListener listener) { + if((projectDiagram == null) || (listener == null)){ + LOG.error("Nullary project diagram or listener to be unregistered"); + return; + } + + if(listenerMap.containsKey(projectDiagram)){ + final Set set = listenerMap.get(projectDiagram); + set.add(listener); + + return; + } + + projectDiagram.addChangeListener(this); + + final Set list = new HashSet(); + list.add(listener); + listenerMap.put(projectDiagram, list); + } + + /** + * {@inheritDoc} + * + * Can be used for special event on demand dispatching. + * One has to be very very careful when using this method himself. There are many consequences. + */ + public void changePerformed(final ProjectDiagramChange change) { + if((change == null) || (change.getProjectDiagram() == null) || change.getChangeType() == null){ + return; + } + + final ProjectDiagram sourceDiagram = change.getProjectDiagram(); + + if(listenerMap.containsKey(sourceDiagram)){ + final Set set = listenerMap.get(sourceDiagram); + + for(final ProjectDiagramListener listener : set){ + // forward change + listener.changePerformed(change); + } + + } else { + LOG.debug("No registered listeners for diagram: " + sourceDiagram.getDisplayName()); + } + + switch (change.getChangeType()){ + case REMOVED_FROM_NAVIGATION: + LOG.info("Removing diagram from map of listeners: " + sourceDiagram.getDisplayName()); + listenerMap.remove(sourceDiagram); + break; + } + } + + /** {@inheritDoc} */ + public void unRegisterDiagramListener(final ProjectDiagram projectDiagram, final ProjectDiagramListener listener) { + if((projectDiagram == null) || (listener == null)){ + LOG.error("Nullary info for un-registering listeners."); + return; + } + + if(listenerMap.containsKey(projectDiagram)){ + final Set set = listenerMap.get(projectDiagram); + set.remove(listener); + } + } + + /** {@inheritDoc} */ + public void unRegisterListener(final ProjectDiagramListener listener) { + if(listener == null){ + LOG.error("Nullary info for un-registering listeners."); + return; + } + + for(final ProjectDiagram projectDiagram : listenerMap.keySet()){ + unRegisterDiagramListener(projectDiagram, listener); + } + } + + /** {@inheritDoc} */ + public void switchChangePublisher(final ProjectDiagram oldProjectDiagram, final ProjectDiagram newProjectDiagram) { + if(oldProjectDiagram == null || newProjectDiagram == null){ + return; + } + + if(listenerMap.containsKey(oldProjectDiagram)){ + if(listenerMap.containsKey(newProjectDiagram)){ + LOG.info("New project diagram is already registered as change publisher"); + + } else { + listenerMap.put(newProjectDiagram, listenerMap.get(oldProjectDiagram)); + listenerMap.remove(oldProjectDiagram); + + newProjectDiagram.publishChange(ProjectDiagramChange.ChangeType.PROJECT_DIAGRAM_REPLACED, oldProjectDiagram); + } + + } + } + + /** {@inheritDoc} */ + public void switchChangeListener(ProjectDiagramListener oldProjectDiagramListener, ProjectDiagramListener newProjectDiagramListener) { + if(oldProjectDiagramListener == null || newProjectDiagramListener == null){ + return; + } + + for(final Set listenerSet : listenerMap.values()){ + if(listenerSet.contains(oldProjectDiagramListener)){ + listenerSet.remove(oldProjectDiagramListener); + listenerSet.add(newProjectDiagramListener); + LOG.info("Listener has been changed. Old: " + oldProjectDiagramListener.toString() +", new:" + newProjectDiagramListener.toString() ); + } + } + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectService.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectService.java index 0db84a4..ce2e56a 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/ProjectService.java @@ -1,187 +1,187 @@ -package cz.cvut.promod.services.projectService; - -import cz.cvut.promod.services.Service; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; -import cz.cvut.promod.services.projectService.treeProjectNode.listener.ProjectDiagramListener; - -import javax.swing.tree.TreePath; -import javax.swing.tree.DefaultMutableTreeNode; -import java.util.List; - -import com.jgoodies.binding.value.ValueModel; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:46:55, 10.10.2009 - */ - -/** - * ProjectService is responsible for operating the project(s) data. - * - * This service provides the developer with an access to particular project data and allows developer - * to operate with this project data. - */ -public interface ProjectService extends Service{ - - /** - * ProMod project file extension. - */ - public static final String PROJECT_FILE_EXTENSION_NAME = "pmp"; - - /** - * File extension delimiter. - */ - public static final String FILE_EXTENSION_DELIMITER = "."; - - /** - * ProMod project file extension with delimiter. - */ - public static final String PROJECT_FILE_EXTENSION = FILE_EXTENSION_DELIMITER + PROJECT_FILE_EXTENSION_NAME; - - /** - * Returns null if no diagram is selected in projects navigation tree, or corresponding notation identifier to the - * selected diagram. There is no equivalent set method. Use ProjectControlService interface instead. - * - * @return notation identifier if and only if there is any diagram selected in the project navigation tree, null otherwise - */ - public String getSelectedProjectNotationIndentifier(); - - /** - * Returns a list of tree paths of all projects opened in project navigation tree. - * - * @return the list of tree paths of of all projects opened in project navigation tree, - */ - public List getProjectPaths(); - - /** - * Returns a list of tree roots (instances of ProjectRoot class) of all projects opened in project navigation tree. - * - * @return the list of tree roots (instances of ProjectRoot class) of all projects opened in - * project navigation tree - */ - public List getProjects(); - - /** - * Returns a project root (instance of ProjectRoot class) opened in the project navigation tree that is specified - * as it's name. - * - * @param projectName is the name of required project (project root) - * - * @return project root if such a project with given name is opened in project navigation tree, null if there is no - * such a project root - */ - public ProjectRoot getProject(final String projectName); - - /** - * Returns a tree node holding a project root (instance of DefaultMutableTreeNode class) opened in the - * project navigation tree that is specified as it's name. - * - * @param projectName is the name of required project (project root) - * - * @return an instance of DefaultMutableTreeNode class holding the project root with the given name, null if there - * is no such a project (and thereby node) - */ - public DefaultMutableTreeNode getProjectTreeNode(final String projectName); - - /** - * Returns a tree path to the project that is specified by the given project name. - * - * @param projectName is the name of required project - * - * @return tree path to the project that is specified by the given project name, null if there is no such - * a project - */ - public TreePath getProjectPath(final String projectName); - - /** - * Checks whether there is such a project with given name opened in project navigation tree. - * - * @param projectName is the project name - * - * @return true if there is such a project with given name opened in project navigation tree, false otherwise - */ - public boolean isOpenedProject(final String projectName); - - /** - * Returns the tree path of the node that is currently selected in the project navigation tree. - * - * @return the tree path of the node that is currently selected in the project navigation tree - */ - public TreePath getSelectedTreePath(); - - /** - * Returns an observable object that holds the currently selected item in the project navigation tree. - * This implements kind of Observer pattern. - * - * @see com.jgoodies.binding.value.ValueModel for more info about value model and how to listen changes - * in project navigation tree - * - * @return an implementation of value model representing currently selected item in project navigation tree - */ - public ValueModel getSelectedItem(); - - /** - * Returns the tree path of the currently selected project. This works event if any child of project node is just - * selected. - * - * @return tree path to the node in project navigation tree that represents path to the project that is - * currently selected or is selected any of this project's child - */ - public TreePath getSelectedProjectPath(); - - /** - * Returns the project root of the currently selected project. This works event if any child of project node is just - * selected. - * - * @return project root that represents the project that is currently selected or is selected - * any of this project's child - */ - public ProjectRoot getSelectedProject(); - - /** - * Returns tree path to the currently selected diagram in the project navigation tree. - * - * @return tree path to the currently selected diagram in the project navigation tree, null if there is no - * diagram selected in the project navigation tree - */ - public TreePath getSelectedDiagramPath(); - - /** - * Returns project diagram of the currently selected diagram in the project navigation tree. - * - * @return project diagram of the currently selected diagram in the project navigation tree, null if there is no - * diagram selected in the project navigation tree - */ - public ProjectDiagram getSelectedDiagram(); - - /** - * Registers given listener for the given project diagram. - * - * Method does NOT check whether the given project diagram is valid project diagram in the project navigation tree. - * One is supposed to verify this (e.g. using ProjectServiceUtils) or it can be used for special purposes. - * - * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils - * - * @param projectDiagram is the project diagram dispatching changes - * @param listener is the listener for event consuming - */ - public void registerDiagramListener(final ProjectDiagram projectDiagram, final ProjectDiagramListener listener); - - /** - * Un-registers given listener from the given project diagram. - * - * @param projectDiagram is the project diagram dispatching changes - * @param listener is the listener for event consuming - */ - public void unRegisterDiagramListener(final ProjectDiagram projectDiagram, final ProjectDiagramListener listener); - - /** - * Un-registers given listener from all project diagram. - * - * @param listener is the listener to be unregistered - */ - public void unRegisterListener(final ProjectDiagramListener listener); - -} +package cz.cvut.promod.services.projectService; + +import cz.cvut.promod.services.Service; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; +import cz.cvut.promod.services.projectService.treeProjectNode.listener.ProjectDiagramListener; + +import javax.swing.tree.TreePath; +import javax.swing.tree.DefaultMutableTreeNode; +import java.util.List; + +import com.jgoodies.binding.value.ValueModel; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:46:55, 10.10.2009 + */ + +/** + * ProjectService is responsible for operating the project(s) data. + * + * This service provides the developer with an access to particular project data and allows developer + * to operate with this project data. + */ +public interface ProjectService extends Service{ + + /** + * ProMod project file extension. + */ + public static final String PROJECT_FILE_EXTENSION_NAME = "pmp"; + + /** + * File extension delimiter. + */ + public static final String FILE_EXTENSION_DELIMITER = "."; + + /** + * ProMod project file extension with delimiter. + */ + public static final String PROJECT_FILE_EXTENSION = FILE_EXTENSION_DELIMITER + PROJECT_FILE_EXTENSION_NAME; + + /** + * Returns null if no diagram is selected in projects navigation tree, or corresponding notation identifier to the + * selected diagram. There is no equivalent set method. Use ProjectControlService interface instead. + * + * @return notation identifier if and only if there is any diagram selected in the project navigation tree, null otherwise + */ + public String getSelectedProjectNotationIndentifier(); + + /** + * Returns a list of tree paths of all projects opened in project navigation tree. + * + * @return the list of tree paths of of all projects opened in project navigation tree, + */ + public List getProjectPaths(); + + /** + * Returns a list of tree roots (instances of ProjectRoot class) of all projects opened in project navigation tree. + * + * @return the list of tree roots (instances of ProjectRoot class) of all projects opened in + * project navigation tree + */ + public List getProjects(); + + /** + * Returns a project root (instance of ProjectRoot class) opened in the project navigation tree that is specified + * as it's name. + * + * @param projectName is the name of required project (project root) + * + * @return project root if such a project with given name is opened in project navigation tree, null if there is no + * such a project root + */ + public ProjectRoot getProject(final String projectName); + + /** + * Returns a tree node holding a project root (instance of DefaultMutableTreeNode class) opened in the + * project navigation tree that is specified as it's name. + * + * @param projectName is the name of required project (project root) + * + * @return an instance of DefaultMutableTreeNode class holding the project root with the given name, null if there + * is no such a project (and thereby node) + */ + public DefaultMutableTreeNode getProjectTreeNode(final String projectName); + + /** + * Returns a tree path to the project that is specified by the given project name. + * + * @param projectName is the name of required project + * + * @return tree path to the project that is specified by the given project name, null if there is no such + * a project + */ + public TreePath getProjectPath(final String projectName); + + /** + * Checks whether there is such a project with given name opened in project navigation tree. + * + * @param projectName is the project name + * + * @return true if there is such a project with given name opened in project navigation tree, false otherwise + */ + public boolean isOpenedProject(final String projectName); + + /** + * Returns the tree path of the node that is currently selected in the project navigation tree. + * + * @return the tree path of the node that is currently selected in the project navigation tree + */ + public TreePath getSelectedTreePath(); + + /** + * Returns an observable object that holds the currently selected item in the project navigation tree. + * This implements kind of Observer pattern. + * + * @see com.jgoodies.binding.value.ValueModel for more info about value model and how to listen changes + * in project navigation tree + * + * @return an implementation of value model representing currently selected item in project navigation tree + */ + public ValueModel getSelectedItem(); + + /** + * Returns the tree path of the currently selected project. This works event if any child of project node is just + * selected. + * + * @return tree path to the node in project navigation tree that represents path to the project that is + * currently selected or is selected any of this project's child + */ + public TreePath getSelectedProjectPath(); + + /** + * Returns the project root of the currently selected project. This works event if any child of project node is just + * selected. + * + * @return project root that represents the project that is currently selected or is selected + * any of this project's child + */ + public ProjectRoot getSelectedProject(); + + /** + * Returns tree path to the currently selected diagram in the project navigation tree. + * + * @return tree path to the currently selected diagram in the project navigation tree, null if there is no + * diagram selected in the project navigation tree + */ + public TreePath getSelectedDiagramPath(); + + /** + * Returns project diagram of the currently selected diagram in the project navigation tree. + * + * @return project diagram of the currently selected diagram in the project navigation tree, null if there is no + * diagram selected in the project navigation tree + */ + public ProjectDiagram getSelectedDiagram(); + + /** + * Registers given listener for the given project diagram. + * + * Method does NOT check whether the given project diagram is valid project diagram in the project navigation tree. + * One is supposed to verify this (e.g. using ProjectServiceUtils) or it can be used for special purposes. + * + * @see cz.cvut.promod.services.projectService.utils.ProjectServiceUtils + * + * @param projectDiagram is the project diagram dispatching changes + * @param listener is the listener for event consuming + */ + public void registerDiagramListener(final ProjectDiagram projectDiagram, final ProjectDiagramListener listener); + + /** + * Un-registers given listener from the given project diagram. + * + * @param projectDiagram is the project diagram dispatching changes + * @param listener is the listener for event consuming + */ + public void unRegisterDiagramListener(final ProjectDiagram projectDiagram, final ProjectDiagramListener listener); + + /** + * Un-registers given listener from all project diagram. + * + * @param listener is the listener to be unregistered + */ + public void unRegisterListener(final ProjectDiagramListener listener); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/dialogs/SyncDialog.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/dialogs/SyncDialog.java index 7cc0c78..283b961 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/dialogs/SyncDialog.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/dialogs/SyncDialog.java @@ -1,148 +1,148 @@ -package cz.cvut.promod.services.projectService.dialogs; - -import javax.swing.*; -import java.awt.event.*; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:05:47, 13.11.2009 - */ - -/** - * SyncDialog controller. - */ -public class SyncDialog extends SyncDialogView{ - - public static final String NEW_LINE_MARK = "\n"; - - private SwingWorker swingWorker = null; - - /** - * Creates a new SyncDialog. - * - * @param title is the SyncDialog title. - */ - public SyncDialog(final String title){ - super(title); - - initEventHandling(); - - okButton.setEnabled(false); - cancelButton.setEnabled(false); - - getRootPane().setDefaultButton(okButton); - - setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - - setModal(true); - } - - /** - * Initialize event handling. - */ - private void initEventHandling() { - okButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - disposeDialog(); - } - }); - - cancelButton.addActionListener(new ActionListener(){ - public void actionPerformed(ActionEvent e) { - swingWorker.cancel(true); - } - }); - - getRootPane().registerKeyboardAction(new ActionListener(){ - public void actionPerformed(ActionEvent actionEvent) { - escape(); - } - }, - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - - addWindowListener(new WindowAdapter(){ - @Override - public void windowClosing(WindowEvent windowEvent) { - escape(); - } - }); - } - - /** - * When the EXC or cross buton is pressed. - */ - private void escape() { - if(okButton.isEnabled()){ - disposeDialog(); - } - } - - /** - * Controls dialogs final appearance. - * - * @param errors if true the dialog remains visible, false -> the dialog will be disposed - */ - public void syncComplete(final boolean errors){ - if(errors){ - okButton.setEnabled(true); - } else { - disposeDialog(); - } - } - - /** - * Sets the cancel button enabled. - */ - public void disableCancelButton(){ - cancelButton.setEnabled(false); - } - - /** - * Disposes the dialog. - */ - public void disposeDialog(){ - setVisible(false); - dispose(); - } - - /** - * Appends a new error message to the synchronization error dialog. - * - * @param message is the error message - * - * @param addEmptyLine if true then there will be added an empty line after this error message - */ - public void appendErrorInfo(final String message, final boolean addEmptyLine){ - errorsTextArea.append(message); - - errorsTextArea.append(NEW_LINE_MARK); - - if(addEmptyLine){ - errorsTextArea.append(NEW_LINE_MARK); - } - } - - /** - * Update current sync position. - * @param text the location - */ - public void updatePosition(final String text){ - currentSearchLocationLabel.setText(text); - } - - /** - * Sets the sync worker. - * @param swingWorker the sync worker. - */ - public void setSyncWorker(final SwingWorker swingWorker) { - if(swingWorker == null){ - return; - } - - this.swingWorker = swingWorker; - - cancelButton.setEnabled(true); - } +package cz.cvut.promod.services.projectService.dialogs; + +import javax.swing.*; +import java.awt.event.*; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:05:47, 13.11.2009 + */ + +/** + * SyncDialog controller. + */ +public class SyncDialog extends SyncDialogView{ + + public static final String NEW_LINE_MARK = "\n"; + + private SwingWorker swingWorker = null; + + /** + * Creates a new SyncDialog. + * + * @param title is the SyncDialog title. + */ + public SyncDialog(final String title){ + super(title); + + initEventHandling(); + + okButton.setEnabled(false); + cancelButton.setEnabled(false); + + getRootPane().setDefaultButton(okButton); + + setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); + + setModal(true); + } + + /** + * Initialize event handling. + */ + private void initEventHandling() { + okButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + disposeDialog(); + } + }); + + cancelButton.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent e) { + swingWorker.cancel(true); + } + }); + + getRootPane().registerKeyboardAction(new ActionListener(){ + public void actionPerformed(ActionEvent actionEvent) { + escape(); + } + }, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + + addWindowListener(new WindowAdapter(){ + @Override + public void windowClosing(WindowEvent windowEvent) { + escape(); + } + }); + } + + /** + * When the EXC or cross buton is pressed. + */ + private void escape() { + if(okButton.isEnabled()){ + disposeDialog(); + } + } + + /** + * Controls dialogs final appearance. + * + * @param errors if true the dialog remains visible, false -> the dialog will be disposed + */ + public void syncComplete(final boolean errors){ + if(errors){ + okButton.setEnabled(true); + } else { + disposeDialog(); + } + } + + /** + * Sets the cancel button enabled. + */ + public void disableCancelButton(){ + cancelButton.setEnabled(false); + } + + /** + * Disposes the dialog. + */ + public void disposeDialog(){ + setVisible(false); + dispose(); + } + + /** + * Appends a new error message to the synchronization error dialog. + * + * @param message is the error message + * + * @param addEmptyLine if true then there will be added an empty line after this error message + */ + public void appendErrorInfo(final String message, final boolean addEmptyLine){ + errorsTextArea.append(message); + + errorsTextArea.append(NEW_LINE_MARK); + + if(addEmptyLine){ + errorsTextArea.append(NEW_LINE_MARK); + } + } + + /** + * Update current sync position. + * @param text the location + */ + public void updatePosition(final String text){ + currentSearchLocationLabel.setText(text); + } + + /** + * Sets the sync worker. + * @param swingWorker the sync worker. + */ + public void setSyncWorker(final SwingWorker swingWorker) { + if(swingWorker == null){ + return; + } + + this.swingWorker = swingWorker; + + cancelButton.setEnabled(true); + } } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/dialogs/SyncDialogView.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/dialogs/SyncDialogView.java index f8bbe31..621a90e 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/dialogs/SyncDialogView.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/dialogs/SyncDialogView.java @@ -1,88 +1,88 @@ -package cz.cvut.promod.services.projectService.dialogs; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; - -import javax.swing.*; -import java.awt.*; - -import com.jgoodies.forms.layout.FormLayout; -import com.jgoodies.forms.layout.CellConstraints; -import com.jgoodies.forms.factories.Borders; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 22:06:00, 13.11.2009 - */ - -/** - * SyncDialog view. - */ -public class SyncDialogView extends JDialog { - - private final JLabel errorsLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.errorlist")); - - private final JLabel searchLocationLabel = ModelerSession.getComponentFactoryService().createLabel( - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.searching")); - - protected final JLabel currentSearchLocationLabel = ModelerSession.getComponentFactoryService().createLabel(""); - - protected final JTextArea errorsTextArea = ModelerSession.getComponentFactoryService().createTextArea(); - - protected final JButton cancelButton = ModelerSession.getComponentFactoryService().createButton( - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.cancel"), null); - - protected final JButton okButton = ModelerSession.getComponentFactoryService().createButton( - ModelerSession.getCommonResourceBundle().getString("modeler.ok"), null); - - public SyncDialogView(final String title){ - super(ModelerSession.getFrame(), title); - - setLocationRelativeTo(ModelerSession.getFrame()); - - setSize(600, 350); - - errorsTextArea.setEditable(false); - - initLayout(); - } - - private void initLayout() { - final JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); - panel.setLayout(new BorderLayout()); - panel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); - - final CellConstraints cellConstraints = new CellConstraints(); - - final JPanel northPanel = ModelerSession.getComponentFactoryService().createPanel(); - northPanel.setLayout(new FormLayout( - "pref:grow, 10dlu, pref", - "pref, 3dlu, pref, 7dlu" - )); - - northPanel.add(searchLocationLabel, cellConstraints.xy(1,1)); - northPanel.add(cancelButton, cellConstraints.xy(3,1)); - - northPanel.add(currentSearchLocationLabel, cellConstraints.xyw(1, 3, 3)); - - final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); - centerPanel.setLayout(new BorderLayout()); - - centerPanel.add(errorsLabel, BorderLayout.NORTH); - centerPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(errorsTextArea), BorderLayout.CENTER); - - final JPanel southPanel = ModelerSession.getComponentFactoryService().createPanel(); - southPanel.setLayout(new FormLayout( - "right:pref:grow", - "7dlu, pref" - )); - southPanel.add(okButton, cellConstraints.xy(1,2)); - - panel.add(northPanel, BorderLayout.NORTH); - panel.add(centerPanel, BorderLayout.CENTER); - panel.add(southPanel, BorderLayout.SOUTH); - add(panel); - } -} +package cz.cvut.promod.services.projectService.dialogs; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.componentFactoryService.ComponentFactoryService; + +import javax.swing.*; +import java.awt.*; + +import com.jgoodies.forms.layout.FormLayout; +import com.jgoodies.forms.layout.CellConstraints; +import com.jgoodies.forms.factories.Borders; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 22:06:00, 13.11.2009 + */ + +/** + * SyncDialog view. + */ +public class SyncDialogView extends JDialog { + + private final JLabel errorsLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.errorlist")); + + private final JLabel searchLocationLabel = ModelerSession.getComponentFactoryService().createLabel( + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.searching")); + + protected final JLabel currentSearchLocationLabel = ModelerSession.getComponentFactoryService().createLabel(""); + + protected final JTextArea errorsTextArea = ModelerSession.getComponentFactoryService().createTextArea(); + + protected final JButton cancelButton = ModelerSession.getComponentFactoryService().createButton( + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.cancel"), null); + + protected final JButton okButton = ModelerSession.getComponentFactoryService().createButton( + ModelerSession.getCommonResourceBundle().getString("modeler.ok"), null); + + public SyncDialogView(final String title){ + super(ModelerSession.getFrame(), title); + + setLocationRelativeTo(ModelerSession.getFrame()); + + setSize(600, 350); + + errorsTextArea.setEditable(false); + + initLayout(); + } + + private void initLayout() { + final JPanel panel = ModelerSession.getComponentFactoryService().createPanel(); + panel.setLayout(new BorderLayout()); + panel.setBorder(Borders.createEmptyBorder(ComponentFactoryService.DEFAULT_FORM_BORDER)); + + final CellConstraints cellConstraints = new CellConstraints(); + + final JPanel northPanel = ModelerSession.getComponentFactoryService().createPanel(); + northPanel.setLayout(new FormLayout( + "pref:grow, 10dlu, pref", + "pref, 3dlu, pref, 7dlu" + )); + + northPanel.add(searchLocationLabel, cellConstraints.xy(1,1)); + northPanel.add(cancelButton, cellConstraints.xy(3,1)); + + northPanel.add(currentSearchLocationLabel, cellConstraints.xyw(1, 3, 3)); + + final JPanel centerPanel = ModelerSession.getComponentFactoryService().createPanel(); + centerPanel.setLayout(new BorderLayout()); + + centerPanel.add(errorsLabel, BorderLayout.NORTH); + centerPanel.add(ModelerSession.getComponentFactoryService().createScrollPane(errorsTextArea), BorderLayout.CENTER); + + final JPanel southPanel = ModelerSession.getComponentFactoryService().createPanel(); + southPanel.setLayout(new FormLayout( + "right:pref:grow", + "7dlu, pref" + )); + southPanel.add(okButton, cellConstraints.xy(1,2)); + + panel.add(northPanel, BorderLayout.NORTH); + panel.add(centerPanel, BorderLayout.CENTER); + panel.add(southPanel, BorderLayout.SOUTH); + add(panel); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileLoader.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileLoader.java index 46db464..c98c736 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileLoader.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileLoader.java @@ -1,337 +1,337 @@ -package cz.cvut.promod.services.projectService.localIO; - -import cz.cvut.promod.gui.ModelerModel; -import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.ProjectService; -import cz.cvut.promod.services.projectService.results.LoadProjectResult; -import cz.cvut.promod.services.projectService.results.ConfigurationDifference; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; -import cz.cvut.promod.plugin.extension.Extension; -import cz.cvut.promod.resources.Resources; - -import java.io.*; -import java.util.List; -import java.util.LinkedList; - -import org.apache.log4j.Logger; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.w3c.dom.Node; -import org.w3c.dom.NamedNodeMap; -import org.xml.sax.SAXException; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Source; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 0:44:44, 11.11.2009 - */ - -/** - * Project file loading functionality holder. - */ -public class ProjectFileLoader { - - private static final Logger LOG = Logger.getLogger(ProjectFileLoader.class); - - /** - * Loads the project file. - * - * @param projectFile is the FS project file location - * @return an instance of LoadProjectResult class holding operation results - */ - public static LoadProjectResult loadProjectFile(final File projectFile) { - if(!isValidFile(projectFile)){ - return null; - } - - final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - - final InputStream schemaInputStream = ClassLoader.getSystemResourceAsStream( - Resources.CONFIG + Resources.PROJECT_XSD_FILE - ); - - - final Schema schema; - final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - final Source source = new StreamSource(schemaInputStream); - try { - schema = schemaFactory.newSchema(source); - - } catch (SAXException e) { - LOG.info("Skipping plugin definition file validation. Schema not found."); - return new LoadProjectResult(null, null); - } - - LOG.info("Validating project file against xsd file."); - - documentBuilderFactory.setNamespaceAware(true); - documentBuilderFactory.setValidating(false); - - final Document document; - - try { - final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - - documentBuilder.setErrorHandler(new ProjectFileXmlErrorHandler()); - - document = documentBuilder.parse(projectFile); - - final Validator validator = schema.newValidator(); - - validator.validate(new DOMSource(document)); - - } catch (ParserConfigurationException e) { - LOG.error("XML Parser configuration has failed.", e); - return new LoadProjectResult(null, null); - - } catch (IOException e) { - LOG.error("An IO error has occurred when reading the project file.", e); - return new LoadProjectResult(null, null); - - } catch (SAXException e) { - LOG.error("An SAX error has occurred when reading the project file.", e); - return new LoadProjectResult(null, null); - } - - final List messages = getConfigurationChanges(document); - final ProjectRoot projectRoot = new ProjectRoot(getProjectName(projectFile.getName()), projectFile.getParent()); - - return new LoadProjectResult(projectRoot, messages); - } - - /** - * Finds differences in actual ProMod configuration and the configuration loaded from the project file - * and stores this changes in list. - * - * @param document is the loaded DOM document of project file - * - * @return list containing all differences in configuration - */ - private static List getConfigurationChanges(final Document document) { - final List messages = new LinkedList(); - - final NodeList rootNodeList = document.getElementsByTagName(XmlConsts.ROOT_ELEMENT); - if(rootNodeList.getLength() != 1){ - LOG.error("More than one (or missing) root node in project xml file."); - return null; - } - - final Node rootNode = rootNodeList.item(0); - - final NodeList nodeList = rootNode.getChildNodes(); - - for(int i = 0; i < nodeList.getLength(); i++){ - final Node node = nodeList.item(i); - - if(XmlConsts.BASIC_INFO_ELEMENT.equals(node.getNodeName())){ - processBasicInfo(node, messages); - - } else if(XmlConsts.CONFIGURATION_ELEMENT.equals(node.getNodeName())){ - final NodeList congigurationNodes = node.getChildNodes(); - - for(int j = 0; j < congigurationNodes.getLength(); j++){ - final Node configurationNode = congigurationNodes.item(j); - - if(XmlConsts.PLUGINS_ELEMENT.equals(configurationNode.getNodeName())){ - final NodeList pluginNodes = configurationNode.getChildNodes(); - - for(int k = 0; k < pluginNodes.getLength(); k++){ - final Node pluginNode = pluginNodes.item(k); - - if(XmlConsts.NOTATION_ELEMENT.equals(pluginNode.getNodeName())){ - processNotationSpecificInfo(pluginNode, messages); - - } else if(XmlConsts.EXTENSION_ELEMENT.equals(pluginNode.getNodeName())){ - processExtensionSpecificInfo(pluginNode, messages); - } - } - } - } - - break; - } - } - - return messages; - } - - /** - * Finds and saves for future use all differences between actual ProMod configuration and the configuration loaded - * from a project file related to the extensions. - * - * @param pluginNode is the plugin node from the project file DOM - * @param messages is the list that collect all differences - */ - private static void processExtensionSpecificInfo(final Node pluginNode, final List messages) { - final NamedNodeMap notationAttributes = pluginNode.getAttributes(); - final String extensionIdentifier = readAttribute(notationAttributes.getNamedItem(XmlConsts.IDENTIFIER_ATTRIBUTE)); - final String extensionFullName = readAttribute(notationAttributes.getNamedItem(XmlConsts.FULL_NAME_ATTRIBUTE)); - - if(extensionIdentifier != null){ - final Extension extension = ModelerSession.getExtensionService().getExtension(extensionIdentifier); - - if(extension == null){ - messages.add(new ConfigurationDifference(ConfigurationDifference.ChangeType.MISSING_EXTENSION, extensionIdentifier)); - - } else { - if(!extension.getName().equals(extensionFullName)){ - messages.add(new ConfigurationDifference( - ConfigurationDifference.ChangeType.DIFFERENT_FULL_NAME, extensionFullName, extensionIdentifier) - ); - } - } - - } else { - // should never happened - LOG.error("Missing extension identifier info in the project file."); - } - - } - - /** - * Finds and saves for future use all differences between actual ProMod configuration and the configuration loaded - * from a project file related to the notations and their modules. - * - * @param pluginNode is the plugin node from the project file DOM - * @param messages is the list that collect all differences - */ - private static void processNotationSpecificInfo(final Node pluginNode, final List messages) { - final NamedNodeMap notationAttributes = pluginNode.getAttributes(); - final String notationIdentifier = readAttribute(notationAttributes.getNamedItem(XmlConsts.IDENTIFIER_ATTRIBUTE)); - final String notationFullName = readAttribute(notationAttributes.getNamedItem(XmlConsts.FULL_NAME_ATTRIBUTE)); - final String notationAbbreviation = readAttribute(notationAttributes.getNamedItem(XmlConsts.ABBREVIATION_ATTRIBUTE)); - final String notationExtension = readAttribute(notationAttributes.getNamedItem(XmlConsts.EXTENSION_ATTRIBUTE)); - - if(notationIdentifier != null){ - final NotationSpecificPlugins notationSpecificPlugins = ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier); - - if(notationSpecificPlugins == null){ - messages.add(new ConfigurationDifference(ConfigurationDifference.ChangeType.MISSING_NOTATION, notationIdentifier)); - - } else { - final Notation notation = notationSpecificPlugins.getNotation(); - - if(!notation.getFullName().equals(notationFullName)){ // the full name doesn't fit - messages.add(new ConfigurationDifference( - ConfigurationDifference.ChangeType.DIFFERENT_FULL_NAME, notationFullName, notationIdentifier) - ); - } - if(!notation.getAbbreviation().equals(notationAbbreviation)){ // the abbreviation doesn't fit - messages.add(new ConfigurationDifference( - ConfigurationDifference.ChangeType.DIFFERENT_ABBREVIATION, notationAbbreviation, notationIdentifier) - ); - } - if(!notation.getLocalIOController().getNotationFileExtension().equals(notationExtension)){ // the extension doesn't fit - messages.add(new ConfigurationDifference( - ConfigurationDifference.ChangeType.DIFFERENT_EXTENSION, notationExtension, notationIdentifier) - ); - } - - final NodeList nodes = pluginNode.getChildNodes(); - for(int i = 0; i < nodes.getLength(); i++){ - final Node moduleNode = nodes.item(i); - - if(XmlConsts.MODULE_ELEMENT.equals(moduleNode.getNodeName())){ - final NamedNodeMap moduleAttributes = moduleNode.getAttributes(); - final String moduleIdentifier = readAttribute(moduleAttributes.getNamedItem(XmlConsts.IDENTIFIER_ATTRIBUTE)); - - if(moduleIdentifier != null){ - final Module module = notationSpecificPlugins.getModule(moduleIdentifier); - - if(module == null){ - messages.add(new ConfigurationDifference( - ConfigurationDifference.ChangeType.MISSING_MODULE, moduleIdentifier, notationIdentifier) - ); - } - } else { - // should never happened - LOG.error("Missing module identifier info in the project file."); - } - } - } - } - - } else { - // should never happened - LOG.error("Missing notation identifier info in the project file."); - } - - - } - - private static void processBasicInfo(final Node node, final List messages) { - // not important for projects - // possible usage for special purposes - } - - /** - * Reads node's attribute. - * - * @param node is the attribute node - * - * @return value of the attribute it exists, null otherwise - */ - private static String readAttribute(final Node node){ - if(node != null){ - return node.getNodeValue(); - } - - return null; - } - - private static String getProjectName(final String fileName) { - return fileName.substring(0, fileName.lastIndexOf(ProjectService.FILE_EXTENSION_DELIMITER)); - } - - /** - * Checks the basic validity of the project file. - * - * @param projectFile is the project file - * - * @return true if the project file is valid, false otherwise - */ - private static boolean isValidFile(final File projectFile){ - if(projectFile == null){ - LOG.error("Undefined project file."); - return false; - } - - if(!projectFile.exists()){ - LOG.error("Not existing project file."); - return false; - } - - if(!projectFile.canRead()){ - LOG.error("NOt possible to read the project file."); - return false; - } - - if(!projectFile.isFile()){ - LOG.error("Project file is not a file."); - return false; - } - - if(!projectFile.getName().endsWith(ProjectService.PROJECT_FILE_EXTENSION)){ - LOG.error("Not a correct project file extension."); - return false; - } - - return true; - } - -} +package cz.cvut.promod.services.projectService.localIO; + +import cz.cvut.promod.gui.ModelerModel; +import cz.cvut.promod.services.pluginLoaderService.utils.PluginLoadErrors; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.ProjectService; +import cz.cvut.promod.services.projectService.results.LoadProjectResult; +import cz.cvut.promod.services.projectService.results.ConfigurationDifference; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; +import cz.cvut.promod.plugin.extension.Extension; +import cz.cvut.promod.resources.Resources; + +import java.io.*; +import java.util.List; +import java.util.LinkedList; + +import org.apache.log4j.Logger; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.w3c.dom.Node; +import org.w3c.dom.NamedNodeMap; +import org.xml.sax.SAXException; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Validator; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 0:44:44, 11.11.2009 + */ + +/** + * Project file loading functionality holder. + */ +public class ProjectFileLoader { + + private static final Logger LOG = Logger.getLogger(ProjectFileLoader.class); + + /** + * Loads the project file. + * + * @param projectFile is the FS project file location + * @return an instance of LoadProjectResult class holding operation results + */ + public static LoadProjectResult loadProjectFile(final File projectFile) { + if(!isValidFile(projectFile)){ + return null; + } + + final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + + final InputStream schemaInputStream = ClassLoader.getSystemResourceAsStream( + Resources.CONFIG + Resources.PROJECT_XSD_FILE + ); + + + final Schema schema; + final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + final Source source = new StreamSource(schemaInputStream); + try { + schema = schemaFactory.newSchema(source); + + } catch (SAXException e) { + LOG.info("Skipping plugin definition file validation. Schema not found."); + return new LoadProjectResult(null, null); + } + + LOG.info("Validating project file against xsd file."); + + documentBuilderFactory.setNamespaceAware(true); + documentBuilderFactory.setValidating(false); + + final Document document; + + try { + final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + + documentBuilder.setErrorHandler(new ProjectFileXmlErrorHandler()); + + document = documentBuilder.parse(projectFile); + + final Validator validator = schema.newValidator(); + + validator.validate(new DOMSource(document)); + + } catch (ParserConfigurationException e) { + LOG.error("XML Parser configuration has failed.", e); + return new LoadProjectResult(null, null); + + } catch (IOException e) { + LOG.error("An IO error has occurred when reading the project file.", e); + return new LoadProjectResult(null, null); + + } catch (SAXException e) { + LOG.error("An SAX error has occurred when reading the project file.", e); + return new LoadProjectResult(null, null); + } + + final List messages = getConfigurationChanges(document); + final ProjectRoot projectRoot = new ProjectRoot(getProjectName(projectFile.getName()), projectFile.getParent()); + + return new LoadProjectResult(projectRoot, messages); + } + + /** + * Finds differences in actual ProMod configuration and the configuration loaded from the project file + * and stores this changes in list. + * + * @param document is the loaded DOM document of project file + * + * @return list containing all differences in configuration + */ + private static List getConfigurationChanges(final Document document) { + final List messages = new LinkedList(); + + final NodeList rootNodeList = document.getElementsByTagName(XmlConsts.ROOT_ELEMENT); + if(rootNodeList.getLength() != 1){ + LOG.error("More than one (or missing) root node in project xml file."); + return null; + } + + final Node rootNode = rootNodeList.item(0); + + final NodeList nodeList = rootNode.getChildNodes(); + + for(int i = 0; i < nodeList.getLength(); i++){ + final Node node = nodeList.item(i); + + if(XmlConsts.BASIC_INFO_ELEMENT.equals(node.getNodeName())){ + processBasicInfo(node, messages); + + } else if(XmlConsts.CONFIGURATION_ELEMENT.equals(node.getNodeName())){ + final NodeList congigurationNodes = node.getChildNodes(); + + for(int j = 0; j < congigurationNodes.getLength(); j++){ + final Node configurationNode = congigurationNodes.item(j); + + if(XmlConsts.PLUGINS_ELEMENT.equals(configurationNode.getNodeName())){ + final NodeList pluginNodes = configurationNode.getChildNodes(); + + for(int k = 0; k < pluginNodes.getLength(); k++){ + final Node pluginNode = pluginNodes.item(k); + + if(XmlConsts.NOTATION_ELEMENT.equals(pluginNode.getNodeName())){ + processNotationSpecificInfo(pluginNode, messages); + + } else if(XmlConsts.EXTENSION_ELEMENT.equals(pluginNode.getNodeName())){ + processExtensionSpecificInfo(pluginNode, messages); + } + } + } + } + + break; + } + } + + return messages; + } + + /** + * Finds and saves for future use all differences between actual ProMod configuration and the configuration loaded + * from a project file related to the extensions. + * + * @param pluginNode is the plugin node from the project file DOM + * @param messages is the list that collect all differences + */ + private static void processExtensionSpecificInfo(final Node pluginNode, final List messages) { + final NamedNodeMap notationAttributes = pluginNode.getAttributes(); + final String extensionIdentifier = readAttribute(notationAttributes.getNamedItem(XmlConsts.IDENTIFIER_ATTRIBUTE)); + final String extensionFullName = readAttribute(notationAttributes.getNamedItem(XmlConsts.FULL_NAME_ATTRIBUTE)); + + if(extensionIdentifier != null){ + final Extension extension = ModelerSession.getExtensionService().getExtension(extensionIdentifier); + + if(extension == null){ + messages.add(new ConfigurationDifference(ConfigurationDifference.ChangeType.MISSING_EXTENSION, extensionIdentifier)); + + } else { + if(!extension.getName().equals(extensionFullName)){ + messages.add(new ConfigurationDifference( + ConfigurationDifference.ChangeType.DIFFERENT_FULL_NAME, extensionFullName, extensionIdentifier) + ); + } + } + + } else { + // should never happened + LOG.error("Missing extension identifier info in the project file."); + } + + } + + /** + * Finds and saves for future use all differences between actual ProMod configuration and the configuration loaded + * from a project file related to the notations and their modules. + * + * @param pluginNode is the plugin node from the project file DOM + * @param messages is the list that collect all differences + */ + private static void processNotationSpecificInfo(final Node pluginNode, final List messages) { + final NamedNodeMap notationAttributes = pluginNode.getAttributes(); + final String notationIdentifier = readAttribute(notationAttributes.getNamedItem(XmlConsts.IDENTIFIER_ATTRIBUTE)); + final String notationFullName = readAttribute(notationAttributes.getNamedItem(XmlConsts.FULL_NAME_ATTRIBUTE)); + final String notationAbbreviation = readAttribute(notationAttributes.getNamedItem(XmlConsts.ABBREVIATION_ATTRIBUTE)); + final String notationExtension = readAttribute(notationAttributes.getNamedItem(XmlConsts.EXTENSION_ATTRIBUTE)); + + if(notationIdentifier != null){ + final NotationSpecificPlugins notationSpecificPlugins = ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier); + + if(notationSpecificPlugins == null){ + messages.add(new ConfigurationDifference(ConfigurationDifference.ChangeType.MISSING_NOTATION, notationIdentifier)); + + } else { + final Notation notation = notationSpecificPlugins.getNotation(); + + if(!notation.getFullName().equals(notationFullName)){ // the full name doesn't fit + messages.add(new ConfigurationDifference( + ConfigurationDifference.ChangeType.DIFFERENT_FULL_NAME, notationFullName, notationIdentifier) + ); + } + if(!notation.getAbbreviation().equals(notationAbbreviation)){ // the abbreviation doesn't fit + messages.add(new ConfigurationDifference( + ConfigurationDifference.ChangeType.DIFFERENT_ABBREVIATION, notationAbbreviation, notationIdentifier) + ); + } + if(!notation.getLocalIOController().getNotationFileExtension().equals(notationExtension)){ // the extension doesn't fit + messages.add(new ConfigurationDifference( + ConfigurationDifference.ChangeType.DIFFERENT_EXTENSION, notationExtension, notationIdentifier) + ); + } + + final NodeList nodes = pluginNode.getChildNodes(); + for(int i = 0; i < nodes.getLength(); i++){ + final Node moduleNode = nodes.item(i); + + if(XmlConsts.MODULE_ELEMENT.equals(moduleNode.getNodeName())){ + final NamedNodeMap moduleAttributes = moduleNode.getAttributes(); + final String moduleIdentifier = readAttribute(moduleAttributes.getNamedItem(XmlConsts.IDENTIFIER_ATTRIBUTE)); + + if(moduleIdentifier != null){ + final Module module = notationSpecificPlugins.getModule(moduleIdentifier); + + if(module == null){ + messages.add(new ConfigurationDifference( + ConfigurationDifference.ChangeType.MISSING_MODULE, moduleIdentifier, notationIdentifier) + ); + } + } else { + // should never happened + LOG.error("Missing module identifier info in the project file."); + } + } + } + } + + } else { + // should never happened + LOG.error("Missing notation identifier info in the project file."); + } + + + } + + private static void processBasicInfo(final Node node, final List messages) { + // not important for projects + // possible usage for special purposes + } + + /** + * Reads node's attribute. + * + * @param node is the attribute node + * + * @return value of the attribute it exists, null otherwise + */ + private static String readAttribute(final Node node){ + if(node != null){ + return node.getNodeValue(); + } + + return null; + } + + private static String getProjectName(final String fileName) { + return fileName.substring(0, fileName.lastIndexOf(ProjectService.FILE_EXTENSION_DELIMITER)); + } + + /** + * Checks the basic validity of the project file. + * + * @param projectFile is the project file + * + * @return true if the project file is valid, false otherwise + */ + private static boolean isValidFile(final File projectFile){ + if(projectFile == null){ + LOG.error("Undefined project file."); + return false; + } + + if(!projectFile.exists()){ + LOG.error("Not existing project file."); + return false; + } + + if(!projectFile.canRead()){ + LOG.error("NOt possible to read the project file."); + return false; + } + + if(!projectFile.isFile()){ + LOG.error("Project file is not a file."); + return false; + } + + if(!projectFile.getName().endsWith(ProjectService.PROJECT_FILE_EXTENSION)){ + LOG.error("Not a correct project file extension."); + return false; + } + + return true; + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileSaver.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileSaver.java index 5eef667..75da221 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileSaver.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileSaver.java @@ -1,253 +1,253 @@ -package cz.cvut.promod.services.projectService.localIO; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; -import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; -import cz.cvut.promod.plugin.extension.Extension; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; -import javax.xml.stream.*; -import javax.xml.transform.*; -import javax.xml.transform.stream.StreamResult; -import java.io.*; -import java.util.Date; - -import javax.xml.transform.stax.StAXSource; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:49:07, 19.11.2009 - */ -public class ProjectFileSaver { - - /** - * Saves the project to the xml project file. The location is defined by the - * location given by the project node and it's user object. - * - * There is saved some basic information about the project like project name, - * project location, date and user, but attributes project name and location - * are not important at all. This attributes are not use when the project is - * being loaded. - * - * There are then saved some information about the ProMod current configuration. - * Some basic information about currently loaded notations, modules and - * extension is saved. This info can be used when the project is being - * loaded to publish some errors or at least warn the user that there are - * some changes in ProMod configuration and some functionality can be missing - * or changed. - * - * @param projectTreePath is the tree path of the project navigation tree to the project root that is supposed - * to be saved - * - * @param useFormater if true, then then the xml output will be formatted, - * decreases performance - * - * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs - * - * @throws IOException an IO error has occurred - * - * @throws TransformerException specifies an exceptional condition that occurred during the transformation process - * - * @throws NullPointerException when the project location is null - * - * @throws IllegalArgumentException when the tree path to the project root is not valid - */ - public static void saveProject(final TreePath projectTreePath, final boolean useFormater) - throws XMLStreamException, IOException, TransformerException, NullPointerException, IllegalArgumentException { - - if(!ProjectServiceUtils.isValidTreePath(projectTreePath)){ - throw new IllegalArgumentException("Invalid tree path"); - } - - if(!ProjectServiceUtils.isProjectRoot((DefaultMutableTreeNode) projectTreePath.getLastPathComponent())){ - throw new IllegalArgumentException("Not a project root to save."); - } - - final DefaultMutableTreeNode projectRootNode = (DefaultMutableTreeNode) projectTreePath.getLastPathComponent(); - - final ProjectRoot projectRoot = (ProjectRoot) projectRootNode.getUserObject(); - - final File projectFile = projectRoot.getProjectFile(); - - if(projectFile == null){ - // should never happened - throw new IOException("Nullary project location"); - } - - final File parentFile = projectFile.getParentFile(); - - if(parentFile == null){ - throw new IOException("Nullary project location"); - } - - if(!parentFile.exists()){ - if(!parentFile.mkdirs()){ - throw new IOException("Unable to create necessary directories."); - } - } - - if(!projectFile.exists()){ - if(!projectFile.createNewFile()){ - throw new IOException("Impossible to create the project file"); - } - } - - final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); - final XMLStreamWriter xmlStreamWriter; - ByteArrayOutputStream byteArrayOutputStream = null; - - if(useFormater){ - byteArrayOutputStream = new ByteArrayOutputStream(); - xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(byteArrayOutputStream, XmlConsts.ENCODING); - } else { - xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(new FileOutputStream(projectRoot.getProjectFile()), XmlConsts.ENCODING); - } - - xmlStreamWriter.writeStartDocument(XmlConsts.ENCODING, XmlConsts.VERSION); - xmlStreamWriter.writeComment(XmlConsts.PROMOD_PROJECT_COMMENT); - xmlStreamWriter.writeStartElement(XmlConsts.ROOT_ELEMENT); - - writeBasicProjectInfo(xmlStreamWriter, projectRoot); - - writeConfigurationInfo(xmlStreamWriter); - - xmlStreamWriter.writeEndElement(); - xmlStreamWriter.writeEndDocument(); - xmlStreamWriter.close(); - - if(useFormater){ - final TransformerFactory transformerFactory = TransformerFactory.newInstance(); - final Transformer transformer = transformerFactory.newTransformer(); - - transformer.setOutputProperty(OutputKeys.METHOD, XmlConsts.METHOD); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, XmlConsts.NO); - transformer.setOutputProperty(OutputKeys.ENCODING, XmlConsts.ENCODING); - transformer.setOutputProperty(OutputKeys.INDENT, XmlConsts.YES); - transformer.setOutputProperty(XmlConsts.INDEND_AMOUNT_PROPERTY, XmlConsts.INDEND_AMOUNT); - - final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray() - ); - - XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); - XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader( - byteArrayInputStream - ); - - transformer.transform( - new StAXSource(xmlStreamReader), new StreamResult(projectRoot.getProjectFile())); - } - - } - - /** - * Appends current ProMod configuration data to the project xml file. - * It is that possible to publish error or warning if the project is - * loaded bt the ProMod having different configuration. - * - * It means, that there could be some missing notations, modules, extensions, - * or the notation could be the same but it can use different file extension - * and so on. - * - * @param xmlStreamWriter is a instance of XMLStreamWriter to that are the - * elements supposed to be written - * - * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs - */ - private static void writeConfigurationInfo(final XMLStreamWriter xmlStreamWriter) throws XMLStreamException { - xmlStreamWriter.writeStartElement(XmlConsts.CONFIGURATION_ELEMENT); - xmlStreamWriter.writeStartElement(XmlConsts.PLUGINS_ELEMENT); - writeNotationsInfo(xmlStreamWriter); - writeExtensionsInfo(xmlStreamWriter); - xmlStreamWriter.writeEndElement(); - xmlStreamWriter.writeEndElement(); - } - - /** - * Appends information about all notations and their related modules to the - * project xml file. - * - * @param xmlStreamWriter is a instance of XMLStreamWriter to that are the - * elements supposed to be written - * - * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs - */ - private static void writeNotationsInfo(final XMLStreamWriter xmlStreamWriter) throws XMLStreamException { - for(final String notationIdentifier : ModelerSession.getNotationService().getNotationsIdentifiers()){ - final NotationSpecificPlugins notationSpecificPlugins = - ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier); - final Notation notation = notationSpecificPlugins.getNotation(); - - xmlStreamWriter.writeStartElement(XmlConsts.NOTATION_ELEMENT); - xmlStreamWriter.writeAttribute(XmlConsts.IDENTIFIER_ATTRIBUTE, notation.getIdentifier()); - xmlStreamWriter.writeAttribute(XmlConsts.FULL_NAME_ATTRIBUTE, notation.getFullName()); - xmlStreamWriter.writeAttribute(XmlConsts.ABBREVIATION_ATTRIBUTE, notation.getAbbreviation()); - xmlStreamWriter.writeAttribute(XmlConsts.EXTENSION_ATTRIBUTE, notation.getLocalIOController().getNotationFileExtension()); - - for(final Module module : notationSpecificPlugins.getModules()){ - xmlStreamWriter.writeStartElement(XmlConsts.MODULE_ELEMENT); - xmlStreamWriter.writeAttribute(XmlConsts.IDENTIFIER_ATTRIBUTE, module.getIdentifier()); - xmlStreamWriter.writeEndElement(); - } - xmlStreamWriter.writeEndElement(); - } - } - - /** - * Appends basic extensions info to the project xml file. - * - * @param xmlStreamWriter is a instance of XMLStreamWriter to that are the - * extensions supposed to be written - * - * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs - */ - private static void writeExtensionsInfo(final XMLStreamWriter xmlStreamWriter) throws XMLStreamException { - for(final Extension extension : ModelerSession.getExtensionService().getExtensions()){ - xmlStreamWriter.writeStartElement(XmlConsts.EXTENSION_ELEMENT); - xmlStreamWriter.writeAttribute(XmlConsts.IDENTIFIER_ATTRIBUTE, extension.getIdentifier()); - xmlStreamWriter.writeAttribute(XmlConsts.FULL_NAME_ATTRIBUTE, extension.getName()); - xmlStreamWriter.writeAttribute(XmlConsts.DESCRIPTION_ATTRIBUTE, extension.getDescription()); - xmlStreamWriter.writeEndElement(); - } - } - - /** - * Appends basic project specific information to the project xml file. - * - * @param xmlOutputFactory is a instance of XMLStreamWriter to that are the - * elements supposed to be written - * - * @param projectRoot is the project root that is supposed to be written to - * the xml file - * - * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs - */ - private static void writeBasicProjectInfo(final XMLStreamWriter xmlOutputFactory, final ProjectRoot projectRoot) - throws XMLStreamException { - - xmlOutputFactory.writeStartElement(XmlConsts.BASIC_INFO_ELEMENT); - - xmlOutputFactory.writeStartElement(XmlConsts.LAST_NAME_ELEMENT); - xmlOutputFactory.writeCharacters(projectRoot.getDisplayName()); - xmlOutputFactory.writeEndElement(); - - xmlOutputFactory.writeStartElement(XmlConsts.LAST_LOCATION_ELEMENT); - xmlOutputFactory.writeCharacters(projectRoot.getProjectFile().getAbsolutePath()); - xmlOutputFactory.writeEndElement(); - - xmlOutputFactory.writeStartElement(XmlConsts.LAST_DATE_ELEMENT); - xmlOutputFactory.writeCharacters(new Date().toString()); - xmlOutputFactory.writeEndElement(); - - xmlOutputFactory.writeStartElement(XmlConsts.LAST_USER_ELEMENT); - ModelerSession.getUserService().getUser(); - xmlOutputFactory.writeEndElement(); - - xmlOutputFactory.writeEndElement(); - } -} +package cz.cvut.promod.services.projectService.localIO; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.pluginLoaderService.utils.NotationSpecificPlugins; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; +import cz.cvut.promod.plugin.notationSpecificPlugIn.module.Module; +import cz.cvut.promod.plugin.extension.Extension; + +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; +import javax.xml.stream.*; +import javax.xml.transform.*; +import javax.xml.transform.stream.StreamResult; +import java.io.*; +import java.util.Date; + +import javax.xml.transform.stax.StAXSource; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:49:07, 19.11.2009 + */ +public class ProjectFileSaver { + + /** + * Saves the project to the xml project file. The location is defined by the + * location given by the project node and it's user object. + * + * There is saved some basic information about the project like project name, + * project location, date and user, but attributes project name and location + * are not important at all. This attributes are not use when the project is + * being loaded. + * + * There are then saved some information about the ProMod current configuration. + * Some basic information about currently loaded notations, modules and + * extension is saved. This info can be used when the project is being + * loaded to publish some errors or at least warn the user that there are + * some changes in ProMod configuration and some functionality can be missing + * or changed. + * + * @param projectTreePath is the tree path of the project navigation tree to the project root that is supposed + * to be saved + * + * @param useFormater if true, then then the xml output will be formatted, + * decreases performance + * + * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs + * + * @throws IOException an IO error has occurred + * + * @throws TransformerException specifies an exceptional condition that occurred during the transformation process + * + * @throws NullPointerException when the project location is null + * + * @throws IllegalArgumentException when the tree path to the project root is not valid + */ + public static void saveProject(final TreePath projectTreePath, final boolean useFormater) + throws XMLStreamException, IOException, TransformerException, NullPointerException, IllegalArgumentException { + + if(!ProjectServiceUtils.isValidTreePath(projectTreePath)){ + throw new IllegalArgumentException("Invalid tree path"); + } + + if(!ProjectServiceUtils.isProjectRoot((DefaultMutableTreeNode) projectTreePath.getLastPathComponent())){ + throw new IllegalArgumentException("Not a project root to save."); + } + + final DefaultMutableTreeNode projectRootNode = (DefaultMutableTreeNode) projectTreePath.getLastPathComponent(); + + final ProjectRoot projectRoot = (ProjectRoot) projectRootNode.getUserObject(); + + final File projectFile = projectRoot.getProjectFile(); + + if(projectFile == null){ + // should never happened + throw new IOException("Nullary project location"); + } + + final File parentFile = projectFile.getParentFile(); + + if(parentFile == null){ + throw new IOException("Nullary project location"); + } + + if(!parentFile.exists()){ + if(!parentFile.mkdirs()){ + throw new IOException("Unable to create necessary directories."); + } + } + + if(!projectFile.exists()){ + if(!projectFile.createNewFile()){ + throw new IOException("Impossible to create the project file"); + } + } + + final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); + final XMLStreamWriter xmlStreamWriter; + ByteArrayOutputStream byteArrayOutputStream = null; + + if(useFormater){ + byteArrayOutputStream = new ByteArrayOutputStream(); + xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(byteArrayOutputStream, XmlConsts.ENCODING); + } else { + xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(new FileOutputStream(projectRoot.getProjectFile()), XmlConsts.ENCODING); + } + + xmlStreamWriter.writeStartDocument(XmlConsts.ENCODING, XmlConsts.VERSION); + xmlStreamWriter.writeComment(XmlConsts.PROMOD_PROJECT_COMMENT); + xmlStreamWriter.writeStartElement(XmlConsts.ROOT_ELEMENT); + + writeBasicProjectInfo(xmlStreamWriter, projectRoot); + + writeConfigurationInfo(xmlStreamWriter); + + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeEndDocument(); + xmlStreamWriter.close(); + + if(useFormater){ + final TransformerFactory transformerFactory = TransformerFactory.newInstance(); + final Transformer transformer = transformerFactory.newTransformer(); + + transformer.setOutputProperty(OutputKeys.METHOD, XmlConsts.METHOD); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, XmlConsts.NO); + transformer.setOutputProperty(OutputKeys.ENCODING, XmlConsts.ENCODING); + transformer.setOutputProperty(OutputKeys.INDENT, XmlConsts.YES); + transformer.setOutputProperty(XmlConsts.INDEND_AMOUNT_PROPERTY, XmlConsts.INDEND_AMOUNT); + + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( + byteArrayOutputStream.toByteArray() + ); + + XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); + XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader( + byteArrayInputStream + ); + + transformer.transform( + new StAXSource(xmlStreamReader), new StreamResult(projectRoot.getProjectFile())); + } + + } + + /** + * Appends current ProMod configuration data to the project xml file. + * It is that possible to publish error or warning if the project is + * loaded bt the ProMod having different configuration. + * + * It means, that there could be some missing notations, modules, extensions, + * or the notation could be the same but it can use different file extension + * and so on. + * + * @param xmlStreamWriter is a instance of XMLStreamWriter to that are the + * elements supposed to be written + * + * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs + */ + private static void writeConfigurationInfo(final XMLStreamWriter xmlStreamWriter) throws XMLStreamException { + xmlStreamWriter.writeStartElement(XmlConsts.CONFIGURATION_ELEMENT); + xmlStreamWriter.writeStartElement(XmlConsts.PLUGINS_ELEMENT); + writeNotationsInfo(xmlStreamWriter); + writeExtensionsInfo(xmlStreamWriter); + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeEndElement(); + } + + /** + * Appends information about all notations and their related modules to the + * project xml file. + * + * @param xmlStreamWriter is a instance of XMLStreamWriter to that are the + * elements supposed to be written + * + * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs + */ + private static void writeNotationsInfo(final XMLStreamWriter xmlStreamWriter) throws XMLStreamException { + for(final String notationIdentifier : ModelerSession.getNotationService().getNotationsIdentifiers()){ + final NotationSpecificPlugins notationSpecificPlugins = + ModelerSession.getNotationService().getNotationSpecificPlugins(notationIdentifier); + final Notation notation = notationSpecificPlugins.getNotation(); + + xmlStreamWriter.writeStartElement(XmlConsts.NOTATION_ELEMENT); + xmlStreamWriter.writeAttribute(XmlConsts.IDENTIFIER_ATTRIBUTE, notation.getIdentifier()); + xmlStreamWriter.writeAttribute(XmlConsts.FULL_NAME_ATTRIBUTE, notation.getFullName()); + xmlStreamWriter.writeAttribute(XmlConsts.ABBREVIATION_ATTRIBUTE, notation.getAbbreviation()); + xmlStreamWriter.writeAttribute(XmlConsts.EXTENSION_ATTRIBUTE, notation.getLocalIOController().getNotationFileExtension()); + + for(final Module module : notationSpecificPlugins.getModules()){ + xmlStreamWriter.writeStartElement(XmlConsts.MODULE_ELEMENT); + xmlStreamWriter.writeAttribute(XmlConsts.IDENTIFIER_ATTRIBUTE, module.getIdentifier()); + xmlStreamWriter.writeEndElement(); + } + xmlStreamWriter.writeEndElement(); + } + } + + /** + * Appends basic extensions info to the project xml file. + * + * @param xmlStreamWriter is a instance of XMLStreamWriter to that are the + * extensions supposed to be written + * + * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs + */ + private static void writeExtensionsInfo(final XMLStreamWriter xmlStreamWriter) throws XMLStreamException { + for(final Extension extension : ModelerSession.getExtensionService().getExtensions()){ + xmlStreamWriter.writeStartElement(XmlConsts.EXTENSION_ELEMENT); + xmlStreamWriter.writeAttribute(XmlConsts.IDENTIFIER_ATTRIBUTE, extension.getIdentifier()); + xmlStreamWriter.writeAttribute(XmlConsts.FULL_NAME_ATTRIBUTE, extension.getName()); + xmlStreamWriter.writeAttribute(XmlConsts.DESCRIPTION_ATTRIBUTE, extension.getDescription()); + xmlStreamWriter.writeEndElement(); + } + } + + /** + * Appends basic project specific information to the project xml file. + * + * @param xmlOutputFactory is a instance of XMLStreamWriter to that are the + * elements supposed to be written + * + * @param projectRoot is the project root that is supposed to be written to + * the xml file + * + * @throws javax.xml.stream.XMLStreamException when an xml streaming error occurs + */ + private static void writeBasicProjectInfo(final XMLStreamWriter xmlOutputFactory, final ProjectRoot projectRoot) + throws XMLStreamException { + + xmlOutputFactory.writeStartElement(XmlConsts.BASIC_INFO_ELEMENT); + + xmlOutputFactory.writeStartElement(XmlConsts.LAST_NAME_ELEMENT); + xmlOutputFactory.writeCharacters(projectRoot.getDisplayName()); + xmlOutputFactory.writeEndElement(); + + xmlOutputFactory.writeStartElement(XmlConsts.LAST_LOCATION_ELEMENT); + xmlOutputFactory.writeCharacters(projectRoot.getProjectFile().getAbsolutePath()); + xmlOutputFactory.writeEndElement(); + + xmlOutputFactory.writeStartElement(XmlConsts.LAST_DATE_ELEMENT); + xmlOutputFactory.writeCharacters(new Date().toString()); + xmlOutputFactory.writeEndElement(); + + xmlOutputFactory.writeStartElement(XmlConsts.LAST_USER_ELEMENT); + ModelerSession.getUserService().getUser(); + xmlOutputFactory.writeEndElement(); + + xmlOutputFactory.writeEndElement(); + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileXmlErrorHandler.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileXmlErrorHandler.java index 09f53ab..3082411 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileXmlErrorHandler.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/ProjectFileXmlErrorHandler.java @@ -1,35 +1,35 @@ -package cz.cvut.promod.services.projectService.localIO; - -import org.apache.log4j.Logger; -import org.xml.sax.SAXParseException; -import org.xml.sax.SAXException; -import org.xml.sax.ErrorHandler; -import cz.cvut.promod.services.pluginLoaderService.errorHandling.PluginLoaderErrorHandler; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 2:13:43, 9.2.2010 - */ -public class ProjectFileXmlErrorHandler implements ErrorHandler { - - private static final Logger LOG = Logger.getLogger(PluginLoaderErrorHandler.class); - - /** {@inheritDoc} */ - public void warning(SAXParseException exception) throws SAXException { - LOG.warn("Project loader XSD validating and parsing warning.", exception); - } - - /** {@inheritDoc} */ - public void error(SAXParseException exception) throws SAXException { - LOG.warn("Project loader XSD validating and parsing error.", exception); - throw new SAXException(exception); - } - - /** {@inheritDoc} */ - public void fatalError(SAXParseException exception) throws SAXException { - LOG.warn("Project loader XSD validating and parsing fatal error.", exception); - throw new SAXException(exception); - } - -} +package cz.cvut.promod.services.projectService.localIO; + +import org.apache.log4j.Logger; +import org.xml.sax.SAXParseException; +import org.xml.sax.SAXException; +import org.xml.sax.ErrorHandler; +import cz.cvut.promod.services.pluginLoaderService.errorHandling.PluginLoaderErrorHandler; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 2:13:43, 9.2.2010 + */ +public class ProjectFileXmlErrorHandler implements ErrorHandler { + + private static final Logger LOG = Logger.getLogger(PluginLoaderErrorHandler.class); + + /** {@inheritDoc} */ + public void warning(SAXParseException exception) throws SAXException { + LOG.warn("Project loader XSD validating and parsing warning.", exception); + } + + /** {@inheritDoc} */ + public void error(SAXParseException exception) throws SAXException { + LOG.warn("Project loader XSD validating and parsing error.", exception); + throw new SAXException(exception); + } + + /** {@inheritDoc} */ + public void fatalError(SAXParseException exception) throws SAXException { + LOG.warn("Project loader XSD validating and parsing fatal error.", exception); + throw new SAXException(exception); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/XmlConsts.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/XmlConsts.java index c446d7c..652cfba 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/XmlConsts.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/localIO/XmlConsts.java @@ -1,54 +1,54 @@ -package cz.cvut.promod.services.projectService.localIO; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 1:26:22, 29.10.2009 - */ - -/** - * Holds project file specific xml constants. - */ -public abstract class XmlConsts { - - public static final String ENCODING = "UTF-8"; - public static final String VERSION = "1.0"; - - public final static String XSD_SCHEMA_LANGUAGE_KEY = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; - public final static String XSD_SCHEMA_LANGUAGE_VALUE = "http://www.w3.org/2001/XMLSchema"; - - public final static String XSD_SCHEMA_SOURCE_KEY = "http://java.sun.com/xml/jaxp/properties/schemaSource"; - - public static final String PROMOD_PROJECT_COMMENT = - "ProMod project file. Avoid of unnecssary manul changes in this file!"; - - public static final String ROOT_ELEMENT = "promod-project"; - - public static final String BASIC_INFO_ELEMENT = "basics"; - public static final String LAST_NAME_ELEMENT = "last-name"; - public static final String LAST_LOCATION_ELEMENT = "last-location"; - public static final String LAST_DATE_ELEMENT = "date"; - public static final String LAST_USER_ELEMENT = "user"; - - public static final String CONFIGURATION_ELEMENT = "configuration"; - public static final String PLUGINS_ELEMENT = "plugins"; - - public static final String NOTATION_ELEMENT = "notation"; - public static final String MODULE_ELEMENT = "module"; - public static final String EXTENSION_ELEMENT = "extension"; - - public static final String IDENTIFIER_ATTRIBUTE = "identifier"; - public static final String FULL_NAME_ATTRIBUTE = "full-name"; - public static final String ABBREVIATION_ATTRIBUTE = "abbreviation"; - public static final String EXTENSION_ATTRIBUTE = "extension"; - public static final String DESCRIPTION_ATTRIBUTE = "description"; - - - public static final String INDEND_AMOUNT_PROPERTY = "{http://xml.apache.org/xslt}indent-amount"; - public static final String INDEND_AMOUNT = "2"; - public static final String YES = "yes"; - public static final String NO = "no"; - - public static final String METHOD = "xml"; - -} +package cz.cvut.promod.services.projectService.localIO; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 1:26:22, 29.10.2009 + */ + +/** + * Holds project file specific xml constants. + */ +public abstract class XmlConsts { + + public static final String ENCODING = "UTF-8"; + public static final String VERSION = "1.0"; + + public final static String XSD_SCHEMA_LANGUAGE_KEY = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; + public final static String XSD_SCHEMA_LANGUAGE_VALUE = "http://www.w3.org/2001/XMLSchema"; + + public final static String XSD_SCHEMA_SOURCE_KEY = "http://java.sun.com/xml/jaxp/properties/schemaSource"; + + public static final String PROMOD_PROJECT_COMMENT = + "ProMod project file. Avoid of unnecssary manul changes in this file!"; + + public static final String ROOT_ELEMENT = "promod-project"; + + public static final String BASIC_INFO_ELEMENT = "basics"; + public static final String LAST_NAME_ELEMENT = "last-name"; + public static final String LAST_LOCATION_ELEMENT = "last-location"; + public static final String LAST_DATE_ELEMENT = "date"; + public static final String LAST_USER_ELEMENT = "user"; + + public static final String CONFIGURATION_ELEMENT = "configuration"; + public static final String PLUGINS_ELEMENT = "plugins"; + + public static final String NOTATION_ELEMENT = "notation"; + public static final String MODULE_ELEMENT = "module"; + public static final String EXTENSION_ELEMENT = "extension"; + + public static final String IDENTIFIER_ATTRIBUTE = "identifier"; + public static final String FULL_NAME_ATTRIBUTE = "full-name"; + public static final String ABBREVIATION_ATTRIBUTE = "abbreviation"; + public static final String EXTENSION_ATTRIBUTE = "extension"; + public static final String DESCRIPTION_ATTRIBUTE = "description"; + + + public static final String INDEND_AMOUNT_PROPERTY = "{http://xml.apache.org/xslt}indent-amount"; + public static final String INDEND_AMOUNT = "2"; + public static final String YES = "yes"; + public static final String NO = "no"; + + public static final String METHOD = "xml"; + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/AddProjectItemResult.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/AddProjectItemResult.java index 7ea877f..edbb4e7 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/AddProjectItemResult.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/AddProjectItemResult.java @@ -1,34 +1,34 @@ -package cz.cvut.promod.services.projectService.results; - -import javax.swing.tree.TreePath; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 0:17:50, 16.11.2009 - */ - -/** - * Add project item result holder. - */ -public class AddProjectItemResult { - - final private AddProjectItemStatus status; - - final private TreePath treePath; - - public AddProjectItemResult(final AddProjectItemStatus status, - final TreePath treePath){ - - this.status = status; - this.treePath = treePath; - } - - public AddProjectItemStatus getStatus() { - return status; - } - - public TreePath getTreePath() { - return treePath; - } -} +package cz.cvut.promod.services.projectService.results; + +import javax.swing.tree.TreePath; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 0:17:50, 16.11.2009 + */ + +/** + * Add project item result holder. + */ +public class AddProjectItemResult { + + final private AddProjectItemStatus status; + + final private TreePath treePath; + + public AddProjectItemResult(final AddProjectItemStatus status, + final TreePath treePath){ + + this.status = status; + this.treePath = treePath; + } + + public AddProjectItemStatus getStatus() { + return status; + } + + public TreePath getTreePath() { + return treePath; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/AddProjectItemStatus.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/AddProjectItemStatus.java index 27d7985..b27a6a8 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/AddProjectItemStatus.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/AddProjectItemStatus.java @@ -1,44 +1,44 @@ -package cz.cvut.promod.services.projectService.results; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 13:05:20, 6.2.2010 - */ - -/** - * Represents the result of adding project item. - */ -public enum AddProjectItemStatus { - - /** - * No error has occurred. - */ - SUCCESS, - - /** - * There is already name colliding project item. - */ - NAME_DUPLICITY, - - /** - * The project item is invalid, e.g. nullary. - */ - INVALID_NAME, - - /** - * Not valid parent for the project item. - */ - ILLEGAL_PARENT, - - /** - * Not valid notation for the project item. - */ - ILLEGAL_NOTATION, - - /** - * Invalid project item data, e.g. nullary. - */ - INVALID_ITEM_DATA, - -} +package cz.cvut.promod.services.projectService.results; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 13:05:20, 6.2.2010 + */ + +/** + * Represents the result of adding project item. + */ +public enum AddProjectItemStatus { + + /** + * No error has occurred. + */ + SUCCESS, + + /** + * There is already name colliding project item. + */ + NAME_DUPLICITY, + + /** + * The project item is invalid, e.g. nullary. + */ + INVALID_NAME, + + /** + * Not valid parent for the project item. + */ + ILLEGAL_PARENT, + + /** + * Not valid notation for the project item. + */ + ILLEGAL_NOTATION, + + /** + * Invalid project item data, e.g. nullary. + */ + INVALID_ITEM_DATA, + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/ConfigurationDifference.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/ConfigurationDifference.java index 32bf8ab..051e905 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/ConfigurationDifference.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/ConfigurationDifference.java @@ -1,93 +1,93 @@ -package cz.cvut.promod.services.projectService.results; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:43:20, 8.2.2010 - */ - -/** - * Dialog showing ProMod configuration changes between actual configuration and the one loaded from a project file. - */ -public class ConfigurationDifference { - - public static enum ChangeType{ - /** - * There is referred a notation that does NOT exist in actual configuration of ProMod - * Message contains the identifier of the non existing notation. - */ - MISSING_NOTATION, - - /** - * There is referred a module that does NOT exist in actual configuration of ProMod. - * Message contains the identifier of the non existing module. - */ - MISSING_MODULE, - - /** - * There is referred a extension that does NOT exist in actual configuration of ProMod. - * Message contains the identifier of the non existing extension. - */ - MISSING_EXTENSION, - - /** - * There is an existing notation but has a different full name. - * Message contains the full name acquired from the project file. - */ - DIFFERENT_FULL_NAME, - - /** - * There is an existing notation but has a different abbreviation. - * Message contains the abbreviation acquired from the project file. - */ - DIFFERENT_ABBREVIATION, - - /** - * There is an existing notation but has a different extension. - * Message contains the extension acquired from the project file. - */ - DIFFERENT_EXTENSION, - } - - private final ChangeType changeType; - - private final String message; - - private final String identifier; - - - public ConfigurationDifference(final ChangeType changeType, final String message) { - this.changeType = changeType; - this.message = message; - - this.identifier = null; - } - - public ConfigurationDifference(final ChangeType changeType, final String message, final String identifier) { - this.changeType = changeType; - this.message = message; - - this.identifier = identifier; - } - - /** - * @return the configuration change type - */ - public ChangeType getChangeType() { - return changeType; - } - - /** - * @return the configuration change message - */ - public String getMessage() { - return message; - } - - /** - * @return the plugin identifier - */ - public String getIdentifier() { - return identifier; - } -} +package cz.cvut.promod.services.projectService.results; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:43:20, 8.2.2010 + */ + +/** + * Dialog showing ProMod configuration changes between actual configuration and the one loaded from a project file. + */ +public class ConfigurationDifference { + + public static enum ChangeType{ + /** + * There is referred a notation that does NOT exist in actual configuration of ProMod + * Message contains the identifier of the non existing notation. + */ + MISSING_NOTATION, + + /** + * There is referred a module that does NOT exist in actual configuration of ProMod. + * Message contains the identifier of the non existing module. + */ + MISSING_MODULE, + + /** + * There is referred a extension that does NOT exist in actual configuration of ProMod. + * Message contains the identifier of the non existing extension. + */ + MISSING_EXTENSION, + + /** + * There is an existing notation but has a different full name. + * Message contains the full name acquired from the project file. + */ + DIFFERENT_FULL_NAME, + + /** + * There is an existing notation but has a different abbreviation. + * Message contains the abbreviation acquired from the project file. + */ + DIFFERENT_ABBREVIATION, + + /** + * There is an existing notation but has a different extension. + * Message contains the extension acquired from the project file. + */ + DIFFERENT_EXTENSION, + } + + private final ChangeType changeType; + + private final String message; + + private final String identifier; + + + public ConfigurationDifference(final ChangeType changeType, final String message) { + this.changeType = changeType; + this.message = message; + + this.identifier = null; + } + + public ConfigurationDifference(final ChangeType changeType, final String message, final String identifier) { + this.changeType = changeType; + this.message = message; + + this.identifier = identifier; + } + + /** + * @return the configuration change type + */ + public ChangeType getChangeType() { + return changeType; + } + + /** + * @return the configuration change message + */ + public String getMessage() { + return message; + } + + /** + * @return the plugin identifier + */ + public String getIdentifier() { + return identifier; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/LoadProjectResult.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/LoadProjectResult.java index 3da94d7..38f66ad 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/LoadProjectResult.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/LoadProjectResult.java @@ -1,48 +1,48 @@ -package cz.cvut.promod.services.projectService.results; - -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; - -import java.util.List; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:32:57, 8.2.2010 - */ - -/** - * Class for representing a return value of loadProject(String) method defined in ProjectControlService interface. - * - * If the ProjectRoot and event the message are null, it was not possible to load file. Possible reason is not valid - * project file. - */ -public class LoadProjectResult{ - - private final ProjectRoot projectRoot; - - private final List messages; - - - public LoadProjectResult(final ProjectRoot projectRoot, final List messages) { - this.projectRoot = projectRoot; - this.messages = messages; - } - - /** - * Returns the project root. - * - * @return the loaded project root. - */ - public ProjectRoot getProjectRoot() { - return projectRoot; - } - - /** - * Returns list of messages about ProMod configuration differences. - * - * @return list of messages about ProMod configuration differences - */ - public List getMessages() { - return messages; - } -} +package cz.cvut.promod.services.projectService.results; + +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; + +import java.util.List; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:32:57, 8.2.2010 + */ + +/** + * Class for representing a return value of loadProject(String) method defined in ProjectControlService interface. + * + * If the ProjectRoot and event the message are null, it was not possible to load file. Possible reason is not valid + * project file. + */ +public class LoadProjectResult{ + + private final ProjectRoot projectRoot; + + private final List messages; + + + public LoadProjectResult(final ProjectRoot projectRoot, final List messages) { + this.projectRoot = projectRoot; + this.messages = messages; + } + + /** + * Returns the project root. + * + * @return the loaded project root. + */ + public ProjectRoot getProjectRoot() { + return projectRoot; + } + + /** + * Returns list of messages about ProMod configuration differences. + * + * @return list of messages about ProMod configuration differences + */ + public List getMessages() { + return messages; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/SaveProjectResult.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/SaveProjectResult.java index c7eb38e..be70fae 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/results/SaveProjectResult.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/results/SaveProjectResult.java @@ -1,36 +1,36 @@ -package cz.cvut.promod.services.projectService.results; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 20:37:47, 8.2.2010 - */ - -/** - * Possible result of project root saving file system operation. - */ -public enum SaveProjectResult { - - /** - * No error has occurred. The project root has been successfully saved. - */ - SUCCESS, - - /** - * Used for signaling run-time failure of writing file system operations. - */ - IOERROR, - - /** - * Represents a xml error during creating of a structure of xml project file. This error should practically NEVER - * happened - represents inner error of saving algorithm. - */ - XML_ERROR, - - /** - * This error occurs when one tries to save project root that represents by an invalid tree path, e.g. not valid - * tree path, or no project root specified by the tree path. - */ - INVALID_TREE_PATH - -} +package cz.cvut.promod.services.projectService.results; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 20:37:47, 8.2.2010 + */ + +/** + * Possible result of project root saving file system operation. + */ +public enum SaveProjectResult { + + /** + * No error has occurred. The project root has been successfully saved. + */ + SUCCESS, + + /** + * Used for signaling run-time failure of writing file system operations. + */ + IOERROR, + + /** + * Represents a xml error during creating of a structure of xml project file. This error should practically NEVER + * happened - represents inner error of saving algorithm. + */ + XML_ERROR, + + /** + * This error occurs when one tries to save project root that represents by an invalid tree path, e.g. not valid + * tree path, or no project root specified by the tree path. + */ + INVALID_TREE_PATH + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncFromFSWorker.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncFromFSWorker.java index 29a1c2e..5ae44ac 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncFromFSWorker.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncFromFSWorker.java @@ -1,561 +1,561 @@ -package cz.cvut.promod.services.projectService.syncWorkers; - -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.results.AddProjectItemStatus; -import cz.cvut.promod.services.projectService.results.AddProjectItemResult; -import cz.cvut.promod.services.projectService.dialogs.SyncDialog; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectItem; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectSubFolder; -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.*; -import javax.swing.tree.TreePath; -import javax.swing.tree.DefaultMutableTreeNode; -import java.io.File; -import java.util.List; -import java.util.Set; -import java.util.HashSet; -import java.util.concurrent.ExecutionException; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 20:40:56, 13.11.2009 - */ - -/** - * SyncFromFSWorker class is a Swing Worker performing synchronization from file system to project navigation. - */ -public class SyncFromFSWorker extends SwingWorker { - - private final Logger LOG = Logger.getLogger(SyncFromFSWorker.class); - - private static final String LOAD_PROJECT_FILE_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.error.load.project.file"); - private static final String INVALID_PROJECT_ROOT_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.error.invalid.project.root"); - private static final String SYNC_SUBTREE_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.error.subtree"); - private static final String SUBTREE_ROOT_NOT_EXIST_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.error.subtree.not.exist"); - private static final String GENERAL_ERROR = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.default.error.message"); - private static final String DIAGRAM_LOAD_ERROR = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.load.error"); - private static final String NOTATION_IDENRIFIER = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.error.identifier"); - private static final String NOTATION_EXTENSION = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.error.extension"); - private static final String CANCELED_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.canceled"); - private static final String OFFSET_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.offset.error"); - private static final String DIRECTORY_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.directory.error"); - private static final String EXCEPTION_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.exception"); - - - private final File projectFile; - - private final List pathOffset; - - private final boolean addProjectItems; - private final boolean overwriteProjectItems; - private final boolean deleteProjectItems; - - private final SyncDialog syncDialog; - - public SyncFromFSWorker(final File projectFile, - final List pathOffset, - final boolean addProjectItems, - final boolean overwriteProjectItems, - final boolean deleteProjectItems, - final SyncDialog syncDialog){ - - this.projectFile = projectFile; - this.pathOffset = pathOffset; - - this.addProjectItems = addProjectItems; - this.overwriteProjectItems = overwriteProjectItems; - this.deleteProjectItems = deleteProjectItems; - - this.syncDialog = syncDialog; - } - - /** - * Performs the synchronization. - * - * @return true if no error occurs, false otherwise - */ - public Boolean doInBackground(){ - showDialog(); - - try{ - final ProjectRoot projectRoot = - ModelerSession.getProjectControlService().loadProject(projectFile).getProjectRoot(); - - if(projectRoot == null){ - syncDialog.appendErrorInfo(LOAD_PROJECT_FILE_ERROR_LABEL, true); - return false; - } - - // determines whether the project is loaded in project navigation - TreePath loadedProjectTreePath = null; //tree path to that project - - for(final TreePath treePath : ModelerSession.getProjectService().getProjectPaths()){ - final ProjectRoot loadedProjectRoot; - - try{ - loadedProjectRoot = (ProjectRoot) ((DefaultMutableTreeNode) treePath.getPathComponent(1)).getUserObject(); - } catch (ClassCastException exception){ - LOG.error("Not valid project root in projects."); - syncDialog.appendErrorInfo(INVALID_PROJECT_ROOT_ERROR_LABEL, true); - return false; - } catch (NullPointerException exception){ - LOG.error("Not a project root in projects."); - syncDialog.appendErrorInfo(INVALID_PROJECT_ROOT_ERROR_LABEL, true); - return false; - } - - if(projectRoot.getDisplayName().equals(loadedProjectRoot.getDisplayName()) - && projectRoot.getProjectLocation().equals(loadedProjectRoot.getProjectLocation())){ - - loadedProjectTreePath = treePath; - break; - } - } - - if(loadedProjectTreePath == null){ - LOG.error("Not such a project in project navigation"); - syncDialog.appendErrorInfo(SYNC_SUBTREE_ERROR_LABEL, true); - return false; - } - - File fsSubtreeLocation = projectFile.getParentFile(); - - if((pathOffset != null) && (pathOffset.size() != 0)){ - loadedProjectTreePath = syncPathWithOffset( - projectFile.getParent(), - pathOffset, - loadedProjectTreePath, - addProjectItems); - - if(loadedProjectTreePath == null){ - LOG.error("Not such a project in project navigation"); - syncDialog.appendErrorInfo(INVALID_PROJECT_ROOT_ERROR_LABEL, true); - return false; - } - - File file = new File(projectFile.getParent()); - - for(final String fsItem : pathOffset){ - file = new File(file.getAbsolutePath(), fsItem); - } - - fsSubtreeLocation = file; - } - - return syncSubtreeToPN( - loadedProjectTreePath, - fsSubtreeLocation, - projectRoot, - addProjectItems, overwriteProjectItems, deleteProjectItems - ); - - } catch (InterruptedException exception){ - // sync has been interrupted by the user - - LOG.info("Synchronization has been interrupted by user."); - - syncDialog.appendErrorInfo(CANCELED_LABEL, true); - - return false; - - } catch (Exception exception){ - // this should never happened, debug + test purposes - LOG.error("An exception has been thrown during synchronization", exception); - syncDialog.appendErrorInfo(GENERAL_ERROR, false); - syncDialog.appendErrorInfo(exception.getMessage(), true); - - return false; - } - } - - /** - * Sync the path before the sync start point. - * - * @param parent file system project parent - * @param pathOffset the offset to the sync starting point - * @param loadedProjectTreePath given tree path the project navigation - * @param addProjectItems flag, if true new items will be added - * @return true if no error occurs, false otherwise - * @throws InterruptedException when the process is interrupted by the user - */ - private TreePath syncPathWithOffset(final String parent, - final List pathOffset, - TreePath loadedProjectTreePath, - final boolean addProjectItems) throws InterruptedException{ - - File file = new File(parent); - - for(int i = 0; i < pathOffset.size(); i++){ - - checkInterruption(); - - final String item = pathOffset.get(i); - - file = new File(file.getAbsolutePath(), item); - - if(!file.exists()){ - syncDialog.appendErrorInfo(OFFSET_ERROR_LABEL, false); - syncDialog.appendErrorInfo(" >> " + file.getAbsolutePath(), true); - - LOG.error("Illegal offset, file not exists: " + file.getAbsolutePath()); - - return null; - } - - if(file.isFile()){ // file (=diagram) can occupy only the last position in the offset - if(i != pathOffset.size() - 1){ - LOG.error("File item can only occupy the last position ofthe path offset."); - return null; - } - - return loadedProjectTreePath; - - } else if(file.isDirectory()){ - final TreePath longerTreePath = ProjectServiceUtils.findTreePath(file, loadedProjectTreePath); - - if(longerTreePath == null){ - if(addProjectItems){ - AddProjectItemResult result = - ModelerSession.getProjectControlService().addSubFolder(file.getName(), loadedProjectTreePath, false); - - if(result.getStatus() != AddProjectItemStatus.SUCCESS){ - return null; - } - - loadedProjectTreePath = ProjectServiceUtils.findTreePath(file, loadedProjectTreePath); // add new created node to the path - - } else { - return null; - } - } else { - loadedProjectTreePath = longerTreePath; // add next node to the path - } - - } else { - LOG.error("Item on the file system has not be identify. It has to be either a file or a directory."); - return null; - } - } - - return loadedProjectTreePath; - } - - /** - * Sync the subfoler. Used in recursion. - * - * @param treePath current tree path - * @param fsSubtreeLocation current file system location - * @param projectRoot project root - * @param addProjectItems if true new items will be added - * @param overwriteProjectItems if true current items will be over-writtem - * @param deleteProjectItems if true missing items will be deleted - * @return true if no error occurs, false otherwise - * @throws InterruptedException if the process is interrupted by the user - */ - private boolean syncSubtreeToPN(final TreePath treePath, - final File fsSubtreeLocation, - final ProjectRoot projectRoot, - final boolean addProjectItems, - final boolean overwriteProjectItems, - final boolean deleteProjectItems) throws InterruptedException{ - - checkInterruption(); - - if(!fsSubtreeLocation.exists()){ - syncDialog.appendErrorInfo(SUBTREE_ROOT_NOT_EXIST_ERROR_LABEL, true); - return false; - } - - syncDialog.updatePosition(SyncWorkersUtils.getMessageString(fsSubtreeLocation)); - - boolean retValue = true; - - final String name = fsSubtreeLocation.getName(); - - if(fsSubtreeLocation.isFile() && ProjectServiceUtils.hasNotationFileExtension(name)){ - // diagram file - - final TreePath childTreePath = ProjectServiceUtils.findTreePath(fsSubtreeLocation, treePath); - final String extension = ProjectServiceUtils.getFileExtension(name); - final String notationIdentifier = ModelerSession.getNotationService().getNotationIdentifier(extension); - - if(childTreePath == null && addProjectItems){ //add a new diagram - final ProjectDiagram projectDiagram; - try{ - projectDiagram = ModelerSession.getNotationService().getNotation(notationIdentifier).getLocalIOController().loadProjectDiagram(fsSubtreeLocation.getAbsolutePath()); - } catch (Exception exception){ - LOG.error("Synchronization failed during a diagram loading.", exception); - syncDialog.appendErrorInfo(DIAGRAM_LOAD_ERROR, false); - syncDialog.appendErrorInfo(NOTATION_IDENRIFIER + " " + notationIdentifier, false); - syncDialog.appendErrorInfo(NOTATION_EXTENSION + " " + extension, false); - syncDialog.appendErrorInfo(fsSubtreeLocation.getAbsolutePath(), true); - syncDialog.appendErrorInfo(EXCEPTION_LABEL + " " + exception.toString(), true); - - return false; - } - - final AddProjectItemResult result = - ModelerSession.getProjectControlService().addDiagram(projectDiagram, treePath, false); - - if(result.getStatus() != AddProjectItemStatus.SUCCESS){ - syncDialog.appendErrorInfo( - SyncWorkersUtils.reportDiagramError(result.getStatus(), fsSubtreeLocation, treePath, false), - true); - - return false; - } - - } else if(childTreePath != null && overwriteProjectItems){ // overwrite user's object of existing diagram - final ProjectDiagram projectDiagram; - try{ - projectDiagram = ModelerSession.getNotationService().getNotation(notationIdentifier).getLocalIOController().loadProjectDiagram(fsSubtreeLocation.getAbsolutePath()); - } catch (Exception exception){ - LOG.error("Synchronization failed during a diagram loading.", exception); - syncDialog.appendErrorInfo(DIAGRAM_LOAD_ERROR, false); - syncDialog.appendErrorInfo(NOTATION_IDENRIFIER + " " + notationIdentifier, false); - syncDialog.appendErrorInfo(NOTATION_EXTENSION + " " + extension, false); - syncDialog.appendErrorInfo(fsSubtreeLocation.getAbsolutePath(), true); - syncDialog.appendErrorInfo(exception.getMessage(), true); - - return false; - } - - if(childTreePath.getLastPathComponent() instanceof DefaultMutableTreeNode){ - final DefaultMutableTreeNode node = (DefaultMutableTreeNode) childTreePath.getLastPathComponent(); - - if(node.getUserObject() instanceof ProjectDiagram){ - final ProjectDiagram oldProjectDiagram = (ProjectDiagram) node.getUserObject(); - - ModelerSession.getProjectControlService().switchChangePublisher(oldProjectDiagram, projectDiagram); - } - } - - - ModelerSession.getProjectControlService().getProjectTreeModel().valueForPathChanged(childTreePath, projectDiagram); - - LOG.info("aa"); - } - - return true; - - } else if(fsSubtreeLocation.isFile()){ - if(fsSubtreeLocation.getAbsolutePath().equals(projectRoot.getProjectFile().getAbsolutePath())){ - // the project file (.pmp) - // the project item is not updated - } - - } else if (fsSubtreeLocation.isDirectory()){ - - final Set synchronizedItems = new HashSet(); - - /* Condition (fsSubtreeLocation.list() != null) ensures that the directory is readable (due to user's rights). - For example for the ordinary user the 'System Volume Information' directory is not accessible. */ - - if(fsSubtreeLocation.list() == null){ - // File system directory is not possible to open (due to the user's rights) - syncDialog.appendErrorInfo(DIRECTORY_ERROR_LABEL, false); - syncDialog.appendErrorInfo(" >> " + fsSubtreeLocation.getAbsolutePath(), true); - - } else { - - for(final String fsItem : fsSubtreeLocation.list()){ - - checkInterruption(); - - final File childFile = new File(fsSubtreeLocation.getAbsolutePath(), fsItem); - - if(childFile.isFile()){ - synchronizedItems.add(childFile); - - retValue &= syncSubtreeToPN( - treePath, - childFile, - projectRoot, - addProjectItems, overwriteProjectItems, deleteProjectItems - ); - - } else if(childFile.isDirectory()){ - synchronizedItems.add(childFile); - - final TreePath subfolderTreePath = ProjectServiceUtils.findTreePath(childFile, treePath); - - if(subfolderTreePath == null){ - if(addProjectItems){ - //add a new project subfolder - final AddProjectItemResult result = - ModelerSession.getProjectControlService().addSubFolder(childFile.getName(), treePath, false); - - if(result.getStatus() == AddProjectItemStatus.SUCCESS){ - //new project subfolder has been added, recursive search will be performed on this folder now - - final TreePath newSubfolderPath = ProjectServiceUtils.findTreePath(childFile, treePath); - - retValue &= syncSubtreeToPN( - newSubfolderPath, - childFile, - projectRoot, - addProjectItems, overwriteProjectItems, deleteProjectItems); - - } else { - //new project subfolder couldn't be added, no recursive search will performed on this folder - syncDialog.appendErrorInfo(SyncWorkersUtils.reportDiagramError( - result.getStatus(), childFile, treePath, false), true); - - retValue &= false; - } - } - - } else { - // subfolder exists in PN, there is no need to overwrite or add it - retValue &= syncSubtreeToPN( - subfolderTreePath, - childFile, - projectRoot, - addProjectItems, overwriteProjectItems, deleteProjectItems - ); - } - } - } - } - - if(deleteProjectItems){ - final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - - for(int i = 0; i < parentNode.getChildCount(); i++){ - final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); - final ProjectItem projectItem = (ProjectItem) childNode.getUserObject(); - - if(projectItem instanceof ProjectSubFolder){ - if(!isSubfolderOnFS(projectItem.getDisplayName(), synchronizedItems)){ - ModelerSession.getProjectControlService().removeProjectItem(treePath.pathByAddingChild(childNode)); - - LOG.info("Project subfolder '" + projectItem.getDisplayName() + "' has been removed."); - - } - } else if(projectItem instanceof ProjectDiagram){ - final TreePath childTreePath = treePath.pathByAddingChild(childNode); - - final String diagramFileName = new File(ProjectServiceUtils.getFileSystemPathToProjectItem(childTreePath)).getName(); - - - if(!isDiagramOnFS(diagramFileName, synchronizedItems)){ - ModelerSession.getProjectControlService().removeProjectItem(childTreePath); - - LOG.info("Project diagram '" + projectItem.getDisplayName() + "' has been removed."); - } - } - } - } - - } else { - LOG.error("An unknown file system has been identify. File system item has to be either file or directory."); - syncDialog.appendErrorInfo(GENERAL_ERROR, true); - return false; - } - - return retValue; - } - - /** - * Checks whether there is the required diagram on FS. - * - * @param diagramFileName diagram file name - * @param synchronizedItems sync items - * @return true when found, false otherwise - */ - private boolean isDiagramOnFS(final String diagramFileName, final Set synchronizedItems) { - for(final File file : synchronizedItems){ - if(file.isFile()){ - if(file.getName().equals(diagramFileName)){ - return true; - } - } - } - - return false; - } - - /** - * Checks whether there is the required subfolder on FS. - * - * @param subfolderName subfolder file name - * @param synchronizedItems sync items - * @return true when found, false otherwise - */ - private boolean isSubfolderOnFS(final String subfolderName, final Set synchronizedItems) { - for(final File file : synchronizedItems){ - if(file.isDirectory()){ - if(file.getName().equals(subfolderName)){ - return true; - } - } - } - - return false; - } - - /** - * Shows the sync dialog. - */ - public void showDialog(){ - SwingUtilities.invokeLater(new Runnable(){ - public void run() { - syncDialog.setVisible(true); - } - }); - } - - /** - * An object of SwingWorker invokes this done method on the Event Dispatcher Thread (EDT) when the doInBackground method - * finishes. This invocation is enqueued to the end of EDT's EventQueue. So it has to be queued after the task, - * tak shows the dialog. - */ - @Override - protected void done() { - syncDialog.disableCancelButton(); - - syncDialog.updatePosition( - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.searching.done") - ); - - try { - if(!isCancelled()){ - syncDialog.syncComplete(!get()); - - return; - } - - } catch (InterruptedException e) { - LOG.error("The synchronization from the file system has been interrupted.", e); - } catch (ExecutionException e) { - LOG.error("There is no return value available.", e); - } - - syncDialog.syncComplete(true); - } - - private void checkInterruption() throws InterruptedException{ - if (Thread.interrupted()) { - throw new InterruptedException(); - } - } -} - +package cz.cvut.promod.services.projectService.syncWorkers; + +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.results.AddProjectItemStatus; +import cz.cvut.promod.services.projectService.results.AddProjectItemResult; +import cz.cvut.promod.services.projectService.dialogs.SyncDialog; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectRoot; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectItem; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectSubFolder; +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.*; +import javax.swing.tree.TreePath; +import javax.swing.tree.DefaultMutableTreeNode; +import java.io.File; +import java.util.List; +import java.util.Set; +import java.util.HashSet; +import java.util.concurrent.ExecutionException; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 20:40:56, 13.11.2009 + */ + +/** + * SyncFromFSWorker class is a Swing Worker performing synchronization from file system to project navigation. + */ +public class SyncFromFSWorker extends SwingWorker { + + private final Logger LOG = Logger.getLogger(SyncFromFSWorker.class); + + private static final String LOAD_PROJECT_FILE_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.error.load.project.file"); + private static final String INVALID_PROJECT_ROOT_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.error.invalid.project.root"); + private static final String SYNC_SUBTREE_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.error.subtree"); + private static final String SUBTREE_ROOT_NOT_EXIST_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.error.subtree.not.exist"); + private static final String GENERAL_ERROR = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.default.error.message"); + private static final String DIAGRAM_LOAD_ERROR = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.load.error"); + private static final String NOTATION_IDENRIFIER = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.error.identifier"); + private static final String NOTATION_EXTENSION = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.error.extension"); + private static final String CANCELED_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.canceled"); + private static final String OFFSET_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.offset.error"); + private static final String DIRECTORY_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.directory.error"); + private static final String EXCEPTION_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.exception"); + + + private final File projectFile; + + private final List pathOffset; + + private final boolean addProjectItems; + private final boolean overwriteProjectItems; + private final boolean deleteProjectItems; + + private final SyncDialog syncDialog; + + public SyncFromFSWorker(final File projectFile, + final List pathOffset, + final boolean addProjectItems, + final boolean overwriteProjectItems, + final boolean deleteProjectItems, + final SyncDialog syncDialog){ + + this.projectFile = projectFile; + this.pathOffset = pathOffset; + + this.addProjectItems = addProjectItems; + this.overwriteProjectItems = overwriteProjectItems; + this.deleteProjectItems = deleteProjectItems; + + this.syncDialog = syncDialog; + } + + /** + * Performs the synchronization. + * + * @return true if no error occurs, false otherwise + */ + public Boolean doInBackground(){ + showDialog(); + + try{ + final ProjectRoot projectRoot = + ModelerSession.getProjectControlService().loadProject(projectFile).getProjectRoot(); + + if(projectRoot == null){ + syncDialog.appendErrorInfo(LOAD_PROJECT_FILE_ERROR_LABEL, true); + return false; + } + + // determines whether the project is loaded in project navigation + TreePath loadedProjectTreePath = null; //tree path to that project + + for(final TreePath treePath : ModelerSession.getProjectService().getProjectPaths()){ + final ProjectRoot loadedProjectRoot; + + try{ + loadedProjectRoot = (ProjectRoot) ((DefaultMutableTreeNode) treePath.getPathComponent(1)).getUserObject(); + } catch (ClassCastException exception){ + LOG.error("Not valid project root in projects."); + syncDialog.appendErrorInfo(INVALID_PROJECT_ROOT_ERROR_LABEL, true); + return false; + } catch (NullPointerException exception){ + LOG.error("Not a project root in projects."); + syncDialog.appendErrorInfo(INVALID_PROJECT_ROOT_ERROR_LABEL, true); + return false; + } + + if(projectRoot.getDisplayName().equals(loadedProjectRoot.getDisplayName()) + && projectRoot.getProjectLocation().equals(loadedProjectRoot.getProjectLocation())){ + + loadedProjectTreePath = treePath; + break; + } + } + + if(loadedProjectTreePath == null){ + LOG.error("Not such a project in project navigation"); + syncDialog.appendErrorInfo(SYNC_SUBTREE_ERROR_LABEL, true); + return false; + } + + File fsSubtreeLocation = projectFile.getParentFile(); + + if((pathOffset != null) && (pathOffset.size() != 0)){ + loadedProjectTreePath = syncPathWithOffset( + projectFile.getParent(), + pathOffset, + loadedProjectTreePath, + addProjectItems); + + if(loadedProjectTreePath == null){ + LOG.error("Not such a project in project navigation"); + syncDialog.appendErrorInfo(INVALID_PROJECT_ROOT_ERROR_LABEL, true); + return false; + } + + File file = new File(projectFile.getParent()); + + for(final String fsItem : pathOffset){ + file = new File(file.getAbsolutePath(), fsItem); + } + + fsSubtreeLocation = file; + } + + return syncSubtreeToPN( + loadedProjectTreePath, + fsSubtreeLocation, + projectRoot, + addProjectItems, overwriteProjectItems, deleteProjectItems + ); + + } catch (InterruptedException exception){ + // sync has been interrupted by the user + + LOG.info("Synchronization has been interrupted by user."); + + syncDialog.appendErrorInfo(CANCELED_LABEL, true); + + return false; + + } catch (Exception exception){ + // this should never happened, debug + test purposes + LOG.error("An exception has been thrown during synchronization", exception); + syncDialog.appendErrorInfo(GENERAL_ERROR, false); + syncDialog.appendErrorInfo(exception.getMessage(), true); + + return false; + } + } + + /** + * Sync the path before the sync start point. + * + * @param parent file system project parent + * @param pathOffset the offset to the sync starting point + * @param loadedProjectTreePath given tree path the project navigation + * @param addProjectItems flag, if true new items will be added + * @return true if no error occurs, false otherwise + * @throws InterruptedException when the process is interrupted by the user + */ + private TreePath syncPathWithOffset(final String parent, + final List pathOffset, + TreePath loadedProjectTreePath, + final boolean addProjectItems) throws InterruptedException{ + + File file = new File(parent); + + for(int i = 0; i < pathOffset.size(); i++){ + + checkInterruption(); + + final String item = pathOffset.get(i); + + file = new File(file.getAbsolutePath(), item); + + if(!file.exists()){ + syncDialog.appendErrorInfo(OFFSET_ERROR_LABEL, false); + syncDialog.appendErrorInfo(" >> " + file.getAbsolutePath(), true); + + LOG.error("Illegal offset, file not exists: " + file.getAbsolutePath()); + + return null; + } + + if(file.isFile()){ // file (=diagram) can occupy only the last position in the offset + if(i != pathOffset.size() - 1){ + LOG.error("File item can only occupy the last position ofthe path offset."); + return null; + } + + return loadedProjectTreePath; + + } else if(file.isDirectory()){ + final TreePath longerTreePath = ProjectServiceUtils.findTreePath(file, loadedProjectTreePath); + + if(longerTreePath == null){ + if(addProjectItems){ + AddProjectItemResult result = + ModelerSession.getProjectControlService().addSubFolder(file.getName(), loadedProjectTreePath, false); + + if(result.getStatus() != AddProjectItemStatus.SUCCESS){ + return null; + } + + loadedProjectTreePath = ProjectServiceUtils.findTreePath(file, loadedProjectTreePath); // add new created node to the path + + } else { + return null; + } + } else { + loadedProjectTreePath = longerTreePath; // add next node to the path + } + + } else { + LOG.error("Item on the file system has not be identify. It has to be either a file or a directory."); + return null; + } + } + + return loadedProjectTreePath; + } + + /** + * Sync the subfoler. Used in recursion. + * + * @param treePath current tree path + * @param fsSubtreeLocation current file system location + * @param projectRoot project root + * @param addProjectItems if true new items will be added + * @param overwriteProjectItems if true current items will be over-writtem + * @param deleteProjectItems if true missing items will be deleted + * @return true if no error occurs, false otherwise + * @throws InterruptedException if the process is interrupted by the user + */ + private boolean syncSubtreeToPN(final TreePath treePath, + final File fsSubtreeLocation, + final ProjectRoot projectRoot, + final boolean addProjectItems, + final boolean overwriteProjectItems, + final boolean deleteProjectItems) throws InterruptedException{ + + checkInterruption(); + + if(!fsSubtreeLocation.exists()){ + syncDialog.appendErrorInfo(SUBTREE_ROOT_NOT_EXIST_ERROR_LABEL, true); + return false; + } + + syncDialog.updatePosition(SyncWorkersUtils.getMessageString(fsSubtreeLocation)); + + boolean retValue = true; + + final String name = fsSubtreeLocation.getName(); + + if(fsSubtreeLocation.isFile() && ProjectServiceUtils.hasNotationFileExtension(name)){ + // diagram file + + final TreePath childTreePath = ProjectServiceUtils.findTreePath(fsSubtreeLocation, treePath); + final String extension = ProjectServiceUtils.getFileExtension(name); + final String notationIdentifier = ModelerSession.getNotationService().getNotationIdentifier(extension); + + if(childTreePath == null && addProjectItems){ //add a new diagram + final ProjectDiagram projectDiagram; + try{ + projectDiagram = ModelerSession.getNotationService().getNotation(notationIdentifier).getLocalIOController().loadProjectDiagram(fsSubtreeLocation.getAbsolutePath()); + } catch (Exception exception){ + LOG.error("Synchronization failed during a diagram loading.", exception); + syncDialog.appendErrorInfo(DIAGRAM_LOAD_ERROR, false); + syncDialog.appendErrorInfo(NOTATION_IDENRIFIER + " " + notationIdentifier, false); + syncDialog.appendErrorInfo(NOTATION_EXTENSION + " " + extension, false); + syncDialog.appendErrorInfo(fsSubtreeLocation.getAbsolutePath(), true); + syncDialog.appendErrorInfo(EXCEPTION_LABEL + " " + exception.toString(), true); + + return false; + } + + final AddProjectItemResult result = + ModelerSession.getProjectControlService().addDiagram(projectDiagram, treePath, false); + + if(result.getStatus() != AddProjectItemStatus.SUCCESS){ + syncDialog.appendErrorInfo( + SyncWorkersUtils.reportDiagramError(result.getStatus(), fsSubtreeLocation, treePath, false), + true); + + return false; + } + + } else if(childTreePath != null && overwriteProjectItems){ // overwrite user's object of existing diagram + final ProjectDiagram projectDiagram; + try{ + projectDiagram = ModelerSession.getNotationService().getNotation(notationIdentifier).getLocalIOController().loadProjectDiagram(fsSubtreeLocation.getAbsolutePath()); + } catch (Exception exception){ + LOG.error("Synchronization failed during a diagram loading.", exception); + syncDialog.appendErrorInfo(DIAGRAM_LOAD_ERROR, false); + syncDialog.appendErrorInfo(NOTATION_IDENRIFIER + " " + notationIdentifier, false); + syncDialog.appendErrorInfo(NOTATION_EXTENSION + " " + extension, false); + syncDialog.appendErrorInfo(fsSubtreeLocation.getAbsolutePath(), true); + syncDialog.appendErrorInfo(exception.getMessage(), true); + + return false; + } + + if(childTreePath.getLastPathComponent() instanceof DefaultMutableTreeNode){ + final DefaultMutableTreeNode node = (DefaultMutableTreeNode) childTreePath.getLastPathComponent(); + + if(node.getUserObject() instanceof ProjectDiagram){ + final ProjectDiagram oldProjectDiagram = (ProjectDiagram) node.getUserObject(); + + ModelerSession.getProjectControlService().switchChangePublisher(oldProjectDiagram, projectDiagram); + } + } + + + ModelerSession.getProjectControlService().getProjectTreeModel().valueForPathChanged(childTreePath, projectDiagram); + + LOG.info("aa"); + } + + return true; + + } else if(fsSubtreeLocation.isFile()){ + if(fsSubtreeLocation.getAbsolutePath().equals(projectRoot.getProjectFile().getAbsolutePath())){ + // the project file (.pmp) + // the project item is not updated + } + + } else if (fsSubtreeLocation.isDirectory()){ + + final Set synchronizedItems = new HashSet(); + + /* Condition (fsSubtreeLocation.list() != null) ensures that the directory is readable (due to user's rights). + For example for the ordinary user the 'System Volume Information' directory is not accessible. */ + + if(fsSubtreeLocation.list() == null){ + // File system directory is not possible to open (due to the user's rights) + syncDialog.appendErrorInfo(DIRECTORY_ERROR_LABEL, false); + syncDialog.appendErrorInfo(" >> " + fsSubtreeLocation.getAbsolutePath(), true); + + } else { + + for(final String fsItem : fsSubtreeLocation.list()){ + + checkInterruption(); + + final File childFile = new File(fsSubtreeLocation.getAbsolutePath(), fsItem); + + if(childFile.isFile()){ + synchronizedItems.add(childFile); + + retValue &= syncSubtreeToPN( + treePath, + childFile, + projectRoot, + addProjectItems, overwriteProjectItems, deleteProjectItems + ); + + } else if(childFile.isDirectory()){ + synchronizedItems.add(childFile); + + final TreePath subfolderTreePath = ProjectServiceUtils.findTreePath(childFile, treePath); + + if(subfolderTreePath == null){ + if(addProjectItems){ + //add a new project subfolder + final AddProjectItemResult result = + ModelerSession.getProjectControlService().addSubFolder(childFile.getName(), treePath, false); + + if(result.getStatus() == AddProjectItemStatus.SUCCESS){ + //new project subfolder has been added, recursive search will be performed on this folder now + + final TreePath newSubfolderPath = ProjectServiceUtils.findTreePath(childFile, treePath); + + retValue &= syncSubtreeToPN( + newSubfolderPath, + childFile, + projectRoot, + addProjectItems, overwriteProjectItems, deleteProjectItems); + + } else { + //new project subfolder couldn't be added, no recursive search will performed on this folder + syncDialog.appendErrorInfo(SyncWorkersUtils.reportDiagramError( + result.getStatus(), childFile, treePath, false), true); + + retValue &= false; + } + } + + } else { + // subfolder exists in PN, there is no need to overwrite or add it + retValue &= syncSubtreeToPN( + subfolderTreePath, + childFile, + projectRoot, + addProjectItems, overwriteProjectItems, deleteProjectItems + ); + } + } + } + } + + if(deleteProjectItems){ + final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + + for(int i = 0; i < parentNode.getChildCount(); i++){ + final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); + final ProjectItem projectItem = (ProjectItem) childNode.getUserObject(); + + if(projectItem instanceof ProjectSubFolder){ + if(!isSubfolderOnFS(projectItem.getDisplayName(), synchronizedItems)){ + ModelerSession.getProjectControlService().removeProjectItem(treePath.pathByAddingChild(childNode)); + + LOG.info("Project subfolder '" + projectItem.getDisplayName() + "' has been removed."); + + } + } else if(projectItem instanceof ProjectDiagram){ + final TreePath childTreePath = treePath.pathByAddingChild(childNode); + + final String diagramFileName = new File(ProjectServiceUtils.getFileSystemPathToProjectItem(childTreePath)).getName(); + + + if(!isDiagramOnFS(diagramFileName, synchronizedItems)){ + ModelerSession.getProjectControlService().removeProjectItem(childTreePath); + + LOG.info("Project diagram '" + projectItem.getDisplayName() + "' has been removed."); + } + } + } + } + + } else { + LOG.error("An unknown file system has been identify. File system item has to be either file or directory."); + syncDialog.appendErrorInfo(GENERAL_ERROR, true); + return false; + } + + return retValue; + } + + /** + * Checks whether there is the required diagram on FS. + * + * @param diagramFileName diagram file name + * @param synchronizedItems sync items + * @return true when found, false otherwise + */ + private boolean isDiagramOnFS(final String diagramFileName, final Set synchronizedItems) { + for(final File file : synchronizedItems){ + if(file.isFile()){ + if(file.getName().equals(diagramFileName)){ + return true; + } + } + } + + return false; + } + + /** + * Checks whether there is the required subfolder on FS. + * + * @param subfolderName subfolder file name + * @param synchronizedItems sync items + * @return true when found, false otherwise + */ + private boolean isSubfolderOnFS(final String subfolderName, final Set synchronizedItems) { + for(final File file : synchronizedItems){ + if(file.isDirectory()){ + if(file.getName().equals(subfolderName)){ + return true; + } + } + } + + return false; + } + + /** + * Shows the sync dialog. + */ + public void showDialog(){ + SwingUtilities.invokeLater(new Runnable(){ + public void run() { + syncDialog.setVisible(true); + } + }); + } + + /** + * An object of SwingWorker invokes this done method on the Event Dispatcher Thread (EDT) when the doInBackground method + * finishes. This invocation is enqueued to the end of EDT's EventQueue. So it has to be queued after the task, + * tak shows the dialog. + */ + @Override + protected void done() { + syncDialog.disableCancelButton(); + + syncDialog.updatePosition( + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.searching.done") + ); + + try { + if(!isCancelled()){ + syncDialog.syncComplete(!get()); + + return; + } + + } catch (InterruptedException e) { + LOG.error("The synchronization from the file system has been interrupted.", e); + } catch (ExecutionException e) { + LOG.error("There is no return value available.", e); + } + + syncDialog.syncComplete(true); + } + + private void checkInterruption() throws InterruptedException{ + if (Thread.interrupted()) { + throw new InterruptedException(); + } + } +} + diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncFromPNWorker.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncFromPNWorker.java index d1d1805..c8189fa 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncFromPNWorker.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncFromPNWorker.java @@ -1,525 +1,525 @@ -package cz.cvut.promod.services.projectService.syncWorkers; - -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.ProjectService; -import cz.cvut.promod.services.projectService.results.SaveProjectResult; -import cz.cvut.promod.services.projectService.dialogs.SyncDialog; -import cz.cvut.promod.services.projectService.treeProjectNode.*; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.localIOController.NotationLocalIOController; - -import javax.swing.*; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; -import java.io.File; -import java.util.Set; -import java.util.HashSet; -import java.util.concurrent.ExecutionException; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:10:13, 13.11.2009 - */ - -/** - * Class that performs synchronization in a direction from project navigation tree to the file system. - * This class extends SwingWorker class, so the synchronization is performed asynchronously to the Event Dispatcher Thread. - * Process of synchronization is NOT thread safety. It is highly recommended to do NOT use this class directly, but use - * ModelerSession.getProjectControlService().synchronize(...) method instead. If you use this synchronize(...) method, - * you don't have to worry about concurrency issues, because this method shows a modal dialog displaying synchronization - * errors and makes the Event Dispatcher Thread wait for the result of the synchronize() method. So, it is not possible to - * invoke other methods on Event Dispatcher Thread during synchronization. - */ -public class SyncFromPNWorker extends SwingWorker { - - private final Logger LOG = Logger.getLogger(SyncFromPNWorker.class); - - private static final String IMPOSSIBLE_TO_SAVE_PROJECT_FILE_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.project.file.error"); - private static final String PROJECT_ROOT_NOT_FOUND_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.project.root.error"); - private static final String INVALID_TREE_PATH_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.invalid.treepath"); - private static final String MISSING_PROJECT_FILE_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.missing.project.file"); - private static final String SYNC_SUBTREE_BUILD_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.subtree.build.error"); - private static final String INVALID_PARENT_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.invalid.parent"); - private static final String DIAGRAM_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.error.diagram"); - private static final String NOTATION_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.error.identifier"); - private static final String DIAGRAM_OVERWRITE_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.overwritten"); - private static final String DIAGRAM_WRITE_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.write"); - private static final String MKDIR_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.mkdir.error"); - private static final String DELETE_ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.delete.error"); - - private final TreePath treePath; - - private final boolean addProjectItems; - private final boolean overwriteProjectItems; - private final boolean deleteProjectItems; - - private final SyncDialog syncDialog; - - public SyncFromPNWorker(final TreePath treePath, - final boolean addProjectItems, - final boolean overwriteProjectItems, - final boolean deleteProjectItems, - final SyncDialog syncDialog){ - - this.treePath = treePath; - - this.addProjectItems = addProjectItems; - this.overwriteProjectItems = overwriteProjectItems; - this.deleteProjectItems = deleteProjectItems; - - this.syncDialog = syncDialog; - } - - /** - * Prepares the synchronization process and starts the synchronization. - * - * @return true if there were no errors during synchronization process, false otherwise - * - * @throws Exception when something happened, synchronize(...) (see above) method deals with possible problems - */ - protected Boolean doInBackground() throws Exception { - showDialog(); - - // First goes the JTree main projects root (root node, invisible for users) and then a project root node. - if(!ProjectServiceUtils.isValidTreePath(treePath) || treePath.getPathCount() < 2){ - LOG.error("Invalid tree path."); - syncDialog.appendErrorInfo(INVALID_TREE_PATH_LABEL, true); - return false; - } - - final DefaultMutableTreeNode projectRootNode; - final ProjectRoot projectRoot; - try{ - projectRootNode = (DefaultMutableTreeNode) treePath.getPathComponent(1); - projectRoot = (ProjectRoot) projectRootNode.getUserObject(); - } catch (ClassCastException exception){ - // should never happened, because isValidTreePath() method ensures this; testing & debuging purposes - LOG.error("Project root not found."); - syncDialog.appendErrorInfo(PROJECT_ROOT_NOT_FOUND_LABEL, true); - return false; - } - - final File projectRootFile = - new File(projectRoot.getProjectLocation(), projectRoot.getDisplayName() + ProjectService.PROJECT_FILE_EXTENSION); - - if(projectRootFile.exists() && overwriteProjectItems && - /* overwrite project file only when the project root is set as tree path (constructor argument) */ - treePath.equals(ModelerSession.getProjectService().getProjectPath(projectRoot.getDisplayName()))){ - - final SaveProjectResult result = ModelerSession.getProjectControlService().saveProject(treePath); //overwrite the project file - if(!SaveProjectResult.SUCCESS.equals(result)){ - LOG.error("Not possible to save project file"); - syncDialog.appendErrorInfo(IMPOSSIBLE_TO_SAVE_PROJECT_FILE_LABEL, true); - return false; - } - - } else if(!projectRootFile.exists() && addProjectItems){ - final SaveProjectResult result = ModelerSession.getProjectControlService().saveProject(treePath); //create the project file - if(!SaveProjectResult.SUCCESS.equals(result)){ - LOG.error("Not possible to save project file"); - syncDialog.appendErrorInfo(IMPOSSIBLE_TO_SAVE_PROJECT_FILE_LABEL, true); - return false; - } - - } else if(!projectRootFile.exists()){ - LOG.error("Project file not found and synchronization is not allowed to add items to the file system."); - syncDialog.appendErrorInfo(MISSING_PROJECT_FILE_LABEL, true); - return false; - } - - final File path = syncPathToTreeRootToFS( - new File(projectRootFile.getParent()), - treePath, - addProjectItems - ); - - if (path == null){ - syncDialog.appendErrorInfo(SYNC_SUBTREE_BUILD_ERROR_LABEL, true); - return false; - } - - /* This is kind of hack to show, that there is no need to continue, - there are still differences between FS and PN, but the method is not allowed to create FS items. */ - return path.getAbsolutePath().equals("") || syncSubtreeToFS( - path, - treePath, - addProjectItems, overwriteProjectItems, deleteProjectItems); - - } - - /** - * Schedules JDialog#setVisible(true) invocation on the Event Dispatcher Thread. - */ - private void showDialog(){ - SwingUtilities.invokeLater(new Runnable(){ - public void run() { - syncDialog.setVisible(true); - } - }); - } - - /** - * Synchronize the file system structure before the subtree that is supposed to be synchronized. This structure to the - * subtree node is created if and only if the addProjectItems is true. Otherwise no items on the file system are created and - * the whole synchronization finishes successfully, even though that there is still differences between file system and - * project navigation. - * - * @param file is the project root directory - * - * @param treePath is the path to the project tree subtree which is supposed to be synchronized - * - * @param addProjectItems indicates whether new items are supposed to be created on the file system if they are missing - * - * @return the file system path related to the subtree chosen to synchronize, null if any error occurs or an instance - * of file class with empty path in it, if there are still differences but the method is not allowed to create items on the - * file system - * - * @throws InterruptedException user has canceled the synchronization - */ - private File syncPathToTreeRootToFS(final File file, - final TreePath treePath, - final boolean addProjectItems) throws InterruptedException{ - File path = file; - - for(int i = 1; i < treePath.getPathCount(); i++){ - checkInterruption(); - - final DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) treePath.getPathComponent(i); - final Object userObject = defaultMutableTreeNode.getUserObject(); - - // update sync dialog - if(userObject instanceof ProjectItem){ - syncDialog.updatePosition(((ProjectItem)userObject).getDisplayName()); - - } else { - // should never happened - LOG.error("All project items have to be instances of classes implementing ProjectItem interface."); - return null; - } - - if(userObject instanceof ProjectRoot){ - if(i > 1){ // should never happened - return null; - } - - } else if(userObject instanceof ProjectDiagram){ - if(i < 2){ // should never happened - return null; - } - - if(defaultMutableTreeNode == treePath.getLastPathComponent()){ - return path; - } else { - return null; // diagram cannot have any children in the tree path - } - - } else if(userObject instanceof ProjectSubFolder){ - if(i < 2){ // should never happened - return null; - } - - final ProjectItem projectItem = (ProjectItem) userObject; - final File subfolder = new File(path.getAbsolutePath(), projectItem.getDisplayName()); - - if(!subfolder.exists()){ - - if(addProjectItems){ - if(subfolder.mkdir()){ - LOG.debug("Sync PN -> FS: new subfolder has been created, " + subfolder.getAbsolutePath() + "."); - } else { - LOG.error("Sync PN -> FS: Creating of a new subfolder has failed failed, " + subfolder.getAbsolutePath() + "."); - return null; - } - } else { // there are differences between PN and FS, but synchronize method is not invoked with addProjectItems flag - return new File(""); - } - } - - path = new File(subfolder.getAbsolutePath()); - - } else { - // should never happened - LOG.error("Project node has to be an instance of ProjectRoot, ProjectSubFolder or Project Diagram class."); - } - } - - return path; - } - - /** - * Synchronize the selected project subtree to the file system. This methods requires the correct starting level - * on the file system with respect to the project subtree to exist. - * - * Important to note that this method synchronize only the SUBTREE 'under' the last tree node in the treePath variable. - * - * @param fsLevel is the starting point for the synchronization on the file system - * @param treePath is the starting point in the project structure for the synchronization - * @param addProjectItems indicates whether new items are supposed to be created on the file system if they are missing - * @param overwriteProjectItems indicates whether diagrams that already exists on the file system are supposed to be overwritten - * @param deleteProjectItems indicates whether not projects items (files or diagrams) are supposed to be deleted from file system - * - * @return true if and only if no error occurs, false otherwise - * - * @throws InterruptedException when user cancels the synchronization - */ - private boolean syncSubtreeToFS(final File fsLevel, - final TreePath treePath, - final boolean addProjectItems, - final boolean overwriteProjectItems, - final boolean deleteProjectItems) throws InterruptedException{ - - checkInterruption(); - - boolean retValue = true; - - final DefaultMutableTreeNode lastTreePathNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - final Object userObject = lastTreePathNode.getUserObject(); - final ProjectItem projectItem; - - projectItem = (ProjectItem) userObject; - - // sync a project diagram - if(userObject instanceof ProjectDiagram){ - final ProjectDiagram projectDiagram = (ProjectDiagram) userObject; - final String fileExtension = ProjectServiceUtils.getNotationFileExtension(projectDiagram.getNotationIdentifier()); - - final File projectItemFile = new File(fsLevel.getAbsolutePath(), projectItem.getDisplayName() + fileExtension); - - NotationLocalIOController.SaveResult successSaveResult = NotationLocalIOController.SaveResult.SUCCESS; - - if(projectItemFile.exists() && overwriteProjectItems){ - successSaveResult = ModelerSession.getNotationService().getNotation(projectDiagram.getNotationIdentifier()). - getLocalIOController().saveProjectDiagram(projectDiagram, projectItemFile.getParent(), false); - - if(successSaveResult == NotationLocalIOController.SaveResult.SUCCESS){ - LOG.debug("Sync PN -> FS: Diagram " + projectItemFile.getAbsolutePath() + " has been overwritten."); - - } else { - publicOverwriteError(projectDiagram, projectItemFile); - } - - } else if(!projectItemFile.exists() && addProjectItems){ - successSaveResult = ModelerSession.getNotationService().getNotation(projectDiagram.getNotationIdentifier()). - getLocalIOController().saveProjectDiagram(projectDiagram, projectItemFile.getParent(), false); - - if(successSaveResult == NotationLocalIOController.SaveResult.SUCCESS){ - LOG.debug("Sync PN -> FS: Diagram " + projectItemFile.getAbsolutePath() + " has been saved."); - } else { - publicAddDiagramError(projectDiagram, projectItemFile); - } - } - - if(successSaveResult != NotationLocalIOController.SaveResult.SUCCESS){ - retValue = false; - } - - // user object is project root or a subfolder - } else if(userObject instanceof ProjectContainer){ - final Set synchronizedItems = new HashSet(); - - if(userObject instanceof ProjectRoot){ - //add project file (.pmp) to the list of synchronizedItems = do not delete it - synchronizedItems.add((((ProjectItem)userObject)).getDisplayName() + ProjectService.PROJECT_FILE_EXTENSION); - } - - for(int i = 0; i < lastTreePathNode.getChildCount(); i++){ - checkInterruption(); - - final DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) lastTreePathNode.getChildAt(i); - final ProjectItem projectItemOfChildNode = (ProjectItem) defaultMutableTreeNode.getUserObject(); - - final File projectItemFile; - if(projectItemOfChildNode instanceof ProjectContainer){ - // project containers are without file extension - projectItemFile = new File(fsLevel.getAbsolutePath(), projectItemOfChildNode.getDisplayName()); - } else if(projectItemOfChildNode instanceof ProjectDiagram){ - // project diagram files do have a file extension - final String fileExtension = ProjectServiceUtils.getNotationFileExtension(((ProjectDiagram) projectItemOfChildNode).getNotationIdentifier()); - projectItemFile = new File(fsLevel.getAbsolutePath(), projectItemOfChildNode.getDisplayName() + fileExtension); - } else { - LOG.error("A project item has to be either project container or project diagram."); - syncDialog.appendErrorInfo(INVALID_PARENT_ERROR_LABEL, true); - return false; - } - - if(projectItemFile.exists()){ - if(projectItemOfChildNode instanceof ProjectDiagram){ - retValue &= syncSubtreeToFS( - projectItemFile.getParentFile(), - treePath.pathByAddingChild(defaultMutableTreeNode), - addProjectItems, overwriteProjectItems, deleteProjectItems); - - } else { /* next child is container */ - retValue &= syncSubtreeToFS( - projectItemFile, - treePath.pathByAddingChild(defaultMutableTreeNode), - addProjectItems, overwriteProjectItems, deleteProjectItems); - } - - synchronizedItems.add(projectItemFile.getName()); - - } else if(!projectItemFile.exists() && addProjectItems){ - - /* next child is diagram */ - if(projectItemOfChildNode instanceof ProjectDiagram){ - - final String fileExtension = ProjectServiceUtils.getNotationFileExtension(((ProjectDiagram) projectItemOfChildNode).getNotationIdentifier()); - - retValue &= syncSubtreeToFS( - projectItemFile.getParentFile(), - treePath.pathByAddingChild(defaultMutableTreeNode), - addProjectItems, overwriteProjectItems, deleteProjectItems); - - synchronizedItems.add(projectItemOfChildNode.getDisplayName() + fileExtension); - - } else { /* next child is container */ - - if(projectItemFile.mkdir()){ //make new subfolder - LOG.debug("Sync PN -> FS: new subfolder has been created, " + projectItemFile.getAbsolutePath() + "."); - - retValue &= syncSubtreeToFS( - projectItemFile, - treePath.pathByAddingChild(defaultMutableTreeNode), - addProjectItems, overwriteProjectItems, deleteProjectItems); - - synchronizedItems.add(projectItemOfChildNode.getDisplayName()); - - } else { - publicMkdirError(projectItemFile); - } - } - } - } - - // delete non PN items in this fs level - if(deleteProjectItems){ - final String[] fsLevelItems = fsLevel.list(); - - for(final String fsItem : fsLevelItems){ - if(!synchronizedItems.contains(fsItem)){ //delete not PN item from FS - final File itemToDelete = new File(fsLevel.getAbsolutePath(), fsItem); - - if(ProjectServiceUtils.removeDirectory(itemToDelete)){ - LOG.debug("File system item has been deleted, " + itemToDelete.getAbsolutePath()); - - } else { - publicDeleteError(itemToDelete); - retValue = false; - } - } - } - } - } - - return retValue; - } - - /** - * done() method is invoked on the Event Dispatcher Thread when the doInBackground() method finishes - */ - @Override - protected void done() { - syncDialog.disableCancelButton(); - - syncDialog.updatePosition( - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.searching.done") - ); - - try { - if(!isCancelled()){ - syncDialog.syncComplete(!get()); - - return; - } - - } catch (InterruptedException e) { - LOG.error("The synchronization from the project navigation has been interrupted.", e); - } catch (ExecutionException e) { - LOG.error("There is no return value available.", e); - } - - syncDialog.syncComplete(true); - } - - /** - * Checks whether the task has not been canceled for example by the user. - * - * @throws InterruptedException when user cancels the synchronization - */ - private void checkInterruption() throws InterruptedException{ - if (Thread.interrupted()) { - throw new InterruptedException(); - } - } - - /** - * Publishes file system item overwrite error. - * - * @param projectDiagram is the diagram that is supposed to be overwritten - * - * @param projectItemFile is the file path to the existing file of diagram - */ - private void publicOverwriteError(final ProjectDiagram projectDiagram, final File projectItemFile){ - syncDialog.appendErrorInfo(DIAGRAM_LABEL + " " + projectDiagram.getDisplayName(), false); - syncDialog.appendErrorInfo(NOTATION_LABEL + " " + projectDiagram.getNotationIdentifier(), false); - syncDialog.appendErrorInfo(DIAGRAM_OVERWRITE_ERROR_LABEL, false); - syncDialog.appendErrorInfo(" >> " + projectItemFile.getAbsolutePath(), true); - LOG.error("Sync PN -> FS: Diagram " + projectItemFile.getAbsolutePath() + " was NOT possible to overwrite."); - } - - /** - * Publishes file system item write error. - * - * @param projectDiagram is the diagram that is supposed to be written - * - * @param projectItemFile is the file path to the not existing file of diagram - */ - private void publicAddDiagramError(final ProjectDiagram projectDiagram, final File projectItemFile){ - syncDialog.appendErrorInfo(DIAGRAM_LABEL + " " + projectDiagram.getDisplayName(), false); - syncDialog.appendErrorInfo(NOTATION_LABEL + " " + projectDiagram.getNotationIdentifier(), false); - syncDialog.appendErrorInfo(DIAGRAM_WRITE_ERROR_LABEL, false); - syncDialog.appendErrorInfo(" >> " + projectItemFile.getAbsolutePath(), true); - - LOG.error("Sync PN -> FS: Diagram " + projectItemFile.getAbsolutePath() + " has NOT been saved."); - } - - /** - * Publishes the make dir error. - * - * @param projectItemFile is the path to the dir - */ - private void publicMkdirError(final File projectItemFile) { - syncDialog.appendErrorInfo(MKDIR_ERROR_LABEL, false); - syncDialog.appendErrorInfo(" >> " +projectItemFile.getAbsolutePath(), true); - - LOG.error("Sync PN -> FS: Creating of a new subfolder has failed, " + projectItemFile.getAbsolutePath() + "."); - } - - /** - * Publishes a delete error. - * - * @param itemToDelete file system to be deleted - */ - private void publicDeleteError(final File itemToDelete) { - syncDialog.appendErrorInfo(DELETE_ERROR_LABEL, false); - syncDialog.appendErrorInfo(" >> " + itemToDelete.getAbsolutePath(), true) ; - - LOG.error("Sync PN -> FS: Deletion of a file system item has failed, " + itemToDelete.getAbsolutePath() + "."); - } - -} +package cz.cvut.promod.services.projectService.syncWorkers; + +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.ProjectService; +import cz.cvut.promod.services.projectService.results.SaveProjectResult; +import cz.cvut.promod.services.projectService.dialogs.SyncDialog; +import cz.cvut.promod.services.projectService.treeProjectNode.*; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.localIOController.NotationLocalIOController; + +import javax.swing.*; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; +import java.io.File; +import java.util.Set; +import java.util.HashSet; +import java.util.concurrent.ExecutionException; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:10:13, 13.11.2009 + */ + +/** + * Class that performs synchronization in a direction from project navigation tree to the file system. + * This class extends SwingWorker class, so the synchronization is performed asynchronously to the Event Dispatcher Thread. + * Process of synchronization is NOT thread safety. It is highly recommended to do NOT use this class directly, but use + * ModelerSession.getProjectControlService().synchronize(...) method instead. If you use this synchronize(...) method, + * you don't have to worry about concurrency issues, because this method shows a modal dialog displaying synchronization + * errors and makes the Event Dispatcher Thread wait for the result of the synchronize() method. So, it is not possible to + * invoke other methods on Event Dispatcher Thread during synchronization. + */ +public class SyncFromPNWorker extends SwingWorker { + + private final Logger LOG = Logger.getLogger(SyncFromPNWorker.class); + + private static final String IMPOSSIBLE_TO_SAVE_PROJECT_FILE_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.project.file.error"); + private static final String PROJECT_ROOT_NOT_FOUND_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.project.root.error"); + private static final String INVALID_TREE_PATH_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.invalid.treepath"); + private static final String MISSING_PROJECT_FILE_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.missing.project.file"); + private static final String SYNC_SUBTREE_BUILD_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.subtree.build.error"); + private static final String INVALID_PARENT_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.invalid.parent"); + private static final String DIAGRAM_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.error.diagram"); + private static final String NOTATION_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.error.identifier"); + private static final String DIAGRAM_OVERWRITE_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.overwritten"); + private static final String DIAGRAM_WRITE_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.diagram.write"); + private static final String MKDIR_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.mkdir.error"); + private static final String DELETE_ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.delete.error"); + + private final TreePath treePath; + + private final boolean addProjectItems; + private final boolean overwriteProjectItems; + private final boolean deleteProjectItems; + + private final SyncDialog syncDialog; + + public SyncFromPNWorker(final TreePath treePath, + final boolean addProjectItems, + final boolean overwriteProjectItems, + final boolean deleteProjectItems, + final SyncDialog syncDialog){ + + this.treePath = treePath; + + this.addProjectItems = addProjectItems; + this.overwriteProjectItems = overwriteProjectItems; + this.deleteProjectItems = deleteProjectItems; + + this.syncDialog = syncDialog; + } + + /** + * Prepares the synchronization process and starts the synchronization. + * + * @return true if there were no errors during synchronization process, false otherwise + * + * @throws Exception when something happened, synchronize(...) (see above) method deals with possible problems + */ + protected Boolean doInBackground() throws Exception { + showDialog(); + + // First goes the JTree main projects root (root node, invisible for users) and then a project root node. + if(!ProjectServiceUtils.isValidTreePath(treePath) || treePath.getPathCount() < 2){ + LOG.error("Invalid tree path."); + syncDialog.appendErrorInfo(INVALID_TREE_PATH_LABEL, true); + return false; + } + + final DefaultMutableTreeNode projectRootNode; + final ProjectRoot projectRoot; + try{ + projectRootNode = (DefaultMutableTreeNode) treePath.getPathComponent(1); + projectRoot = (ProjectRoot) projectRootNode.getUserObject(); + } catch (ClassCastException exception){ + // should never happened, because isValidTreePath() method ensures this; testing & debuging purposes + LOG.error("Project root not found."); + syncDialog.appendErrorInfo(PROJECT_ROOT_NOT_FOUND_LABEL, true); + return false; + } + + final File projectRootFile = + new File(projectRoot.getProjectLocation(), projectRoot.getDisplayName() + ProjectService.PROJECT_FILE_EXTENSION); + + if(projectRootFile.exists() && overwriteProjectItems && + /* overwrite project file only when the project root is set as tree path (constructor argument) */ + treePath.equals(ModelerSession.getProjectService().getProjectPath(projectRoot.getDisplayName()))){ + + final SaveProjectResult result = ModelerSession.getProjectControlService().saveProject(treePath); //overwrite the project file + if(!SaveProjectResult.SUCCESS.equals(result)){ + LOG.error("Not possible to save project file"); + syncDialog.appendErrorInfo(IMPOSSIBLE_TO_SAVE_PROJECT_FILE_LABEL, true); + return false; + } + + } else if(!projectRootFile.exists() && addProjectItems){ + final SaveProjectResult result = ModelerSession.getProjectControlService().saveProject(treePath); //create the project file + if(!SaveProjectResult.SUCCESS.equals(result)){ + LOG.error("Not possible to save project file"); + syncDialog.appendErrorInfo(IMPOSSIBLE_TO_SAVE_PROJECT_FILE_LABEL, true); + return false; + } + + } else if(!projectRootFile.exists()){ + LOG.error("Project file not found and synchronization is not allowed to add items to the file system."); + syncDialog.appendErrorInfo(MISSING_PROJECT_FILE_LABEL, true); + return false; + } + + final File path = syncPathToTreeRootToFS( + new File(projectRootFile.getParent()), + treePath, + addProjectItems + ); + + if (path == null){ + syncDialog.appendErrorInfo(SYNC_SUBTREE_BUILD_ERROR_LABEL, true); + return false; + } + + /* This is kind of hack to show, that there is no need to continue, + there are still differences between FS and PN, but the method is not allowed to create FS items. */ + return path.getAbsolutePath().equals("") || syncSubtreeToFS( + path, + treePath, + addProjectItems, overwriteProjectItems, deleteProjectItems); + + } + + /** + * Schedules JDialog#setVisible(true) invocation on the Event Dispatcher Thread. + */ + private void showDialog(){ + SwingUtilities.invokeLater(new Runnable(){ + public void run() { + syncDialog.setVisible(true); + } + }); + } + + /** + * Synchronize the file system structure before the subtree that is supposed to be synchronized. This structure to the + * subtree node is created if and only if the addProjectItems is true. Otherwise no items on the file system are created and + * the whole synchronization finishes successfully, even though that there is still differences between file system and + * project navigation. + * + * @param file is the project root directory + * + * @param treePath is the path to the project tree subtree which is supposed to be synchronized + * + * @param addProjectItems indicates whether new items are supposed to be created on the file system if they are missing + * + * @return the file system path related to the subtree chosen to synchronize, null if any error occurs or an instance + * of file class with empty path in it, if there are still differences but the method is not allowed to create items on the + * file system + * + * @throws InterruptedException user has canceled the synchronization + */ + private File syncPathToTreeRootToFS(final File file, + final TreePath treePath, + final boolean addProjectItems) throws InterruptedException{ + File path = file; + + for(int i = 1; i < treePath.getPathCount(); i++){ + checkInterruption(); + + final DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) treePath.getPathComponent(i); + final Object userObject = defaultMutableTreeNode.getUserObject(); + + // update sync dialog + if(userObject instanceof ProjectItem){ + syncDialog.updatePosition(((ProjectItem)userObject).getDisplayName()); + + } else { + // should never happened + LOG.error("All project items have to be instances of classes implementing ProjectItem interface."); + return null; + } + + if(userObject instanceof ProjectRoot){ + if(i > 1){ // should never happened + return null; + } + + } else if(userObject instanceof ProjectDiagram){ + if(i < 2){ // should never happened + return null; + } + + if(defaultMutableTreeNode == treePath.getLastPathComponent()){ + return path; + } else { + return null; // diagram cannot have any children in the tree path + } + + } else if(userObject instanceof ProjectSubFolder){ + if(i < 2){ // should never happened + return null; + } + + final ProjectItem projectItem = (ProjectItem) userObject; + final File subfolder = new File(path.getAbsolutePath(), projectItem.getDisplayName()); + + if(!subfolder.exists()){ + + if(addProjectItems){ + if(subfolder.mkdir()){ + LOG.debug("Sync PN -> FS: new subfolder has been created, " + subfolder.getAbsolutePath() + "."); + } else { + LOG.error("Sync PN -> FS: Creating of a new subfolder has failed failed, " + subfolder.getAbsolutePath() + "."); + return null; + } + } else { // there are differences between PN and FS, but synchronize method is not invoked with addProjectItems flag + return new File(""); + } + } + + path = new File(subfolder.getAbsolutePath()); + + } else { + // should never happened + LOG.error("Project node has to be an instance of ProjectRoot, ProjectSubFolder or Project Diagram class."); + } + } + + return path; + } + + /** + * Synchronize the selected project subtree to the file system. This methods requires the correct starting level + * on the file system with respect to the project subtree to exist. + * + * Important to note that this method synchronize only the SUBTREE 'under' the last tree node in the treePath variable. + * + * @param fsLevel is the starting point for the synchronization on the file system + * @param treePath is the starting point in the project structure for the synchronization + * @param addProjectItems indicates whether new items are supposed to be created on the file system if they are missing + * @param overwriteProjectItems indicates whether diagrams that already exists on the file system are supposed to be overwritten + * @param deleteProjectItems indicates whether not projects items (files or diagrams) are supposed to be deleted from file system + * + * @return true if and only if no error occurs, false otherwise + * + * @throws InterruptedException when user cancels the synchronization + */ + private boolean syncSubtreeToFS(final File fsLevel, + final TreePath treePath, + final boolean addProjectItems, + final boolean overwriteProjectItems, + final boolean deleteProjectItems) throws InterruptedException{ + + checkInterruption(); + + boolean retValue = true; + + final DefaultMutableTreeNode lastTreePathNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + final Object userObject = lastTreePathNode.getUserObject(); + final ProjectItem projectItem; + + projectItem = (ProjectItem) userObject; + + // sync a project diagram + if(userObject instanceof ProjectDiagram){ + final ProjectDiagram projectDiagram = (ProjectDiagram) userObject; + final String fileExtension = ProjectServiceUtils.getNotationFileExtension(projectDiagram.getNotationIdentifier()); + + final File projectItemFile = new File(fsLevel.getAbsolutePath(), projectItem.getDisplayName() + fileExtension); + + NotationLocalIOController.SaveResult successSaveResult = NotationLocalIOController.SaveResult.SUCCESS; + + if(projectItemFile.exists() && overwriteProjectItems){ + successSaveResult = ModelerSession.getNotationService().getNotation(projectDiagram.getNotationIdentifier()). + getLocalIOController().saveProjectDiagram(projectDiagram, projectItemFile.getParent(), false); + + if(successSaveResult == NotationLocalIOController.SaveResult.SUCCESS){ + LOG.debug("Sync PN -> FS: Diagram " + projectItemFile.getAbsolutePath() + " has been overwritten."); + + } else { + publicOverwriteError(projectDiagram, projectItemFile); + } + + } else if(!projectItemFile.exists() && addProjectItems){ + successSaveResult = ModelerSession.getNotationService().getNotation(projectDiagram.getNotationIdentifier()). + getLocalIOController().saveProjectDiagram(projectDiagram, projectItemFile.getParent(), false); + + if(successSaveResult == NotationLocalIOController.SaveResult.SUCCESS){ + LOG.debug("Sync PN -> FS: Diagram " + projectItemFile.getAbsolutePath() + " has been saved."); + } else { + publicAddDiagramError(projectDiagram, projectItemFile); + } + } + + if(successSaveResult != NotationLocalIOController.SaveResult.SUCCESS){ + retValue = false; + } + + // user object is project root or a subfolder + } else if(userObject instanceof ProjectContainer){ + final Set synchronizedItems = new HashSet(); + + if(userObject instanceof ProjectRoot){ + //add project file (.pmp) to the list of synchronizedItems = do not delete it + synchronizedItems.add((((ProjectItem)userObject)).getDisplayName() + ProjectService.PROJECT_FILE_EXTENSION); + } + + for(int i = 0; i < lastTreePathNode.getChildCount(); i++){ + checkInterruption(); + + final DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) lastTreePathNode.getChildAt(i); + final ProjectItem projectItemOfChildNode = (ProjectItem) defaultMutableTreeNode.getUserObject(); + + final File projectItemFile; + if(projectItemOfChildNode instanceof ProjectContainer){ + // project containers are without file extension + projectItemFile = new File(fsLevel.getAbsolutePath(), projectItemOfChildNode.getDisplayName()); + } else if(projectItemOfChildNode instanceof ProjectDiagram){ + // project diagram files do have a file extension + final String fileExtension = ProjectServiceUtils.getNotationFileExtension(((ProjectDiagram) projectItemOfChildNode).getNotationIdentifier()); + projectItemFile = new File(fsLevel.getAbsolutePath(), projectItemOfChildNode.getDisplayName() + fileExtension); + } else { + LOG.error("A project item has to be either project container or project diagram."); + syncDialog.appendErrorInfo(INVALID_PARENT_ERROR_LABEL, true); + return false; + } + + if(projectItemFile.exists()){ + if(projectItemOfChildNode instanceof ProjectDiagram){ + retValue &= syncSubtreeToFS( + projectItemFile.getParentFile(), + treePath.pathByAddingChild(defaultMutableTreeNode), + addProjectItems, overwriteProjectItems, deleteProjectItems); + + } else { /* next child is container */ + retValue &= syncSubtreeToFS( + projectItemFile, + treePath.pathByAddingChild(defaultMutableTreeNode), + addProjectItems, overwriteProjectItems, deleteProjectItems); + } + + synchronizedItems.add(projectItemFile.getName()); + + } else if(!projectItemFile.exists() && addProjectItems){ + + /* next child is diagram */ + if(projectItemOfChildNode instanceof ProjectDiagram){ + + final String fileExtension = ProjectServiceUtils.getNotationFileExtension(((ProjectDiagram) projectItemOfChildNode).getNotationIdentifier()); + + retValue &= syncSubtreeToFS( + projectItemFile.getParentFile(), + treePath.pathByAddingChild(defaultMutableTreeNode), + addProjectItems, overwriteProjectItems, deleteProjectItems); + + synchronizedItems.add(projectItemOfChildNode.getDisplayName() + fileExtension); + + } else { /* next child is container */ + + if(projectItemFile.mkdir()){ //make new subfolder + LOG.debug("Sync PN -> FS: new subfolder has been created, " + projectItemFile.getAbsolutePath() + "."); + + retValue &= syncSubtreeToFS( + projectItemFile, + treePath.pathByAddingChild(defaultMutableTreeNode), + addProjectItems, overwriteProjectItems, deleteProjectItems); + + synchronizedItems.add(projectItemOfChildNode.getDisplayName()); + + } else { + publicMkdirError(projectItemFile); + } + } + } + } + + // delete non PN items in this fs level + if(deleteProjectItems){ + final String[] fsLevelItems = fsLevel.list(); + + for(final String fsItem : fsLevelItems){ + if(!synchronizedItems.contains(fsItem)){ //delete not PN item from FS + final File itemToDelete = new File(fsLevel.getAbsolutePath(), fsItem); + + if(ProjectServiceUtils.removeDirectory(itemToDelete)){ + LOG.debug("File system item has been deleted, " + itemToDelete.getAbsolutePath()); + + } else { + publicDeleteError(itemToDelete); + retValue = false; + } + } + } + } + } + + return retValue; + } + + /** + * done() method is invoked on the Event Dispatcher Thread when the doInBackground() method finishes + */ + @Override + protected void done() { + syncDialog.disableCancelButton(); + + syncDialog.updatePosition( + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.searching.done") + ); + + try { + if(!isCancelled()){ + syncDialog.syncComplete(!get()); + + return; + } + + } catch (InterruptedException e) { + LOG.error("The synchronization from the project navigation has been interrupted.", e); + } catch (ExecutionException e) { + LOG.error("There is no return value available.", e); + } + + syncDialog.syncComplete(true); + } + + /** + * Checks whether the task has not been canceled for example by the user. + * + * @throws InterruptedException when user cancels the synchronization + */ + private void checkInterruption() throws InterruptedException{ + if (Thread.interrupted()) { + throw new InterruptedException(); + } + } + + /** + * Publishes file system item overwrite error. + * + * @param projectDiagram is the diagram that is supposed to be overwritten + * + * @param projectItemFile is the file path to the existing file of diagram + */ + private void publicOverwriteError(final ProjectDiagram projectDiagram, final File projectItemFile){ + syncDialog.appendErrorInfo(DIAGRAM_LABEL + " " + projectDiagram.getDisplayName(), false); + syncDialog.appendErrorInfo(NOTATION_LABEL + " " + projectDiagram.getNotationIdentifier(), false); + syncDialog.appendErrorInfo(DIAGRAM_OVERWRITE_ERROR_LABEL, false); + syncDialog.appendErrorInfo(" >> " + projectItemFile.getAbsolutePath(), true); + LOG.error("Sync PN -> FS: Diagram " + projectItemFile.getAbsolutePath() + " was NOT possible to overwrite."); + } + + /** + * Publishes file system item write error. + * + * @param projectDiagram is the diagram that is supposed to be written + * + * @param projectItemFile is the file path to the not existing file of diagram + */ + private void publicAddDiagramError(final ProjectDiagram projectDiagram, final File projectItemFile){ + syncDialog.appendErrorInfo(DIAGRAM_LABEL + " " + projectDiagram.getDisplayName(), false); + syncDialog.appendErrorInfo(NOTATION_LABEL + " " + projectDiagram.getNotationIdentifier(), false); + syncDialog.appendErrorInfo(DIAGRAM_WRITE_ERROR_LABEL, false); + syncDialog.appendErrorInfo(" >> " + projectItemFile.getAbsolutePath(), true); + + LOG.error("Sync PN -> FS: Diagram " + projectItemFile.getAbsolutePath() + " has NOT been saved."); + } + + /** + * Publishes the make dir error. + * + * @param projectItemFile is the path to the dir + */ + private void publicMkdirError(final File projectItemFile) { + syncDialog.appendErrorInfo(MKDIR_ERROR_LABEL, false); + syncDialog.appendErrorInfo(" >> " +projectItemFile.getAbsolutePath(), true); + + LOG.error("Sync PN -> FS: Creating of a new subfolder has failed, " + projectItemFile.getAbsolutePath() + "."); + } + + /** + * Publishes a delete error. + * + * @param itemToDelete file system to be deleted + */ + private void publicDeleteError(final File itemToDelete) { + syncDialog.appendErrorInfo(DELETE_ERROR_LABEL, false); + syncDialog.appendErrorInfo(" >> " + itemToDelete.getAbsolutePath(), true) ; + + LOG.error("Sync PN -> FS: Deletion of a file system item has failed, " + itemToDelete.getAbsolutePath() + "."); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncWorkersUtils.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncWorkersUtils.java index fb8225a..37bfaa3 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncWorkersUtils.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/syncWorkers/SyncWorkersUtils.java @@ -1,127 +1,127 @@ -package cz.cvut.promod.services.projectService.syncWorkers; - -import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; -import cz.cvut.promod.services.projectService.results.AddProjectItemStatus; -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectItem; -import cz.cvut.promod.services.projectService.dialogs.SyncDialog; -import cz.cvut.promod.services.ModelerSession; - -import javax.swing.tree.TreePath; -import javax.swing.tree.DefaultMutableTreeNode; -import java.io.File; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 0:37:58, 14.11.2009 - */ - -/** - * Sync util class. - */ -public class SyncWorkersUtils { - - private static final Logger LOG = Logger.getLogger(SyncWorkersUtils.class); - - private static final String TREEPATH_ELEMENTS_DELIMITER = " -> "; - - private static final String TO_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.default.error.to"); - private static final String FROM_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.default.error.from"); - private static final String ERROR_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.default.error.message"); - private static final String INVALID_NAME_LABEL = - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.invalidname.error.message"); - - /** - * Report the sync error. - * - * @param addProjectItemStatus diagram/error status - * @param fsSubtreeLocation FS location of the item - * @param treePath location in the project navigation tree - * @param toFS if true, the sync is from PN to FS, false in other way - * @return error message - */ - public static String reportDiagramError(final AddProjectItemStatus addProjectItemStatus, - final File fsSubtreeLocation, - final TreePath treePath, - final boolean toFS) { - String message = ""; - - final String to; - final String from; - - if(toFS){ - from = getMessageString(treePath); - to = getMessageString(fsSubtreeLocation); - } else { - from = getMessageString(fsSubtreeLocation); - to = getMessageString(treePath); - } - - switch (addProjectItemStatus){ - case SUCCESS: - break; - case INVALID_NAME: - message = INVALID_NAME_LABEL; - message += " " + ProjectServiceUtils.getDisallowedNameSymbols(','); - break; - default: - message = ERROR_LABEL; - - } - - message += SyncDialog.NEW_LINE_MARK + - " >> " + FROM_LABEL + " " + - from + - SyncDialog.NEW_LINE_MARK + - " >> " + TO_LABEL + " " + - to; - - return message; - } - - /** - * @param file is a file on FS - * @return the full file name - */ - public static String getMessageString(final File file){ - return file.getAbsolutePath(); - } - - /** - * @param treePath is location of a item in the project navigation - * @return error message of the item - */ - public static String getMessageString(final TreePath treePath){ - StringBuffer locationBuffer = new StringBuffer(); - - final int itemNumber = treePath.getPathCount() - 1; - - for(int i = 1; i <= itemNumber; i++){ - - try{ - ProjectItem projectItem = (ProjectItem) ((DefaultMutableTreeNode) treePath.getPathComponent(i)).getUserObject(); - - locationBuffer.append(projectItem.getDisplayName()); - - if(i != itemNumber){ - locationBuffer.append(TREEPATH_ELEMENTS_DELIMITER); - } - - } catch (Exception exception){ - LOG.error("Illegal node in project tree."); - locationBuffer = new StringBuffer( - ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.treepatherror")); - - break; - } - } - - return locationBuffer.toString(); - } - +package cz.cvut.promod.services.projectService.syncWorkers; + +import cz.cvut.promod.services.projectService.utils.ProjectServiceUtils; +import cz.cvut.promod.services.projectService.results.AddProjectItemStatus; +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectItem; +import cz.cvut.promod.services.projectService.dialogs.SyncDialog; +import cz.cvut.promod.services.ModelerSession; + +import javax.swing.tree.TreePath; +import javax.swing.tree.DefaultMutableTreeNode; +import java.io.File; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 0:37:58, 14.11.2009 + */ + +/** + * Sync util class. + */ +public class SyncWorkersUtils { + + private static final Logger LOG = Logger.getLogger(SyncWorkersUtils.class); + + private static final String TREEPATH_ELEMENTS_DELIMITER = " -> "; + + private static final String TO_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.default.error.to"); + private static final String FROM_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.default.error.from"); + private static final String ERROR_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.default.error.message"); + private static final String INVALID_NAME_LABEL = + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.invalidname.error.message"); + + /** + * Report the sync error. + * + * @param addProjectItemStatus diagram/error status + * @param fsSubtreeLocation FS location of the item + * @param treePath location in the project navigation tree + * @param toFS if true, the sync is from PN to FS, false in other way + * @return error message + */ + public static String reportDiagramError(final AddProjectItemStatus addProjectItemStatus, + final File fsSubtreeLocation, + final TreePath treePath, + final boolean toFS) { + String message = ""; + + final String to; + final String from; + + if(toFS){ + from = getMessageString(treePath); + to = getMessageString(fsSubtreeLocation); + } else { + from = getMessageString(fsSubtreeLocation); + to = getMessageString(treePath); + } + + switch (addProjectItemStatus){ + case SUCCESS: + break; + case INVALID_NAME: + message = INVALID_NAME_LABEL; + message += " " + ProjectServiceUtils.getDisallowedNameSymbols(','); + break; + default: + message = ERROR_LABEL; + + } + + message += SyncDialog.NEW_LINE_MARK + + " >> " + FROM_LABEL + " " + + from + + SyncDialog.NEW_LINE_MARK + + " >> " + TO_LABEL + " " + + to; + + return message; + } + + /** + * @param file is a file on FS + * @return the full file name + */ + public static String getMessageString(final File file){ + return file.getAbsolutePath(); + } + + /** + * @param treePath is location of a item in the project navigation + * @return error message of the item + */ + public static String getMessageString(final TreePath treePath){ + StringBuffer locationBuffer = new StringBuffer(); + + final int itemNumber = treePath.getPathCount() - 1; + + for(int i = 1; i <= itemNumber; i++){ + + try{ + ProjectItem projectItem = (ProjectItem) ((DefaultMutableTreeNode) treePath.getPathComponent(i)).getUserObject(); + + locationBuffer.append(projectItem.getDisplayName()); + + if(i != itemNumber){ + locationBuffer.append(TREEPATH_ELEMENTS_DELIMITER); + } + + } catch (Exception exception){ + LOG.error("Illegal node in project tree."); + locationBuffer = new StringBuffer( + ModelerSession.getCommonResourceBundle().getString("project.service.sync.dialog.treepatherror")); + + break; + } + } + + return locationBuffer.toString(); + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/IdentifiableProjectItem.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/IdentifiableProjectItem.java index 6e7caf9..a0494be 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/IdentifiableProjectItem.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/IdentifiableProjectItem.java @@ -1,21 +1,21 @@ -package cz.cvut.promod.services.projectService.treeProjectNode; - -import java.util.UUID; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:11:41, 1.11.2009 - */ - -/** - * Common interface for identifiable project items. - */ -public interface IdentifiableProjectItem extends ProjectItem{ - - /** - * @return the project item identifier - */ - public UUID getUuid(); - -} +package cz.cvut.promod.services.projectService.treeProjectNode; + +import java.util.UUID; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:11:41, 1.11.2009 + */ + +/** + * Common interface for identifiable project items. + */ +public interface IdentifiableProjectItem extends ProjectItem{ + + /** + * @return the project item identifier + */ + public UUID getUuid(); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectContainer.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectContainer.java index 7dad487..17b1f35 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectContainer.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectContainer.java @@ -1,13 +1,13 @@ -package cz.cvut.promod.services.projectService.treeProjectNode; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:42:39, 23.10.2009 - */ - -/** - * Common interface for project containers - ProjectRoot and ProjectSubFolder - */ -public interface ProjectContainer extends ProjectItem { -} +package cz.cvut.promod.services.projectService.treeProjectNode; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:42:39, 23.10.2009 + */ + +/** + * Common interface for project containers - ProjectRoot and ProjectSubFolder + */ +public interface ProjectContainer extends ProjectItem { +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectDiagram.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectDiagram.java index b155fb1..732b53a 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectDiagram.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectDiagram.java @@ -1,168 +1,168 @@ -package cz.cvut.promod.services.projectService.treeProjectNode; - -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModel; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModelChangeListener; -import cz.cvut.promod.services.projectService.treeProjectNode.listener.ProjectDiagramListener; - -import java.util.UUID; -import java.util.Set; -import java.util.HashSet; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 21:03:10, 13.10.2009 - */ - -/** - * Represents an item in the project tree navigation. - * This class is final. So no plugin is allowed to implement any subclasses of this class. In case of need, plugins - * can extend ProjectModel class and store it's specific data there. - */ -public final class ProjectDiagram implements IdentifiableProjectItem, DiagramModelChangeListener{ - - private final UUID uuid; - - /** display name is supposed to match with file name (without extension) */ - private transient String displayName; - - // serialize, but just for pertinent error handling - final String notationIdentifier; - - /** Indicates whether the model has been changes since last save */ - private transient boolean changed = false; - - private transient final Set listeners; - - final DiagramModel diagramModel; - - - public ProjectDiagram(final String displayName, - final String notationIdentifier, - final UUID uuid, - final DiagramModel diagramModel) { - - this.uuid = uuid; - this.notationIdentifier = notationIdentifier; - this.diagramModel = diagramModel; - - /** register itself to listen changes in it's diagram model */ - if(diagramModel != null){ - diagramModel.addChangeListener(this); - } - - changed = false; - - listeners = new HashSet(); - - setDisplayName(displayName); - } - - /** - * @return the diagrams notation identifier - */ - public String getNotationIdentifier() { - return notationIdentifier; - } - - /** {@inheritDoc} */ - public void setDisplayName(final String displayName) { - final String oldName = this.displayName; - this.displayName = displayName; - - publishChange(ProjectDiagramChange.ChangeType.DISPLAY_NAME, displayName, oldName); - } - - /** {@inheritDoc} */ - public String getDisplayName() { - return displayName; - } - - public UUID getUuid() { - return uuid; - } - - /** - * @return diagrams model - */ - public DiagramModel getDiagramModel() { - return diagramModel; - } - - @Override - public String toString(){ - return getDisplayName(); - } - - /** - * @return the value of change flag - */ - public boolean isChanged() { - return changed; - } - - /** - * set the change flag to false = unchanged. - */ - public void reset() { - final boolean oldChanged = changed; - changed = false; - - publishChange(ProjectDiagramChange.ChangeType.CHANGE_FLAG, false, oldChanged); - } - - public void changePerformed(final Object change) { - final boolean oldChanged = changed; - - changed = true; - - publishChange(ProjectDiagramChange.ChangeType.DIAGRAM_MODEL, change, oldChanged); - } - - /** - * Registers a new change listener. - * - * @param listener is a listener that listens changes in ProjectDiagram. - */ - public void addChangeListener(final ProjectDiagramListener listener){ - listeners.add(listener); - } - - /** - * Removes the change listener. - * - * @param listener is the listener to be removed - */ - public void removeChangeListener(final ProjectDiagramListener listener){ - listeners.remove(listener); - } - - /** - * Publishes the change that has occurred. - * - * @param changeType is the type of the change - * @param changeValue is optional change info about the change - */ - public void publishChange(final ProjectDiagramChange.ChangeType changeType, final Object changeValue){ - final ProjectDiagramChange change = new ProjectDiagramChange(this, changeType, changeValue, null); - - for(final ProjectDiagramListener listener : listeners){ - listener.changePerformed(change); - } - } - - /** - * Publishes the change that has occurred. - * - * @param changeType is the type of the change - * @param changeValue is optional change info about the change - * @param oldValue is the old value before the change - */ - public void publishChange(final ProjectDiagramChange.ChangeType changeType, final Object changeValue, final Object oldValue){ - final ProjectDiagramChange change = new ProjectDiagramChange(this, changeType, changeValue, oldValue); - - for(final ProjectDiagramListener listener : listeners){ - listener.changePerformed(change); - } - } -} +package cz.cvut.promod.services.projectService.treeProjectNode; + +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModel; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.model.DiagramModelChangeListener; +import cz.cvut.promod.services.projectService.treeProjectNode.listener.ProjectDiagramListener; + +import java.util.UUID; +import java.util.Set; +import java.util.HashSet; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 21:03:10, 13.10.2009 + */ + +/** + * Represents an item in the project tree navigation. + * This class is final. So no plugin is allowed to implement any subclasses of this class. In case of need, plugins + * can extend ProjectModel class and store it's specific data there. + */ +public final class ProjectDiagram implements IdentifiableProjectItem, DiagramModelChangeListener{ + + private final UUID uuid; + + /** display name is supposed to match with file name (without extension) */ + private transient String displayName; + + // serialize, but just for pertinent error handling + final String notationIdentifier; + + /** Indicates whether the model has been changes since last save */ + private transient boolean changed = false; + + private transient final Set listeners; + + final DiagramModel diagramModel; + + + public ProjectDiagram(final String displayName, + final String notationIdentifier, + final UUID uuid, + final DiagramModel diagramModel) { + + this.uuid = uuid; + this.notationIdentifier = notationIdentifier; + this.diagramModel = diagramModel; + + /** register itself to listen changes in it's diagram model */ + if(diagramModel != null){ + diagramModel.addChangeListener(this); + } + + changed = false; + + listeners = new HashSet(); + + setDisplayName(displayName); + } + + /** + * @return the diagrams notation identifier + */ + public String getNotationIdentifier() { + return notationIdentifier; + } + + /** {@inheritDoc} */ + public void setDisplayName(final String displayName) { + final String oldName = this.displayName; + this.displayName = displayName; + + publishChange(ProjectDiagramChange.ChangeType.DISPLAY_NAME, displayName, oldName); + } + + /** {@inheritDoc} */ + public String getDisplayName() { + return displayName; + } + + public UUID getUuid() { + return uuid; + } + + /** + * @return diagrams model + */ + public DiagramModel getDiagramModel() { + return diagramModel; + } + + @Override + public String toString(){ + return getDisplayName(); + } + + /** + * @return the value of change flag + */ + public boolean isChanged() { + return changed; + } + + /** + * set the change flag to false = unchanged. + */ + public void reset() { + final boolean oldChanged = changed; + changed = false; + + publishChange(ProjectDiagramChange.ChangeType.CHANGE_FLAG, false, oldChanged); + } + + public void changePerformed(final Object change) { + final boolean oldChanged = changed; + + changed = true; + + publishChange(ProjectDiagramChange.ChangeType.DIAGRAM_MODEL, change, oldChanged); + } + + /** + * Registers a new change listener. + * + * @param listener is a listener that listens changes in ProjectDiagram. + */ + public void addChangeListener(final ProjectDiagramListener listener){ + listeners.add(listener); + } + + /** + * Removes the change listener. + * + * @param listener is the listener to be removed + */ + public void removeChangeListener(final ProjectDiagramListener listener){ + listeners.remove(listener); + } + + /** + * Publishes the change that has occurred. + * + * @param changeType is the type of the change + * @param changeValue is optional change info about the change + */ + public void publishChange(final ProjectDiagramChange.ChangeType changeType, final Object changeValue){ + final ProjectDiagramChange change = new ProjectDiagramChange(this, changeType, changeValue, null); + + for(final ProjectDiagramListener listener : listeners){ + listener.changePerformed(change); + } + } + + /** + * Publishes the change that has occurred. + * + * @param changeType is the type of the change + * @param changeValue is optional change info about the change + * @param oldValue is the old value before the change + */ + public void publishChange(final ProjectDiagramChange.ChangeType changeType, final Object changeValue, final Object oldValue){ + final ProjectDiagramChange change = new ProjectDiagramChange(this, changeType, changeValue, oldValue); + + for(final ProjectDiagramListener listener : listeners){ + listener.changePerformed(change); + } + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectDiagramChange.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectDiagramChange.java index 945c9fb..21b0e18 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectDiagramChange.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectDiagramChange.java @@ -1,117 +1,117 @@ -package cz.cvut.promod.services.projectService.treeProjectNode; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 8:31:21, 18.1.2010 - */ - -/** - * ProjectDiagramChange class contains detail information about change that occurred in an instance of - * ProjectDiagram class. - */ -public class ProjectDiagramChange { - - /** - * Standard project diagram change types. - */ - public static enum ChangeType { - /** - * The displayed name has changes. - */ - DISPLAY_NAME, - - /** - * The project diagram change flag has changed. - */ - CHANGE_FLAG, - - /** - * Diagram model od project diagram has changed. - */ - DIAGRAM_MODEL, - - /** - * Project diagram has been removed from the project navigation tree. - */ - REMOVED_FROM_NAVIGATION, - - /** - * When the project diagram object in the project navigation tree has been replaced bt another - * project diagram object. When is event is dispatched by the ProjectControlService, the project - * diagram variable is the new object and the changeValue holds the old object of project diagram. - */ - PROJECT_DIAGRAM_REPLACED, - - /** - * Special purposes. - */ - UNDEFINED - } - - private final ChangeType changeType; - - /** Any object holding detail info about the particular change */ - private final Object changeValue; - - /** Any object holding detail info about the particular change */ - private final Object oldValue; - - /** source diagram */ - private final ProjectDiagram projectDiagram; - - /** - * Instantiate new ProjectDiagramChange object. - * - * @param projectDiagram project diagram that has changed - * @param changeType is the change type - * @param changeValue change payload, detail information - */ - public ProjectDiagramChange(final ProjectDiagram projectDiagram, - final ChangeType changeType, - final Object changeValue, - final Object oldValue){ - this.changeType = changeType; - this.changeValue = changeValue; - this.projectDiagram = projectDiagram; - this.oldValue = oldValue; - } - - /** - * Instantiate new ProjectDiagramChange object. - * - * @param projectDiagram project diagram that has changed - * @param changeType is the change type - */ - public ProjectDiagramChange(final ProjectDiagram projectDiagram, final ChangeType changeType){ - this(projectDiagram, changeType, null, null); - } - - /** - * @return returns the changed project diagram - */ - public ProjectDiagram getProjectDiagram() { - return projectDiagram; - } - - /** - * @return the old value, the value before change - */ - public Object getOldValue() { - return oldValue; - } - - /** - * @return the change type - */ - public ChangeType getChangeType() { - return changeType; - } - - /** - * @return the change payload - */ - public Object getChangeValue() { - return changeValue; - } -} +package cz.cvut.promod.services.projectService.treeProjectNode; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 8:31:21, 18.1.2010 + */ + +/** + * ProjectDiagramChange class contains detail information about change that occurred in an instance of + * ProjectDiagram class. + */ +public class ProjectDiagramChange { + + /** + * Standard project diagram change types. + */ + public static enum ChangeType { + /** + * The displayed name has changes. + */ + DISPLAY_NAME, + + /** + * The project diagram change flag has changed. + */ + CHANGE_FLAG, + + /** + * Diagram model od project diagram has changed. + */ + DIAGRAM_MODEL, + + /** + * Project diagram has been removed from the project navigation tree. + */ + REMOVED_FROM_NAVIGATION, + + /** + * When the project diagram object in the project navigation tree has been replaced bt another + * project diagram object. When is event is dispatched by the ProjectControlService, the project + * diagram variable is the new object and the changeValue holds the old object of project diagram. + */ + PROJECT_DIAGRAM_REPLACED, + + /** + * Special purposes. + */ + UNDEFINED + } + + private final ChangeType changeType; + + /** Any object holding detail info about the particular change */ + private final Object changeValue; + + /** Any object holding detail info about the particular change */ + private final Object oldValue; + + /** source diagram */ + private final ProjectDiagram projectDiagram; + + /** + * Instantiate new ProjectDiagramChange object. + * + * @param projectDiagram project diagram that has changed + * @param changeType is the change type + * @param changeValue change payload, detail information + */ + public ProjectDiagramChange(final ProjectDiagram projectDiagram, + final ChangeType changeType, + final Object changeValue, + final Object oldValue){ + this.changeType = changeType; + this.changeValue = changeValue; + this.projectDiagram = projectDiagram; + this.oldValue = oldValue; + } + + /** + * Instantiate new ProjectDiagramChange object. + * + * @param projectDiagram project diagram that has changed + * @param changeType is the change type + */ + public ProjectDiagramChange(final ProjectDiagram projectDiagram, final ChangeType changeType){ + this(projectDiagram, changeType, null, null); + } + + /** + * @return returns the changed project diagram + */ + public ProjectDiagram getProjectDiagram() { + return projectDiagram; + } + + /** + * @return the old value, the value before change + */ + public Object getOldValue() { + return oldValue; + } + + /** + * @return the change type + */ + public ChangeType getChangeType() { + return changeType; + } + + /** + * @return the change payload + */ + public Object getChangeValue() { + return changeValue; + } +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectItem.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectItem.java index 9e7099e..1d28212 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectItem.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectItem.java @@ -1,30 +1,30 @@ -package cz.cvut.promod.services.projectService.treeProjectNode; - -import com.jgoodies.binding.value.ValueModel; - -import javax.swing.tree.DefaultMutableTreeNode; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 20:44:48, 13.10.2009 - */ - -/** - * Common interface for project items. - */ -public interface ProjectItem{ - - /** - * @return the display name of the project item - */ - public String getDisplayName(); - - /** - * Sets the project item display name. - * - * @param displayName new display name - */ - public void setDisplayName(final String displayName); - -} +package cz.cvut.promod.services.projectService.treeProjectNode; + +import com.jgoodies.binding.value.ValueModel; + +import javax.swing.tree.DefaultMutableTreeNode; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 20:44:48, 13.10.2009 + */ + +/** + * Common interface for project items. + */ +public interface ProjectItem{ + + /** + * @return the display name of the project item + */ + public String getDisplayName(); + + /** + * Sets the project item display name. + * + * @param displayName new display name + */ + public void setDisplayName(final String displayName); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectRoot.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectRoot.java index 1d4ba92..27926b7 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectRoot.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectRoot.java @@ -1,81 +1,81 @@ -package cz.cvut.promod.services.projectService.treeProjectNode; - -import cz.cvut.promod.services.projectService.ProjectService; - -import java.io.File; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 21:02:45, 13.10.2009 - */ - -/** - * Represents the project root object. - */ -public final class ProjectRoot implements ProjectContainer { - - private String displayName; - - /* location of the project file (having ProjectService.PROJECT_FILE_EXTENSION_NAME extension) is not taken into - account during saving the project root */ - transient private String projectLocation; - - - /** - * Constructs a new instance of ProjectRoot class. - * - * @param displayName is the project name (will be trimmed) - * @param projectLocation is the project location on the file system (will be trimmed) - */ - public ProjectRoot(final String displayName, final String projectLocation){ - if(displayName != null){ - this.displayName = displayName.trim(); - } - - if(projectLocation != null){ - this.projectLocation = projectLocation.trim(); - } - } - - /** {@inheritDoc} */ - public void setDisplayName(final String displayName) { - this.displayName = displayName.trim(); - } - - /** {@inheritDoc} */ - public String getDisplayName() { - return displayName; - } - - /** - * @return the project file system location - */ - public String getProjectLocation() { - return projectLocation; - } - - /** - * Sets the file system location - * - * @param projectLocation is the new project file system location - */ - public void setProjectLocation(final String projectLocation) { - this.projectLocation = projectLocation.trim(); - } - - /** - * Returns the project file. - * - * @return the project file - */ - public File getProjectFile(){ - return new File(getProjectLocation(), getDisplayName() + ProjectService.PROJECT_FILE_EXTENSION); - } - - @Override - public String toString(){ - return getDisplayName(); - } - +package cz.cvut.promod.services.projectService.treeProjectNode; + +import cz.cvut.promod.services.projectService.ProjectService; + +import java.io.File; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 21:02:45, 13.10.2009 + */ + +/** + * Represents the project root object. + */ +public final class ProjectRoot implements ProjectContainer { + + private String displayName; + + /* location of the project file (having ProjectService.PROJECT_FILE_EXTENSION_NAME extension) is not taken into + account during saving the project root */ + transient private String projectLocation; + + + /** + * Constructs a new instance of ProjectRoot class. + * + * @param displayName is the project name (will be trimmed) + * @param projectLocation is the project location on the file system (will be trimmed) + */ + public ProjectRoot(final String displayName, final String projectLocation){ + if(displayName != null){ + this.displayName = displayName.trim(); + } + + if(projectLocation != null){ + this.projectLocation = projectLocation.trim(); + } + } + + /** {@inheritDoc} */ + public void setDisplayName(final String displayName) { + this.displayName = displayName.trim(); + } + + /** {@inheritDoc} */ + public String getDisplayName() { + return displayName; + } + + /** + * @return the project file system location + */ + public String getProjectLocation() { + return projectLocation; + } + + /** + * Sets the file system location + * + * @param projectLocation is the new project file system location + */ + public void setProjectLocation(final String projectLocation) { + this.projectLocation = projectLocation.trim(); + } + + /** + * Returns the project file. + * + * @return the project file + */ + public File getProjectFile(){ + return new File(getProjectLocation(), getDisplayName() + ProjectService.PROJECT_FILE_EXTENSION); + } + + @Override + public String toString(){ + return getDisplayName(); + } + } \ No newline at end of file diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectSubFolder.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectSubFolder.java index 488efc8..2fe5f9a 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectSubFolder.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/ProjectSubFolder.java @@ -1,44 +1,44 @@ -package cz.cvut.promod.services.projectService.treeProjectNode; - -import com.jgoodies.binding.PresentationModel; -import com.jgoodies.binding.value.ValueModel; -import com.jgoodies.binding.beans.Model; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 21:02:57, 13.10.2009 - */ - -/** - * Represents the project subfolder. - */ -public final class ProjectSubFolder implements ProjectContainer { - - private String displayName; - - /** - * Creates a new project subfolder. - * - * @param displayName is the display name of the project subfolder. - */ - public ProjectSubFolder(final String displayName) { - this.displayName = displayName; - } - - /** {@inheritDoc} */ - public String getDisplayName() { - return displayName; - } - - /** {@inheritDoc} */ - public void setDisplayName(final String displayName) { - this.displayName = displayName; - } - - @Override - public String toString(){ - return getDisplayName(); - } - -} +package cz.cvut.promod.services.projectService.treeProjectNode; + +import com.jgoodies.binding.PresentationModel; +import com.jgoodies.binding.value.ValueModel; +import com.jgoodies.binding.beans.Model; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 21:02:57, 13.10.2009 + */ + +/** + * Represents the project subfolder. + */ +public final class ProjectSubFolder implements ProjectContainer { + + private String displayName; + + /** + * Creates a new project subfolder. + * + * @param displayName is the display name of the project subfolder. + */ + public ProjectSubFolder(final String displayName) { + this.displayName = displayName; + } + + /** {@inheritDoc} */ + public String getDisplayName() { + return displayName; + } + + /** {@inheritDoc} */ + public void setDisplayName(final String displayName) { + this.displayName = displayName; + } + + @Override + public String toString(){ + return getDisplayName(); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/listener/ProjectDiagramListener.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/listener/ProjectDiagramListener.java index 631f888..dba6d09 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/listener/ProjectDiagramListener.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/treeProjectNode/listener/ProjectDiagramListener.java @@ -1,26 +1,26 @@ -package cz.cvut.promod.services.projectService.treeProjectNode.listener; - -import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagramChange; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 0:06:56, 18.1.2010 - */ - -/** - * Listener of changes in an instance of ProjectDiagram. - * - * @see cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram - */ -public interface ProjectDiagramListener { - - /** - * Listener method. Whenever any publishable change occurs, this method of all listeners is invoked. - * - * @param change is an object holding info about the change - * - * @see cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagramChange - */ - public void changePerformed(final ProjectDiagramChange change); -} +package cz.cvut.promod.services.projectService.treeProjectNode.listener; + +import cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagramChange; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 0:06:56, 18.1.2010 + */ + +/** + * Listener of changes in an instance of ProjectDiagram. + * + * @see cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagram + */ +public interface ProjectDiagramListener { + + /** + * Listener method. Whenever any publishable change occurs, this method of all listeners is invoked. + * + * @param change is an object holding info about the change + * + * @see cz.cvut.promod.services.projectService.treeProjectNode.ProjectDiagramChange + */ + public void changePerformed(final ProjectDiagramChange change); +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/projectService/utils/ProjectServiceUtils.java b/IndependentModeler/src/cz/cvut/promod/services/projectService/utils/ProjectServiceUtils.java index 0455a9e..39f71e5 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/projectService/utils/ProjectServiceUtils.java +++ b/IndependentModeler/src/cz/cvut/promod/services/projectService/utils/ProjectServiceUtils.java @@ -1,592 +1,592 @@ -package cz.cvut.promod.services.projectService.utils; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.projectService.treeProjectNode.*; -import cz.cvut.promod.services.projectService.ProjectService; -import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; - -import javax.swing.tree.TreeNode; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeModel; -import java.io.File; -import java.util.UUID; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 19:32:38, 12.11.2009 - */ - -/** - * Methods completing the ProjectService and ProjectControlService services. - * - * Use this methods when not required functionality is in the ProjectService or ProjectControlService service. - */ -public class ProjectServiceUtils { - - private static final Logger LOG = Logger.getLogger(ProjectServiceUtils.class); - - /* one can never give a project, diagram or subfolder name containing any of this chars */ - public static final char[] DISALLOWES_FILE_NAME_SYMBOLS = {'\\', '/', '?', '%', '*', ':', '|', '"', '<', '>', '.'}; - - /** - * Gives the file extension of the file name specified by the parameter. - * - * @param fileName full file name - * @return extension of this file - */ - public static String getFileExtension(final String fileName){ - if(fileName == null){ - return null; - } - - final int index = fileName.lastIndexOf(ProjectService.FILE_EXTENSION_DELIMITER); - - if(index < 0){ - return null; - } - - return fileName.substring(index + 1, fileName.length()); - } - - - /** - * Returns the file extension preceding by the '.' symbol that has been assigned to the notation - * - * @param notationIdentifier is the notation identifier - * @return symbol '.' and the file extension associated with the notation specified by the notation identifier - */ - public static String getNotationFileExtension(final String notationIdentifier) { - return ProjectService.FILE_EXTENSION_DELIMITER + ModelerSession.getNotationService().getNotation(notationIdentifier).getLocalIOController().getNotationFileExtension(); - } - - - /** - * Check whether file with given name ends with any notation file extension. - * - * @param fileName is a file name with it's extension - * @return true if there is a notation that saves/loads files with files extension - */ - public static boolean hasNotationFileExtension(final String fileName) { - for(final Notation notation : ModelerSession.getNotationService().getNotations()){ - final String fileExtension = ProjectService.FILE_EXTENSION_DELIMITER + notation.getLocalIOController().getNotationFileExtension(); - - if(fileName.endsWith(fileExtension)){ - return true; - } - } - - return false; - } - - - /** - * Removes any file or directory (even not empty) from the file system. - * - * @param path is path to the file or directory to be deleted - * - * @return true if the job has been done successfully, false otherwise - */ - public static boolean removeDirectory(final File path) { - if (path.isDirectory()) { - - final String[] dirChildren = path.list(); - - for (final String dirChild : dirChildren) { - if (!removeDirectory(new File(path, dirChild))) { //delete sub-directories - return false; - } - } - } - - return path.delete(); - } - - - /** - * Checks if there is no duplicity in display names in one project tree level. - * - * @param parent defines the required level - * @param displayName name of project item - * @return true if there is no same display name in the level - */ - public static boolean isUniqueProjectContainerDisplayName(final TreeNode parent, final String displayName) { - for(int i = 0; i < parent.getChildCount(); i++){ - - final ProjectItem projectItem = (ProjectItem) ((DefaultMutableTreeNode) parent.getChildAt(i)).getUserObject(); - - if(projectItem.getDisplayName().equals(displayName) && projectItem instanceof ProjectContainer){ - return false; - } - } - - return true; - } - - /** - * Checks whether user's object stored in an instance of DefaultMutableTreeNode is an instance of - * ProjectContainer class. - * - * @param parent is a instance of DefaultMutableTreeNode which is supposed to hold the mentioned user's object - * @return true if and only if the user's object is an instance of class extending Project container interface - */ - public static boolean isProjectContainer(final DefaultMutableTreeNode parent){ - final ProjectItem projectItem; - - try{ - projectItem = (ProjectItem) parent.getUserObject(); - } catch (ClassCastException exception){ - return false; - } - - return projectItem != null && projectItem instanceof ProjectContainer; - } - - - /** - * Checks if there is already no another diagram of the same name and notation under the tree parent. - * - * @param parent is common the tree parent - * @param projectDiagram is the "new" project diagram that's name and notation identifier will be tested - * - * @return true if and only of there is not any diagram with the same name and same notation under the given tree parent yet - */ - public static boolean isUniqueProjectDiagramName(final TreeNode parent, final ProjectDiagram projectDiagram) { - for(int i = 0; i < parent.getChildCount(); i++){ - - final Object userObject = ((DefaultMutableTreeNode) parent.getChildAt(i)).getUserObject(); - - if( userObject instanceof ProjectDiagram){ - final ProjectDiagram existingDiagram = (ProjectDiagram) userObject; - - if((existingDiagram.getDisplayName().equals(projectDiagram.getDisplayName())) - && (existingDiagram.getNotationIdentifier().equals(projectDiagram.getNotationIdentifier()))){ - return false; - } - } - } - - return true; - } - - - /** - * Checks whether the tree path provided as an argument is valid tree path accordingly to the tree model. - * - * @param treePath a tree path to check for validity - * @return true if and only if the treePath is valid, false otherwise - */ - public static boolean isValidTreePath(final TreePath treePath){ - final TreeModel treeModel = ModelerSession.getProjectControlService().getProjectTreeModel(); - final TreeNode rootNode = (TreeNode) treeModel.getRoot(); - - if((treePath == null) || (rootNode != treePath.getPathComponent(0))){ - return false; - } - - final int pathCount = treePath.getPathCount(); - - for(int i = 1; i < pathCount; i++){ - final Object parent = treePath.getPathComponent(i - 1); - final Object child = treePath.getPathComponent(i); - - final int index = treeModel.getIndexOfChild(parent, child); - - if(index < 0){ - return false; - } - - final DefaultMutableTreeNode node; - try{ - node = (DefaultMutableTreeNode) child; - } catch (ClassCastException exception){ - LOG.error("All project tree nodes have to be an instance of DefaultMutableTreeNode class."); - return false; - } - - final Object userObject = node.getUserObject(); - - //second node has to represent a project root - if(i == 1){ - if(!(userObject instanceof ProjectRoot)){ - return false; - } - } - - if(userObject instanceof ProjectRoot){ - if(i != 1){ - return false; - } - } else if(userObject instanceof ProjectSubFolder){ - // do nothing - } else if(userObject instanceof ProjectDiagram){ - if(i != (pathCount - 1)){ - // diagram node has no other children - return false; - } - } - } - - return true; - } - - - /** - * Looks for the tree path of a project diagram specified by the it's uuid. The search starts by the project node - * specified by the treePath argument and continues recursively like DFS search. - * - * Due to performance reason this method doesn't check the given tree path for validity. Programmer should do - * it on his/her own (using ProjectServiceUtils.isValidTreePath() method). - * - * @param treePath is the tree path of the node, where the search is supposed to start - * @param uuid is the uuid of searched project diagram - * - * @return tree path to the project diagram with given uuid, null if no diagram was found - */ - public static TreePath findProjectDiagram(final TreePath treePath, final UUID uuid) { - - final DefaultMutableTreeNode parentNode; - try{ - parentNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); - } catch (Exception e){ - LOG.error("All items in the project tree modelFactory have to be an instance of DefaultMutableTreeNode class or " + - "any class extending DefaultMutableTreeNode class.", e); - return null; - } - - if(parentNode.getUserObject() instanceof ProjectDiagram){ - if(((ProjectDiagram) parentNode.getUserObject()).getUuid().equals(uuid)){ - return treePath; - } - - } else if(parentNode.getUserObject() instanceof ProjectContainer){ - - // is not a ProjectDiagram but a ProjectContainer - TreePath resultTreePath; - - for(int i = 0; i < parentNode.getChildCount(); i++){ - final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); - - final TreePath childTreePath = treePath.pathByAddingChild(childNode); - - resultTreePath = findProjectDiagram(childTreePath, uuid); - - if(resultTreePath != null){ - return resultTreePath; - } - } - - } else { - LOG.error("Project's node user's object has to be an instance of ProjectDiagram or ProjectContainer interface."); - return null; - } - - return null; - } - - /** - * Finds tree path to the child node of a node specified by parentTreePath which is one of method's arguments. - * This child node has to have the same name and event the same notation. If the first method argument is a - * directory, that method compares just display name and the directory name. If there is a real file specified by - * the file argument, that this method compares display name of project item and name of the file without file - * extension and project diagram notation and the notation that is specified by the file's extension. - * - * @param file that specifies the directory or project diagram of any notation - * @param parentTreePath specifies the path to the parent node where the search is supposed to be performed - * @return tree path of the existing project subfolder or project diagram if exists, null otherwise - */ - public static TreePath findTreePath(final File file, final TreePath parentTreePath) { - final String name = file.getName(); - - try{ - final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) parentTreePath.getLastPathComponent(); - - if(file.isFile() && ProjectServiceUtils.hasNotationFileExtension(name)){ - - final String fileNameWithoutExt = name.substring(0, name.lastIndexOf(ProjectService.FILE_EXTENSION_DELIMITER)); - final String extension = name.substring(name.lastIndexOf(ProjectService.FILE_EXTENSION_DELIMITER) + 1, name.length()); - final String notationIdentifier = ModelerSession.getNotationService().getNotationIdentifier(extension); - - if(notationIdentifier == null){ // there is no such a notation for this file extension - return null; - } - - if(fileNameWithoutExt == null || fileNameWithoutExt.equals("")){ - return null; - } - - for(int i = 0; i < parentNode.getChildCount(); i++){ - final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); - - final ProjectItem usersProjectItem = (ProjectItem) childNode.getUserObject(); - - if(usersProjectItem instanceof ProjectDiagram){ - final ProjectDiagram projectDiagram = (ProjectDiagram) usersProjectItem; - - if(projectDiagram.getDisplayName().equals(fileNameWithoutExt) && notationIdentifier.equals(projectDiagram.getNotationIdentifier())){ - return parentTreePath.pathByAddingChild(childNode); - } - - } - } - } else if (file.isDirectory()){ - for(int i = 0; i < parentNode.getChildCount(); i++){ - final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); - - final ProjectItem usersProjectItem = (ProjectItem) childNode.getUserObject(); - - if(usersProjectItem instanceof ProjectContainer){ - if(usersProjectItem.getDisplayName().equals(name)) - return parentTreePath.pathByAddingChild(childNode); - } - } - } - - } catch(ClassCastException exception){ - LOG.error("An node in project tree modelFactory is not an instance of DefaultMutableTreeNode."); - } - - return null; - } - - - /** - * Creating a file system path of the file that's is related to the project item. - * If a project root is specified by the tree path and the project file (.pmp) is - * saved in C:\Project\myProject.pmp, then this method returns C:\Project. This - * works in the same way for project subfolders and diagrams. Files related to the - * project diagrams have an extension associated with a notation loaded. - * - * @param treePath to the project item, has to have at least 2 components - * - * @return a file system path, null if any error has occurred - */ - public static String getFileSystemPathToProjectItem(final TreePath treePath){ - if(!isValidTreePath(treePath)){ - return null; - } - - final StringBuffer fileSystemPath = new StringBuffer(); - - try{ - ProjectRoot projectRoot = (ProjectRoot) ((DefaultMutableTreeNode)treePath.getPathComponent(1)).getUserObject(); - - fileSystemPath.append(projectRoot.getProjectLocation()); - - final int pathCount = treePath.getPathCount(); - - for(int i = 2; i < pathCount; i++){ - final Object object = ((DefaultMutableTreeNode)treePath.getPathComponent(i)).getUserObject(); - - if(object instanceof ProjectSubFolder){ - final String name = ((ProjectSubFolder)object).getDisplayName(); - - if(name == null || name.equals("")){ - return null; - } - - fileSystemPath.append(System.getProperty("file.separator")); - fileSystemPath.append(name); - - } else if(object instanceof ProjectDiagram){ - final ProjectDiagram projectDiagram = (ProjectDiagram)object; - final String name = projectDiagram.getDisplayName(); - final String extension = getNotationFileExtension(projectDiagram.getNotationIdentifier()); - - if(name == null || name.equals("") || extension == null || extension.equals("")){ - return null; - } - - fileSystemPath.append(System.getProperty("file.separator")); - fileSystemPath.append(name).append(extension); - - } else { - LOG.error("Any project item after project root can be only project subfolder or a project diagram."); - return null; - } - } - - return fileSystemPath.toString(); - - } catch (Exception exception){ - LOG.error("An error during file system path sequence creation has occurred.", exception); - } - - return null; - } - - /** - * @param node is an instance od DefaultMutableTreeNode - * @return true if the node holds and instance of ProjectDiagram, false otherwise - */ - public static boolean isProjectDiagram(final DefaultMutableTreeNode node){ - return node != null && isProjectDiagram(node.getUserObject()); - - } - - /** - * @param object an object - * @return true if the object is an instance of ProjectDiagram - */ - public static boolean isProjectDiagram(final Object object){ - return object instanceof ProjectDiagram; - } - - - /** - * @param node is an instance od DefaultMutableTreeNode - * @return true if the node holds and instance of ProjectSubFolder, false otherwise - */ - public static boolean isProjectSubfolder(final DefaultMutableTreeNode node){ - return node != null && isProjectSubfolder(node.getUserObject()); - - } - - /** - * @param object an object - * @return true if the object is an instance of ProjectSubFolder - */ - public static boolean isProjectSubfolder(final Object object){ - return object instanceof ProjectSubFolder; - } - - /** - * @param node is an instance od DefaultMutableTreeNode - * @return true if the node holds and instance of ProjectRoot , false otherwise - */ - public static boolean isProjectRoot(final DefaultMutableTreeNode node){ - return node != null && isProjectRoot(node.getUserObject()); - - } - - /** - * @param object an object - * @return true if the object is an instance of ProjectRoot - */ - public static boolean isProjectRoot(final Object object){ - return object instanceof ProjectRoot; - } - - - /** - * Deletes an item (file or directory) from file system which path is specified by the projectParentNodeTreePath variable. The path is build - * from the project root file (absolut path) and then by adding subfolders names. All user's object in nodes in the - * tree path has to be implementations of ProjectContainer interface, except the first one, which is the model root. - * Finally the itemName variable is added to the end of the built path. And the item with the resulting path is deleted. - * - * @param projectParentNodeTreePath is a tree path to build the file system path the the item that is supposed to be deleted - * @param itemName is a name of the item to be deleted (e.g. myfile.pmd, mydir, ...) - - * @return true on success, false otherwise - */ - public static boolean deleteFSItem(final TreePath projectParentNodeTreePath, final String itemName) { - if(!ProjectServiceUtils.isValidTreePath(projectParentNodeTreePath) || projectParentNodeTreePath.getPathCount() < 2){ - return false; - } - - File file; - try{ - ProjectRoot projectRoot = (ProjectRoot) ((DefaultMutableTreeNode) projectParentNodeTreePath.getPathComponent(1)).getUserObject(); - file = new File((projectRoot.getProjectLocation())); - - for(int i = 2; i < projectParentNodeTreePath.getPathCount(); i++){ - ProjectContainer projectContainer = (ProjectContainer) ((DefaultMutableTreeNode) projectParentNodeTreePath.getPathComponent(i)).getUserObject(); - - file = new File(file.getAbsolutePath(), projectContainer.getDisplayName()); - } - - } catch (ClassCastException exception){ - LOG.error("Not valid tree path or even project structure. The path do the file system item is not possible to build.", exception); - return false; - } - - file = new File(file.getAbsolutePath(), itemName); - - return !file.exists() || ProjectServiceUtils.removeDirectory(file); - } - - - /** - * Compares two tree paths and returns true if the path specified by the second method's parameter is an - * extension of the path specified by the first argument of the method. - * - * The path specified by the second argument is checked for validity, - * @see ProjectServiceUtils isValidTreePath(final TreePath treePath) - * - * Reference comparison is used. - * - * @param originalTreePath is the shorter path - * @param extendedTreePath is the extended path - * - * @return true if the extended path is the same like the original path or it extends the original path and the - * extended path is valid tree path (with regard to the project tree model), false otherwise - */ - public static boolean isTreePathExtension(final TreePath originalTreePath, final TreePath extendedTreePath){ - if(!isValidTreePath(extendedTreePath)){ - return false; - } - - if(originalTreePath.getPathCount() > extendedTreePath.getPathCount()){ - return false; - } - - for(int i = 0; i < originalTreePath.getPathCount(); i++){ - if(originalTreePath.getPathComponent(i) != extendedTreePath.getPathComponent(i)){ - return false; - } - } - - return true; - - } - - /** - * Checks whether the name given as a method's argument doesn't contain any of disallowed symbols. - * This should ensure that all project's, subfolder's and diagram's names used in ProMod will be then - * possible to save on file system in main OSs (MS Windows, Linux, Solaris). - * - * @param name to be checked - * @return true if and only if the name given as argument doesn't contain any disallowed symbol, false otherwise - */ - public static boolean isSyntacticallyCorrectName(final String name){ - if(name == null || name.isEmpty()){ - return false; - } - - for(final char ch : DISALLOWES_FILE_NAME_SYMBOLS){ - if(name.indexOf(ch) > -1){ - return false; - } - } - - return true; - } - - /** - * Returns the string of disallowed symbols as a string using specified delimiter, e.g. (delimiter is ',') - * ?,:,|,\,/ etc. - * - * @param delimiter is the separator - * @return the string of all disallowed symbols - */ - public static String getDisallowedNameSymbols(final char delimiter){ - final StringBuffer symbols = new StringBuffer(); - - final int symbolCount = DISALLOWES_FILE_NAME_SYMBOLS.length; - for(int i = 0; i < symbolCount; i++){ - final char symbol = DISALLOWES_FILE_NAME_SYMBOLS[i]; - - symbols.append(symbol); - - if(i != (symbolCount - 1)){ - symbols.append(delimiter); - } - } - - return symbols.toString(); - } - -} +package cz.cvut.promod.services.projectService.utils; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.projectService.treeProjectNode.*; +import cz.cvut.promod.services.projectService.ProjectService; +import cz.cvut.promod.plugin.notationSpecificPlugIn.notation.Notation; + +import javax.swing.tree.TreeNode; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeModel; +import java.io.File; +import java.util.UUID; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 19:32:38, 12.11.2009 + */ + +/** + * Methods completing the ProjectService and ProjectControlService services. + * + * Use this methods when not required functionality is in the ProjectService or ProjectControlService service. + */ +public class ProjectServiceUtils { + + private static final Logger LOG = Logger.getLogger(ProjectServiceUtils.class); + + /* one can never give a project, diagram or subfolder name containing any of this chars */ + public static final char[] DISALLOWES_FILE_NAME_SYMBOLS = {'\\', '/', '?', '%', '*', ':', '|', '"', '<', '>', '.'}; + + /** + * Gives the file extension of the file name specified by the parameter. + * + * @param fileName full file name + * @return extension of this file + */ + public static String getFileExtension(final String fileName){ + if(fileName == null){ + return null; + } + + final int index = fileName.lastIndexOf(ProjectService.FILE_EXTENSION_DELIMITER); + + if(index < 0){ + return null; + } + + return fileName.substring(index + 1, fileName.length()); + } + + + /** + * Returns the file extension preceding by the '.' symbol that has been assigned to the notation + * + * @param notationIdentifier is the notation identifier + * @return symbol '.' and the file extension associated with the notation specified by the notation identifier + */ + public static String getNotationFileExtension(final String notationIdentifier) { + return ProjectService.FILE_EXTENSION_DELIMITER + ModelerSession.getNotationService().getNotation(notationIdentifier).getLocalIOController().getNotationFileExtension(); + } + + + /** + * Check whether file with given name ends with any notation file extension. + * + * @param fileName is a file name with it's extension + * @return true if there is a notation that saves/loads files with files extension + */ + public static boolean hasNotationFileExtension(final String fileName) { + for(final Notation notation : ModelerSession.getNotationService().getNotations()){ + final String fileExtension = ProjectService.FILE_EXTENSION_DELIMITER + notation.getLocalIOController().getNotationFileExtension(); + + if(fileName.endsWith(fileExtension)){ + return true; + } + } + + return false; + } + + + /** + * Removes any file or directory (even not empty) from the file system. + * + * @param path is path to the file or directory to be deleted + * + * @return true if the job has been done successfully, false otherwise + */ + public static boolean removeDirectory(final File path) { + if (path.isDirectory()) { + + final String[] dirChildren = path.list(); + + for (final String dirChild : dirChildren) { + if (!removeDirectory(new File(path, dirChild))) { //delete sub-directories + return false; + } + } + } + + return path.delete(); + } + + + /** + * Checks if there is no duplicity in display names in one project tree level. + * + * @param parent defines the required level + * @param displayName name of project item + * @return true if there is no same display name in the level + */ + public static boolean isUniqueProjectContainerDisplayName(final TreeNode parent, final String displayName) { + for(int i = 0; i < parent.getChildCount(); i++){ + + final ProjectItem projectItem = (ProjectItem) ((DefaultMutableTreeNode) parent.getChildAt(i)).getUserObject(); + + if(projectItem.getDisplayName().equals(displayName) && projectItem instanceof ProjectContainer){ + return false; + } + } + + return true; + } + + /** + * Checks whether user's object stored in an instance of DefaultMutableTreeNode is an instance of + * ProjectContainer class. + * + * @param parent is a instance of DefaultMutableTreeNode which is supposed to hold the mentioned user's object + * @return true if and only if the user's object is an instance of class extending Project container interface + */ + public static boolean isProjectContainer(final DefaultMutableTreeNode parent){ + final ProjectItem projectItem; + + try{ + projectItem = (ProjectItem) parent.getUserObject(); + } catch (ClassCastException exception){ + return false; + } + + return projectItem != null && projectItem instanceof ProjectContainer; + } + + + /** + * Checks if there is already no another diagram of the same name and notation under the tree parent. + * + * @param parent is common the tree parent + * @param projectDiagram is the "new" project diagram that's name and notation identifier will be tested + * + * @return true if and only of there is not any diagram with the same name and same notation under the given tree parent yet + */ + public static boolean isUniqueProjectDiagramName(final TreeNode parent, final ProjectDiagram projectDiagram) { + for(int i = 0; i < parent.getChildCount(); i++){ + + final Object userObject = ((DefaultMutableTreeNode) parent.getChildAt(i)).getUserObject(); + + if( userObject instanceof ProjectDiagram){ + final ProjectDiagram existingDiagram = (ProjectDiagram) userObject; + + if((existingDiagram.getDisplayName().equals(projectDiagram.getDisplayName())) + && (existingDiagram.getNotationIdentifier().equals(projectDiagram.getNotationIdentifier()))){ + return false; + } + } + } + + return true; + } + + + /** + * Checks whether the tree path provided as an argument is valid tree path accordingly to the tree model. + * + * @param treePath a tree path to check for validity + * @return true if and only if the treePath is valid, false otherwise + */ + public static boolean isValidTreePath(final TreePath treePath){ + final TreeModel treeModel = ModelerSession.getProjectControlService().getProjectTreeModel(); + final TreeNode rootNode = (TreeNode) treeModel.getRoot(); + + if((treePath == null) || (rootNode != treePath.getPathComponent(0))){ + return false; + } + + final int pathCount = treePath.getPathCount(); + + for(int i = 1; i < pathCount; i++){ + final Object parent = treePath.getPathComponent(i - 1); + final Object child = treePath.getPathComponent(i); + + final int index = treeModel.getIndexOfChild(parent, child); + + if(index < 0){ + return false; + } + + final DefaultMutableTreeNode node; + try{ + node = (DefaultMutableTreeNode) child; + } catch (ClassCastException exception){ + LOG.error("All project tree nodes have to be an instance of DefaultMutableTreeNode class."); + return false; + } + + final Object userObject = node.getUserObject(); + + //second node has to represent a project root + if(i == 1){ + if(!(userObject instanceof ProjectRoot)){ + return false; + } + } + + if(userObject instanceof ProjectRoot){ + if(i != 1){ + return false; + } + } else if(userObject instanceof ProjectSubFolder){ + // do nothing + } else if(userObject instanceof ProjectDiagram){ + if(i != (pathCount - 1)){ + // diagram node has no other children + return false; + } + } + } + + return true; + } + + + /** + * Looks for the tree path of a project diagram specified by the it's uuid. The search starts by the project node + * specified by the treePath argument and continues recursively like DFS search. + * + * Due to performance reason this method doesn't check the given tree path for validity. Programmer should do + * it on his/her own (using ProjectServiceUtils.isValidTreePath() method). + * + * @param treePath is the tree path of the node, where the search is supposed to start + * @param uuid is the uuid of searched project diagram + * + * @return tree path to the project diagram with given uuid, null if no diagram was found + */ + public static TreePath findProjectDiagram(final TreePath treePath, final UUID uuid) { + + final DefaultMutableTreeNode parentNode; + try{ + parentNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); + } catch (Exception e){ + LOG.error("All items in the project tree modelFactory have to be an instance of DefaultMutableTreeNode class or " + + "any class extending DefaultMutableTreeNode class.", e); + return null; + } + + if(parentNode.getUserObject() instanceof ProjectDiagram){ + if(((ProjectDiagram) parentNode.getUserObject()).getUuid().equals(uuid)){ + return treePath; + } + + } else if(parentNode.getUserObject() instanceof ProjectContainer){ + + // is not a ProjectDiagram but a ProjectContainer + TreePath resultTreePath; + + for(int i = 0; i < parentNode.getChildCount(); i++){ + final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); + + final TreePath childTreePath = treePath.pathByAddingChild(childNode); + + resultTreePath = findProjectDiagram(childTreePath, uuid); + + if(resultTreePath != null){ + return resultTreePath; + } + } + + } else { + LOG.error("Project's node user's object has to be an instance of ProjectDiagram or ProjectContainer interface."); + return null; + } + + return null; + } + + /** + * Finds tree path to the child node of a node specified by parentTreePath which is one of method's arguments. + * This child node has to have the same name and event the same notation. If the first method argument is a + * directory, that method compares just display name and the directory name. If there is a real file specified by + * the file argument, that this method compares display name of project item and name of the file without file + * extension and project diagram notation and the notation that is specified by the file's extension. + * + * @param file that specifies the directory or project diagram of any notation + * @param parentTreePath specifies the path to the parent node where the search is supposed to be performed + * @return tree path of the existing project subfolder or project diagram if exists, null otherwise + */ + public static TreePath findTreePath(final File file, final TreePath parentTreePath) { + final String name = file.getName(); + + try{ + final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) parentTreePath.getLastPathComponent(); + + if(file.isFile() && ProjectServiceUtils.hasNotationFileExtension(name)){ + + final String fileNameWithoutExt = name.substring(0, name.lastIndexOf(ProjectService.FILE_EXTENSION_DELIMITER)); + final String extension = name.substring(name.lastIndexOf(ProjectService.FILE_EXTENSION_DELIMITER) + 1, name.length()); + final String notationIdentifier = ModelerSession.getNotationService().getNotationIdentifier(extension); + + if(notationIdentifier == null){ // there is no such a notation for this file extension + return null; + } + + if(fileNameWithoutExt == null || fileNameWithoutExt.equals("")){ + return null; + } + + for(int i = 0; i < parentNode.getChildCount(); i++){ + final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); + + final ProjectItem usersProjectItem = (ProjectItem) childNode.getUserObject(); + + if(usersProjectItem instanceof ProjectDiagram){ + final ProjectDiagram projectDiagram = (ProjectDiagram) usersProjectItem; + + if(projectDiagram.getDisplayName().equals(fileNameWithoutExt) && notationIdentifier.equals(projectDiagram.getNotationIdentifier())){ + return parentTreePath.pathByAddingChild(childNode); + } + + } + } + } else if (file.isDirectory()){ + for(int i = 0; i < parentNode.getChildCount(); i++){ + final DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); + + final ProjectItem usersProjectItem = (ProjectItem) childNode.getUserObject(); + + if(usersProjectItem instanceof ProjectContainer){ + if(usersProjectItem.getDisplayName().equals(name)) + return parentTreePath.pathByAddingChild(childNode); + } + } + } + + } catch(ClassCastException exception){ + LOG.error("An node in project tree modelFactory is not an instance of DefaultMutableTreeNode."); + } + + return null; + } + + + /** + * Creating a file system path of the file that's is related to the project item. + * If a project root is specified by the tree path and the project file (.pmp) is + * saved in C:\Project\myProject.pmp, then this method returns C:\Project. This + * works in the same way for project subfolders and diagrams. Files related to the + * project diagrams have an extension associated with a notation loaded. + * + * @param treePath to the project item, has to have at least 2 components + * + * @return a file system path, null if any error has occurred + */ + public static String getFileSystemPathToProjectItem(final TreePath treePath){ + if(!isValidTreePath(treePath)){ + return null; + } + + final StringBuffer fileSystemPath = new StringBuffer(); + + try{ + ProjectRoot projectRoot = (ProjectRoot) ((DefaultMutableTreeNode)treePath.getPathComponent(1)).getUserObject(); + + fileSystemPath.append(projectRoot.getProjectLocation()); + + final int pathCount = treePath.getPathCount(); + + for(int i = 2; i < pathCount; i++){ + final Object object = ((DefaultMutableTreeNode)treePath.getPathComponent(i)).getUserObject(); + + if(object instanceof ProjectSubFolder){ + final String name = ((ProjectSubFolder)object).getDisplayName(); + + if(name == null || name.equals("")){ + return null; + } + + fileSystemPath.append(System.getProperty("file.separator")); + fileSystemPath.append(name); + + } else if(object instanceof ProjectDiagram){ + final ProjectDiagram projectDiagram = (ProjectDiagram)object; + final String name = projectDiagram.getDisplayName(); + final String extension = getNotationFileExtension(projectDiagram.getNotationIdentifier()); + + if(name == null || name.equals("") || extension == null || extension.equals("")){ + return null; + } + + fileSystemPath.append(System.getProperty("file.separator")); + fileSystemPath.append(name).append(extension); + + } else { + LOG.error("Any project item after project root can be only project subfolder or a project diagram."); + return null; + } + } + + return fileSystemPath.toString(); + + } catch (Exception exception){ + LOG.error("An error during file system path sequence creation has occurred.", exception); + } + + return null; + } + + /** + * @param node is an instance od DefaultMutableTreeNode + * @return true if the node holds and instance of ProjectDiagram, false otherwise + */ + public static boolean isProjectDiagram(final DefaultMutableTreeNode node){ + return node != null && isProjectDiagram(node.getUserObject()); + + } + + /** + * @param object an object + * @return true if the object is an instance of ProjectDiagram + */ + public static boolean isProjectDiagram(final Object object){ + return object instanceof ProjectDiagram; + } + + + /** + * @param node is an instance od DefaultMutableTreeNode + * @return true if the node holds and instance of ProjectSubFolder, false otherwise + */ + public static boolean isProjectSubfolder(final DefaultMutableTreeNode node){ + return node != null && isProjectSubfolder(node.getUserObject()); + + } + + /** + * @param object an object + * @return true if the object is an instance of ProjectSubFolder + */ + public static boolean isProjectSubfolder(final Object object){ + return object instanceof ProjectSubFolder; + } + + /** + * @param node is an instance od DefaultMutableTreeNode + * @return true if the node holds and instance of ProjectRoot , false otherwise + */ + public static boolean isProjectRoot(final DefaultMutableTreeNode node){ + return node != null && isProjectRoot(node.getUserObject()); + + } + + /** + * @param object an object + * @return true if the object is an instance of ProjectRoot + */ + public static boolean isProjectRoot(final Object object){ + return object instanceof ProjectRoot; + } + + + /** + * Deletes an item (file or directory) from file system which path is specified by the projectParentNodeTreePath variable. The path is build + * from the project root file (absolut path) and then by adding subfolders names. All user's object in nodes in the + * tree path has to be implementations of ProjectContainer interface, except the first one, which is the model root. + * Finally the itemName variable is added to the end of the built path. And the item with the resulting path is deleted. + * + * @param projectParentNodeTreePath is a tree path to build the file system path the the item that is supposed to be deleted + * @param itemName is a name of the item to be deleted (e.g. myfile.pmd, mydir, ...) + + * @return true on success, false otherwise + */ + public static boolean deleteFSItem(final TreePath projectParentNodeTreePath, final String itemName) { + if(!ProjectServiceUtils.isValidTreePath(projectParentNodeTreePath) || projectParentNodeTreePath.getPathCount() < 2){ + return false; + } + + File file; + try{ + ProjectRoot projectRoot = (ProjectRoot) ((DefaultMutableTreeNode) projectParentNodeTreePath.getPathComponent(1)).getUserObject(); + file = new File((projectRoot.getProjectLocation())); + + for(int i = 2; i < projectParentNodeTreePath.getPathCount(); i++){ + ProjectContainer projectContainer = (ProjectContainer) ((DefaultMutableTreeNode) projectParentNodeTreePath.getPathComponent(i)).getUserObject(); + + file = new File(file.getAbsolutePath(), projectContainer.getDisplayName()); + } + + } catch (ClassCastException exception){ + LOG.error("Not valid tree path or even project structure. The path do the file system item is not possible to build.", exception); + return false; + } + + file = new File(file.getAbsolutePath(), itemName); + + return !file.exists() || ProjectServiceUtils.removeDirectory(file); + } + + + /** + * Compares two tree paths and returns true if the path specified by the second method's parameter is an + * extension of the path specified by the first argument of the method. + * + * The path specified by the second argument is checked for validity, + * @see ProjectServiceUtils isValidTreePath(final TreePath treePath) + * + * Reference comparison is used. + * + * @param originalTreePath is the shorter path + * @param extendedTreePath is the extended path + * + * @return true if the extended path is the same like the original path or it extends the original path and the + * extended path is valid tree path (with regard to the project tree model), false otherwise + */ + public static boolean isTreePathExtension(final TreePath originalTreePath, final TreePath extendedTreePath){ + if(!isValidTreePath(extendedTreePath)){ + return false; + } + + if(originalTreePath.getPathCount() > extendedTreePath.getPathCount()){ + return false; + } + + for(int i = 0; i < originalTreePath.getPathCount(); i++){ + if(originalTreePath.getPathComponent(i) != extendedTreePath.getPathComponent(i)){ + return false; + } + } + + return true; + + } + + /** + * Checks whether the name given as a method's argument doesn't contain any of disallowed symbols. + * This should ensure that all project's, subfolder's and diagram's names used in ProMod will be then + * possible to save on file system in main OSs (MS Windows, Linux, Solaris). + * + * @param name to be checked + * @return true if and only if the name given as argument doesn't contain any disallowed symbol, false otherwise + */ + public static boolean isSyntacticallyCorrectName(final String name){ + if(name == null || name.isEmpty()){ + return false; + } + + for(final char ch : DISALLOWES_FILE_NAME_SYMBOLS){ + if(name.indexOf(ch) > -1){ + return false; + } + } + + return true; + } + + /** + * Returns the string of disallowed symbols as a string using specified delimiter, e.g. (delimiter is ',') + * ?,:,|,\,/ etc. + * + * @param delimiter is the separator + * @return the string of all disallowed symbols + */ + public static String getDisallowedNameSymbols(final char delimiter){ + final StringBuffer symbols = new StringBuffer(); + + final int symbolCount = DISALLOWES_FILE_NAME_SYMBOLS.length; + for(int i = 0; i < symbolCount; i++){ + final char symbol = DISALLOWES_FILE_NAME_SYMBOLS[i]; + + symbols.append(symbol); + + if(i != (symbolCount - 1)){ + symbols.append(delimiter); + } + } + + return symbols.toString(); + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarControlService.java b/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarControlService.java index f6ea9de..b6d1b51 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarControlService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarControlService.java @@ -1,25 +1,25 @@ -package cz.cvut.promod.services.statusBarService; - -import com.jidesoft.status.StatusBar; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 14:53:46, 21.1.2010 - */ - -/** - * StatusBarControlService allows developers to obtain the notation specific status bar. - */ -public interface StatusBarControlService extends StatusBarService{ - - /** - * Returns the notation specific status bar. - * - * @param notationIdentifier is the notation identifier of the associated status bar - * - * @return required notation specific status bar - */ - public StatusBar getStatusBar(final String notationIdentifier); - -} +package cz.cvut.promod.services.statusBarService; + +import com.jidesoft.status.StatusBar; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 14:53:46, 21.1.2010 + */ + +/** + * StatusBarControlService allows developers to obtain the notation specific status bar. + */ +public interface StatusBarControlService extends StatusBarService{ + + /** + * Returns the notation specific status bar. + * + * @param notationIdentifier is the notation identifier of the associated status bar + * + * @return required notation specific status bar + */ + public StatusBar getStatusBar(final String notationIdentifier); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarControlServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarControlServiceImpl.java index 661e809..81aaf85 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarControlServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarControlServiceImpl.java @@ -1,99 +1,99 @@ -package cz.cvut.promod.services.statusBarService; - -import com.jidesoft.status.StatusBar; -import com.jidesoft.status.StatusBarItem; -import com.jidesoft.swing.JideBoxLayout; - -import java.util.Map; -import java.util.HashMap; - -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.services.statusBarService.utils.InsertStatusBarItemResult; -import cz.cvut.promod.gui.ModelerModel; -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 14:54:23, 21.1.2010 - */ - -/** - * StatusBarControlService implementation. - */ -public class StatusBarControlServiceImpl implements StatusBarControlService{ - - private static final Logger LOG = Logger.getLogger(StatusBarControlServiceImpl.class); - - private final Map statusBarMap; - - - /** - * Constructs a new StatusBarControlServiceImpl instance. - */ - public StatusBarControlServiceImpl() { - statusBarMap = new HashMap(); - } - - /** {@inheritDoc} */ - public StatusBar getStatusBar(final String notationIdentifier) { - if(notationIdentifier == null){ - return null; - } - - if(!ModelerSession.getNotationService().existNotation(notationIdentifier) - && !notationIdentifier.equals(ModelerModel.MODELER_IDENTIFIER)){ - return null; - } - - if(statusBarMap.containsKey(notationIdentifier)){ - return statusBarMap.get(notationIdentifier); - } - - final StatusBar statusBar = ModelerSession.getComponentFactoryService().createStatusBar(); - statusBarMap.put(notationIdentifier, statusBar); - - return statusBar; - } - - /** {@inheritDoc} */ - public InsertStatusBarItemResult addStatusBarItem(final String notationIdentifier, - final StatusBarItem statusBarItem, - String itemLayout) { - - if(!ModelerSession.getNotationService().existNotation(notationIdentifier) - && !ModelerModel.MODELER_IDENTIFIER.equals(notationIdentifier)){ - LOG.error("Not possible to insert action to the tool bar of not existing notation."); - return InsertStatusBarItemResult.INVALID_NOTATION; - } - - if(statusBarItem == null){ - LOG.error("Invalid status bar item to be inserted."); - return InsertStatusBarItemResult.INVALID_STATUS_BAR_ITEM; - } - - if(itemLayout == null){ - LOG.info("Setting status bar layout to implicit value"); - itemLayout = JideBoxLayout.FIX; - } - - final StatusBar statusBar = getStatusBar(notationIdentifier); - - if(!(itemLayout.equals(JideBoxLayout.FIX) - || itemLayout.equals(JideBoxLayout.FLEXIBLE) - || itemLayout.equals(JideBoxLayout.VARY))){ - - itemLayout = JideBoxLayout.FIX; - } - - statusBar.add(statusBarItem, itemLayout); - - return InsertStatusBarItemResult.SUCCESS; - } - - /** {@inheritDoc} */ - public boolean check() { - return true; - } - -} +package cz.cvut.promod.services.statusBarService; + +import com.jidesoft.status.StatusBar; +import com.jidesoft.status.StatusBarItem; +import com.jidesoft.swing.JideBoxLayout; + +import java.util.Map; +import java.util.HashMap; + +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.services.statusBarService.utils.InsertStatusBarItemResult; +import cz.cvut.promod.gui.ModelerModel; +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 14:54:23, 21.1.2010 + */ + +/** + * StatusBarControlService implementation. + */ +public class StatusBarControlServiceImpl implements StatusBarControlService{ + + private static final Logger LOG = Logger.getLogger(StatusBarControlServiceImpl.class); + + private final Map statusBarMap; + + + /** + * Constructs a new StatusBarControlServiceImpl instance. + */ + public StatusBarControlServiceImpl() { + statusBarMap = new HashMap(); + } + + /** {@inheritDoc} */ + public StatusBar getStatusBar(final String notationIdentifier) { + if(notationIdentifier == null){ + return null; + } + + if(!ModelerSession.getNotationService().existNotation(notationIdentifier) + && !notationIdentifier.equals(ModelerModel.MODELER_IDENTIFIER)){ + return null; + } + + if(statusBarMap.containsKey(notationIdentifier)){ + return statusBarMap.get(notationIdentifier); + } + + final StatusBar statusBar = ModelerSession.getComponentFactoryService().createStatusBar(); + statusBarMap.put(notationIdentifier, statusBar); + + return statusBar; + } + + /** {@inheritDoc} */ + public InsertStatusBarItemResult addStatusBarItem(final String notationIdentifier, + final StatusBarItem statusBarItem, + String itemLayout) { + + if(!ModelerSession.getNotationService().existNotation(notationIdentifier) + && !ModelerModel.MODELER_IDENTIFIER.equals(notationIdentifier)){ + LOG.error("Not possible to insert action to the tool bar of not existing notation."); + return InsertStatusBarItemResult.INVALID_NOTATION; + } + + if(statusBarItem == null){ + LOG.error("Invalid status bar item to be inserted."); + return InsertStatusBarItemResult.INVALID_STATUS_BAR_ITEM; + } + + if(itemLayout == null){ + LOG.info("Setting status bar layout to implicit value"); + itemLayout = JideBoxLayout.FIX; + } + + final StatusBar statusBar = getStatusBar(notationIdentifier); + + if(!(itemLayout.equals(JideBoxLayout.FIX) + || itemLayout.equals(JideBoxLayout.FLEXIBLE) + || itemLayout.equals(JideBoxLayout.VARY))){ + + itemLayout = JideBoxLayout.FIX; + } + + statusBar.add(statusBarItem, itemLayout); + + return InsertStatusBarItemResult.SUCCESS; + } + + /** {@inheritDoc} */ + public boolean check() { + return true; + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarService.java b/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarService.java index 8f44c76..79ea522 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/statusBarService/StatusBarService.java @@ -1,38 +1,38 @@ -package cz.cvut.promod.services.statusBarService; - -import com.jidesoft.status.StatusBarItem; -import cz.cvut.promod.services.Service; -import cz.cvut.promod.services.statusBarService.utils.InsertStatusBarItemResult; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 14:53:26, 21.1.2010 - */ - -/** - * StatusBarService allows developers to insert new status bar items into the notation specific status bar. - */ -public interface StatusBarService extends Service { - - /** - * Appends new status bar item to the notation specific status bar. - * - * @param notationIdentifier is the identifier of notation into which status bar is the new item supposed to be - * appended - * - * @param statusBarItem is the status bar item that is supposed to be appended - * - * @param itemLayout is the layout information, see JideBoxLayout.FIX, JideBoxLayout.FLEXIBLE, JideBoxLayout.VARY, - * JideBoxLayout.FIX is the initial value in case of nullary info or invalid value - * - * @return any value from InsertStatusBarItemResult enumeration - * - * @see cz.cvut.promod.services.statusBarService.utils.InsertStatusBarItemResult for more detail info about return - * values - */ - public InsertStatusBarItemResult addStatusBarItem(final String notationIdentifier, - final StatusBarItem statusBarItem, - String itemLayout); - -} +package cz.cvut.promod.services.statusBarService; + +import com.jidesoft.status.StatusBarItem; +import cz.cvut.promod.services.Service; +import cz.cvut.promod.services.statusBarService.utils.InsertStatusBarItemResult; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 14:53:26, 21.1.2010 + */ + +/** + * StatusBarService allows developers to insert new status bar items into the notation specific status bar. + */ +public interface StatusBarService extends Service { + + /** + * Appends new status bar item to the notation specific status bar. + * + * @param notationIdentifier is the identifier of notation into which status bar is the new item supposed to be + * appended + * + * @param statusBarItem is the status bar item that is supposed to be appended + * + * @param itemLayout is the layout information, see JideBoxLayout.FIX, JideBoxLayout.FLEXIBLE, JideBoxLayout.VARY, + * JideBoxLayout.FIX is the initial value in case of nullary info or invalid value + * + * @return any value from InsertStatusBarItemResult enumeration + * + * @see cz.cvut.promod.services.statusBarService.utils.InsertStatusBarItemResult for more detail info about return + * values + */ + public InsertStatusBarItemResult addStatusBarItem(final String notationIdentifier, + final StatusBarItem statusBarItem, + String itemLayout); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/statusBarService/utils/InsertStatusBarItemResult.java b/IndependentModeler/src/cz/cvut/promod/services/statusBarService/utils/InsertStatusBarItemResult.java index a3e1ab6..b32bb09 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/statusBarService/utils/InsertStatusBarItemResult.java +++ b/IndependentModeler/src/cz/cvut/promod/services/statusBarService/utils/InsertStatusBarItemResult.java @@ -1,29 +1,29 @@ -package cz.cvut.promod.services.statusBarService.utils; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 14:26:54, 4.2.2010 - */ - -/** - * Possible results for inserting a new status bar item into the notation specific status bar. - */ -public enum InsertStatusBarItemResult { - - /** - * The new status bar item has been appended successfully. - */ - SUCCESS, - - /** - * It is not possible to insert any status bar item into the tool bar of not existing notation. - */ - INVALID_NOTATION, - - /** - * Status bar item is not valid. - */ - INVALID_STATUS_BAR_ITEM, - -} +package cz.cvut.promod.services.statusBarService.utils; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 14:26:54, 4.2.2010 + */ + +/** + * Possible results for inserting a new status bar item into the notation specific status bar. + */ +public enum InsertStatusBarItemResult { + + /** + * The new status bar item has been appended successfully. + */ + SUCCESS, + + /** + * It is not possible to insert any status bar item into the tool bar of not existing notation. + */ + INVALID_NOTATION, + + /** + * Status bar item is not valid. + */ + INVALID_STATUS_BAR_ITEM, + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarControlService.java b/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarControlService.java index 58c4c3e..a78495f 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarControlService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarControlService.java @@ -1,25 +1,25 @@ -package cz.cvut.promod.services.toolBarService; - -import com.jidesoft.action.CommandBar; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 23:54:34, 20.12.2009 - */ - -/** - * ToolBarControlService allows developer to obtain and operate with notation specific tool bar. - */ -public interface ToolBarControlService extends ToolBarService{ - - /** - * Returns notation specific instance of CommandBar class. - * - * @param notationIdentifier is the identifier of a notation - * - * @return the command bar for the notation, or null if there is no such a notation - */ - public CommandBar getCommandBar(final String notationIdentifier); - -} +package cz.cvut.promod.services.toolBarService; + +import com.jidesoft.action.CommandBar; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 23:54:34, 20.12.2009 + */ + +/** + * ToolBarControlService allows developer to obtain and operate with notation specific tool bar. + */ +public interface ToolBarControlService extends ToolBarService{ + + /** + * Returns notation specific instance of CommandBar class. + * + * @param notationIdentifier is the identifier of a notation + * + * @return the command bar for the notation, or null if there is no such a notation + */ + public CommandBar getCommandBar(final String notationIdentifier); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarControlServiceImpl.java b/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarControlServiceImpl.java index 7f6e72e..8e5cb69 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarControlServiceImpl.java +++ b/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarControlServiceImpl.java @@ -1,129 +1,129 @@ -package cz.cvut.promod.services.toolBarService; - -import com.jidesoft.action.CommandBar; - -import java.util.Map; -import java.util.HashMap; -import java.awt.*; - -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; -import cz.cvut.promod.services.toolBarService.utils.InsertToolBarItemResult; -import cz.cvut.promod.services.ModelerSession; -import cz.cvut.promod.gui.ModelerModel; - -import javax.swing.*; - -import org.apache.log4j.Logger; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:51:01, 10.10.2009 - */ - -/** - * An implementation of ToolBarControlService. - */ -public class ToolBarControlServiceImpl implements ToolBarControlService{ - - private static final Logger LOG = Logger.getLogger(ToolBarControlServiceImpl.class); - - private final Map commandBars; - - /** - * Constructs ToolBarControlServiceImpl class. - */ - public ToolBarControlServiceImpl() { - commandBars = new HashMap(); - } - - /** {@inheritDoc} */ - public CommandBar getCommandBar(final String notationIdentifier) { - if(notationIdentifier == null){ - return null; - } - - if(ModelerSession.getNotationService().existNotation(notationIdentifier) - || notationIdentifier.equals(ModelerModel.MODELER_IDENTIFIER)){ - - if(commandBars.containsKey(notationIdentifier)){ - return commandBars.get(notationIdentifier); - } - - final CommandBar commandBar = new CommandBar(); - commandBars.put(notationIdentifier, commandBar); - return commandBar; - } - - return null; - } - - /** {@inheritDoc} */ - public InsertToolBarItemResult addAction(final String notationIdentifier, final ProModAction action) { - if(action == null - || action.getValue(AbstractAction.NAME) == null - || ((String)action.getValue(AbstractAction.NAME)).isEmpty()){ - - return InsertToolBarItemResult.UNDEFINED_ACTION; - } - - if(!ModelerSession.getNotationService().existNotation(notationIdentifier)){ - LOG.error("Not possible to insert action to the tool bar of not existing notation."); - return InsertToolBarItemResult.INVALID_NOTATION; - } - - if(!ModelerSession.getActionControlService().isRegisteredAction(action)){ - LOG.error("Not possible to insert unregistered action."); - return InsertToolBarItemResult.UNREGISTERED_ACTION; - } - - if(!action.getNotationIdentifier().equals(notationIdentifier)){ - LOG.error("Not possible to insert action registered with another notation."); - return InsertToolBarItemResult.UNREGISTERED_ACTION; - } - - final CommandBar commandBar = getCommandBar(notationIdentifier); - - if(!isUniqueAction(commandBar, action)){ - LOG.info("Skipping insertion of duplicate action," + - " action identifier: " + action.getActionIdentifier() + - ", notation identifier: " + action.getNotationIdentifier() + - ", module identifier: " + action.getModuleIdentifier()); - - return InsertToolBarItemResult.DUPLICATE_ACTION; - } - - commandBar.add(action); - - return InsertToolBarItemResult.SUCCESS; - } - - /** - * Checks whether there is no the same action already inserted in one tool bar. It uses just reference - * comparison (==) for action equality. - * - * @param commandBar is the status bar to be search - * @param action is the action to be found - * @return true if there is already no such a action in the command bar, false otherwise - */ - private boolean isUniqueAction(final CommandBar commandBar, final ProModAction action) { - for(final Component component : commandBar.getComponents()){ - if(component instanceof JButton){ - final JButton button = (JButton) component; - final Action buttonAction = button.getAction(); - - if( buttonAction != null && buttonAction == action){ - return false; - } - } - } - - return true; - } - - /** {@inheritDoc} */ - public boolean check() { - return true; - } - -} +package cz.cvut.promod.services.toolBarService; + +import com.jidesoft.action.CommandBar; + +import java.util.Map; +import java.util.HashMap; +import java.awt.*; + +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; +import cz.cvut.promod.services.toolBarService.utils.InsertToolBarItemResult; +import cz.cvut.promod.services.ModelerSession; +import cz.cvut.promod.gui.ModelerModel; + +import javax.swing.*; + +import org.apache.log4j.Logger; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:51:01, 10.10.2009 + */ + +/** + * An implementation of ToolBarControlService. + */ +public class ToolBarControlServiceImpl implements ToolBarControlService{ + + private static final Logger LOG = Logger.getLogger(ToolBarControlServiceImpl.class); + + private final Map commandBars; + + /** + * Constructs ToolBarControlServiceImpl class. + */ + public ToolBarControlServiceImpl() { + commandBars = new HashMap(); + } + + /** {@inheritDoc} */ + public CommandBar getCommandBar(final String notationIdentifier) { + if(notationIdentifier == null){ + return null; + } + + if(ModelerSession.getNotationService().existNotation(notationIdentifier) + || notationIdentifier.equals(ModelerModel.MODELER_IDENTIFIER)){ + + if(commandBars.containsKey(notationIdentifier)){ + return commandBars.get(notationIdentifier); + } + + final CommandBar commandBar = new CommandBar(); + commandBars.put(notationIdentifier, commandBar); + return commandBar; + } + + return null; + } + + /** {@inheritDoc} */ + public InsertToolBarItemResult addAction(final String notationIdentifier, final ProModAction action) { + if(action == null + || action.getValue(AbstractAction.NAME) == null + || ((String)action.getValue(AbstractAction.NAME)).isEmpty()){ + + return InsertToolBarItemResult.UNDEFINED_ACTION; + } + + if(!ModelerSession.getNotationService().existNotation(notationIdentifier)){ + LOG.error("Not possible to insert action to the tool bar of not existing notation."); + return InsertToolBarItemResult.INVALID_NOTATION; + } + + if(!ModelerSession.getActionControlService().isRegisteredAction(action)){ + LOG.error("Not possible to insert unregistered action."); + return InsertToolBarItemResult.UNREGISTERED_ACTION; + } + + if(!action.getNotationIdentifier().equals(notationIdentifier)){ + LOG.error("Not possible to insert action registered with another notation."); + return InsertToolBarItemResult.UNREGISTERED_ACTION; + } + + final CommandBar commandBar = getCommandBar(notationIdentifier); + + if(!isUniqueAction(commandBar, action)){ + LOG.info("Skipping insertion of duplicate action," + + " action identifier: " + action.getActionIdentifier() + + ", notation identifier: " + action.getNotationIdentifier() + + ", module identifier: " + action.getModuleIdentifier()); + + return InsertToolBarItemResult.DUPLICATE_ACTION; + } + + commandBar.add(action); + + return InsertToolBarItemResult.SUCCESS; + } + + /** + * Checks whether there is no the same action already inserted in one tool bar. It uses just reference + * comparison (==) for action equality. + * + * @param commandBar is the status bar to be search + * @param action is the action to be found + * @return true if there is already no such a action in the command bar, false otherwise + */ + private boolean isUniqueAction(final CommandBar commandBar, final ProModAction action) { + for(final Component component : commandBar.getComponents()){ + if(component instanceof JButton){ + final JButton button = (JButton) component; + final Action buttonAction = button.getAction(); + + if( buttonAction != null && buttonAction == action){ + return false; + } + } + } + + return true; + } + + /** {@inheritDoc} */ + public boolean check() { + return true; + } + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarService.java b/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarService.java index f8b6b20..faf363f 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/toolBarService/ToolBarService.java @@ -1,29 +1,29 @@ -package cz.cvut.promod.services.toolBarService; - -import cz.cvut.promod.services.Service; -import cz.cvut.promod.services.toolBarService.utils.InsertToolBarItemResult; -import cz.cvut.promod.services.actionService.actionUtils.ProModAction; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:46:23, 10.10.2009 - */ - -/** - * ToolBarService allows developer to insert (append) simple action to the notation specific tool bar. - */ -public interface ToolBarService extends Service{ - - /** - * Adds new action to the tool bar of specified notation. - * - * @param notationIdentifier is the identifier of the notation to which is tool bar is the action supposed to be added. - * @param action the action that is supposed to be added - * @return the result in form of InsertToolBarItemResult - * - * @see cz.cvut.promod.services.toolBarService.utils.InsertToolBarItemResult - */ - public InsertToolBarItemResult addAction(final String notationIdentifier, final ProModAction action); - -} +package cz.cvut.promod.services.toolBarService; + +import cz.cvut.promod.services.Service; +import cz.cvut.promod.services.toolBarService.utils.InsertToolBarItemResult; +import cz.cvut.promod.services.actionService.actionUtils.ProModAction; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:46:23, 10.10.2009 + */ + +/** + * ToolBarService allows developer to insert (append) simple action to the notation specific tool bar. + */ +public interface ToolBarService extends Service{ + + /** + * Adds new action to the tool bar of specified notation. + * + * @param notationIdentifier is the identifier of the notation to which is tool bar is the action supposed to be added. + * @param action the action that is supposed to be added + * @return the result in form of InsertToolBarItemResult + * + * @see cz.cvut.promod.services.toolBarService.utils.InsertToolBarItemResult + */ + public InsertToolBarItemResult addAction(final String notationIdentifier, final ProModAction action); + +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/toolBarService/utils/InsertToolBarItemResult.java b/IndependentModeler/src/cz/cvut/promod/services/toolBarService/utils/InsertToolBarItemResult.java index 01fc7d1..437c2db 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/toolBarService/utils/InsertToolBarItemResult.java +++ b/IndependentModeler/src/cz/cvut/promod/services/toolBarService/utils/InsertToolBarItemResult.java @@ -1,38 +1,38 @@ -package cz.cvut.promod.services.toolBarService.utils; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 11:53:01, 4.2.2010 - */ - -/** - * Possible results for inserting a new action into the notation specific tool bar. - */ -public enum InsertToolBarItemResult { - - /** - * The action has been successfully added into the tool bar. - */ - SUCCESS, - - /** - * The action is either null or does not have name or has an empty string as it's name. - */ - UNDEFINED_ACTION, - - /** - * It is not possible to insert any action into the tool bar of not existing notation. - */ - INVALID_NOTATION, - - /** - * It is not possible to insert action that is not registered by the ActionService. - */ - UNREGISTERED_ACTION, - - /** - * It is not possible to insert the same action twice into the same tool bar. - */ - DUPLICATE_ACTION -} +package cz.cvut.promod.services.toolBarService.utils; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 11:53:01, 4.2.2010 + */ + +/** + * Possible results for inserting a new action into the notation specific tool bar. + */ +public enum InsertToolBarItemResult { + + /** + * The action has been successfully added into the tool bar. + */ + SUCCESS, + + /** + * The action is either null or does not have name or has an empty string as it's name. + */ + UNDEFINED_ACTION, + + /** + * It is not possible to insert any action into the tool bar of not existing notation. + */ + INVALID_NOTATION, + + /** + * It is not possible to insert action that is not registered by the ActionService. + */ + UNREGISTERED_ACTION, + + /** + * It is not possible to insert the same action twice into the same tool bar. + */ + DUPLICATE_ACTION +} diff --git a/IndependentModeler/src/cz/cvut/promod/services/userService/UserService.java b/IndependentModeler/src/cz/cvut/promod/services/userService/UserService.java index f1f28df..e770ba1 100644 --- a/IndependentModeler/src/cz/cvut/promod/services/userService/UserService.java +++ b/IndependentModeler/src/cz/cvut/promod/services/userService/UserService.java @@ -1,40 +1,40 @@ -package cz.cvut.promod.services.userService; - -import cz.cvut.promod.services.Service; -import com.jgoodies.binding.value.ValueModel; - -/** - * ProMod, master thesis project - * User: Petr Zverina, petr.zverina@gmail.com - * Date: 17:43:19, 10.10.2009 - */ - -/** - * UserService interface. - * - * UserService holds the user identification. - */ -public interface UserService extends Service { - - /** - * Returns the identifier of logged user. - * - * @return user's identifier - */ - public String getUser(); - - /** - * Returns the observable value model representing the user's identifier. - * - * @return observable value model representing the user's identifier - */ - public ValueModel getUserValueModel(); - - /** - * Changes the actual user. - * - * @param user is the identifier of the new user, an empty string stands for no user - */ - public void setUser(final String user); - -} +package cz.cvut.promod.services.userService; + +import cz.cvut.promod.services.Service; +import com.jgoodies.binding.value.ValueModel; + +/** + * ProMod, master thesis project + * User: Petr Zverina, petr.zverina@gmail.com + * Date: 17:43:19, 10.10.2009 + */ + +/** + * UserService interface. + * + * UserService holds the user identification. + */ +public interface UserService extends Service { + + /** + * Returns the identifier of logged user. + * + * @return user's identifier + */ + public String getUser(); + + /** + * Returns the observable value model representing the user's identifier. + * + * @return observable value model representing the user's identifier + */ + public ValueModel getUserValueModel(); + + /** + * Changes the actual user. + * + * @param user is the identifier of the new user, an empty string stands for no user + */ + public void setUser(final String user); + +} -- 2.11.4.GIT