View Javadoc
1   package org.opentrafficsim.editor.extensions;
2   
3   import java.rmi.RemoteException;
4   import java.util.function.Consumer;
5   
6   import org.djutils.event.Event;
7   import org.djutils.event.EventListener;
8   import org.djutils.event.reference.ReferenceType;
9   import org.opentrafficsim.editor.OtsEditor;
10  import org.opentrafficsim.editor.XsdPaths;
11  import org.opentrafficsim.editor.XsdTreeNode;
12  import org.opentrafficsim.editor.XsdTreeNodeRoot;
13  
14  /**
15   * Allows the user to save definitions separately.
16   * <p>
17   * Copyright (c) 2023-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
18   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
19   * </p>
20   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
21   */
22  public class DefinitionsSaver implements EventListener, Consumer<XsdTreeNode>
23  {
24      /** */
25      private static final long serialVersionUID = 20230914L;
26  
27      /** Editor. */
28      private OtsEditor editor;
29  
30      /**
31       * Constructor.
32       * @param editor OtsEditor; editor.
33       * @throws RemoteException if listener cannot be added.
34       */
35      public DefinitionsSaver(final OtsEditor editor) throws RemoteException
36      {
37          editor.addListener(this, OtsEditor.NEW_FILE);
38          this.editor = editor;
39      }
40  
41      /** {@inheritDoc} */
42      @Override
43      public void notify(final Event event) throws RemoteException
44      {
45          if (event.getType().equals(OtsEditor.NEW_FILE))
46          {
47              XsdTreeNodeRoot root = (XsdTreeNodeRoot) event.getContent();
48              root.addListener(this, XsdTreeNodeRoot.NODE_CREATED, ReferenceType.WEAK);
49              root.addListener(this, XsdTreeNodeRoot.NODE_REMOVED, ReferenceType.WEAK);
50          }
51          else if (event.getType().equals(XsdTreeNodeRoot.NODE_CREATED))
52          {
53              XsdTreeNode node = (XsdTreeNode) ((Object[]) event.getContent())[0];
54              if (!node.getPathString().equals(XsdPaths.DEFINITIONS + ".xi:include") && node.getParent() != null
55                      && node.getParent().getPathString().equals(XsdPaths.DEFINITIONS))
56              {
57                  node.addConsumer("Save as include file...", this);
58              }
59          }
60          else if (event.getType().equals(XsdTreeNodeRoot.NODE_REMOVED))
61          {
62              XsdTreeNode node = (XsdTreeNode) ((Object[]) event.getContent())[0];
63              node.removeListener(this, XsdTreeNodeRoot.NODE_REMOVED);
64          }
65      }
66  
67      /** {@inheritDoc} */
68      @Override
69      public void accept(final XsdTreeNode node)
70      {
71          this.editor.saveFileAs(node);
72      }
73  }