protected void onSpecificationChange() {
   selectionListener.enable = false;
   //        for (Node o : (Node[]) em.getSelectedNodes()) {
   //            ((DecoratedNode) o).setHtmlDecorator(null);
   //        }
   DecoratedNode root = (DecoratedNode) em.getRootContext();
   Optional<DecoratedNode> node =
       root.breadthFirstIterable()
           .firstMatch(
               new Predicate<DecoratedNode>() {
                 @Override
                 public boolean apply(DecoratedNode input) {
                   return isCurrentSpecificationNode(input.getOriginal());
                 }
               });
   if (node.isPresent()) {
     //            node.get().setHtmlDecorator(DecoratedNode.Html.BOLD);
     try {
       em.setSelectedNodes(new Node[] {node.get()});
     } catch (PropertyVetoException ex) {
       // do nothing?
     }
   }
   selectionListener.enable = true;
 }
  /** Refreshes changed content nodes */
  private void refreshDataSourceTree() {
    Node selectedNode = getSelectedNode();
    final String[] selectedPath = NodeOp.createPath(selectedNode, em.getRootContext());

    Children rootChildren = em.getRootContext().getChildren();
    Node dataSourcesFilterNode = rootChildren.findChild(DataSourcesNode.NAME);
    if (dataSourcesFilterNode == null) {
      logger.log(
          Level.SEVERE,
          "Cannot find data sources filter node, won't refresh the content tree"); // NON-NLS
      return;
    }
    OriginalNode imagesNodeOrig = dataSourcesFilterNode.getLookup().lookup(OriginalNode.class);

    if (imagesNodeOrig == null) {
      logger.log(
          Level.SEVERE, "Cannot find data sources node, won't refresh the content tree"); // NON-NLS
      return;
    }

    Node imagesNode = imagesNodeOrig.getNode();

    RootContentChildren contentRootChildren = (RootContentChildren) imagesNode.getChildren();
    contentRootChildren.refreshContentKeys();

    // final TreeView tree = getTree();
    // tree.expandNode(imagesNode);

    setSelectedNode(selectedPath, DataSourcesNode.NAME);
  }
 private void initTree() {
   String sFilter;
   if (jCheckBoxCVS.isSelected()) {
     if (jCheckBoxTests.isSelected()) {
       sFilter =
           GENERAL_EXCLUDES + "|" + STANDARD_ANT_EXCLUDES + "|" + TEST_EXCLUDES + ")$"; // NOI18N
     } else {
       sFilter = GENERAL_EXCLUDES + "|" + STANDARD_ANT_EXCLUDES + ")$"; // NOI18N
     }
   } else {
     if (jCheckBoxTests.isSelected()) {
       sFilter = GENERAL_EXCLUDES + "|" + TEST_EXCLUDES + ")$"; // NOI18N
     } else {
       sFilter = GENERAL_EXCLUDES + ")$"; // NOI18N
     }
   }
   this.filter = Pattern.compile(sFilter);
   try {
     final DataObject dob = DataObject.find(srcRoot);
     manager.setRootContext(new FOBNode(dob.getNodeDelegate().cloneNode(), dob.getPrimaryFile()));
   } catch (DataObjectNotFoundException dnfe) {
     manager.setRootContext(Node.EMPTY);
   }
   treeView.registerProperty(properties, excludesTranslatedPropertyName, filter);
 }
 @Override
 public void addNotify() {
   super.addNotify();
   if (nodeChangeListener == null) {
     nodeChangeListener = new NodeChangeListener();
   }
   manager.addPropertyChangeListener(nodeChangeListener);
   manager.setRootContext(getRootContext());
   treeView.expandAll();
 }
Beispiel #5
0
  public LayoutScene(LayoutViewElement mve, LayoutDataObject obj) {
    super();

    this.dataObject = obj;

    multiview = mve;
    this.projectPath =
        FileOwnerQuery.getOwner(obj.getPrimaryFile()).getProjectDirectory().getPath();
    this.lSystem = LayoutParser.parse(obj);
    //        addSaveAsCapable();

    LayoutDocument ld = lSystem.getDocument();
    ld.addPropertyChangeListener(new DocumentDPIChangeListener());

    // paper layer
    this.paperWidget = new PaperWidget(this, ld);
    // add paper biar bisa diedit2
    ic.add(ld);
    paperLayer.addChild(paperWidget);

    layerController = LayerFactory.createLayer(this, lSystem.getLayers());
    // init em listener
    ExplorerManager em = layerController.getExplorerManager();
    em.addPropertyChangeListener(new NodeSelectionListener());
    // main layer, where sublayout widgets will be added
    mainLayer = layerController.getRootWidget();
    addChild(mainLayer);

    // selection layer, directly above the main layer
    selectionLayer = new LayerWidget(this);
    selectionWrapperWidget = new SelectionWrapperWidget(this);
    selectionLayer.addChild(selectionWrapperWidget);
    addChild(selectionLayer);

    //        getPriorActions().addAction(new KeySwitchToolAction());
    // scene's actions, applied to all selected widgets
    // key move tool, always available
    getActions().addAction(KEY_MOVE_ACTION);
    // move tool
    createActions(FREE_MOVE_TOOL).addAction(MOVE_ACTION);
    createActions(ON_AXIS_MOVE_TOOL).addAction(ON_AXIS_MOVE_ACTION);
    setActiveTool(FREE_MOVE_TOOL);
    // rotate on outside of selectedwrapper border
    createActions(SelectionWrapperWidget.TRANSFORM_TOOL).addAction(ROTATE_ACTION);
    // mirror selected layer, only on transform mode
    createActions(SelectionWrapperWidget.TRANSFORM_TOOL).addAction(MIRROR_ACTION);
    // show popup under right click to show layers under cursor
    getActions().addAction(SELECT_ACTION);
    getPriorActions().addAction(SCROLL_MODIFIER_ACTION);
    initLookup();

    createView();
  }
 @Override
 public void resultChanged(LookupEvent le) {
   Logger.getLogger(OscillogramNavigatorPanel.class.getName())
       .log(Level.INFO, manager.getRootContext().getDisplayName());
   Collection<? extends ChannelList> allInstances = this.result.allInstances();
   if (!allInstances.isEmpty()) {
     ChannelList list = allInstances.iterator().next();
     AbstractNode rn =
         new AbstractNode(Children.create(new ChannelChildFactory(list.getChannels()), false));
     rn.setName(list.getName());
     rn.setIconBaseWithExtension("tw/edu/sju/ee/eea/module/iepe/project/iepe_project.png");
     manager.setRootContext(rn);
     return;
   }
   //        manager.setRootContext(Node.EMPTY);
 }
  private void updateHistory(Node[] selectedNodes) {
    if (selectedNodes.length == 0) {
      return;
    }

    Node selectedNode = selectedNodes[0];
    String selectedNodeName = selectedNode.getName();

    /* get the previous entry to make sure we don't duplicate it.
     * Motivation for this is also that if we used the back button,
     * then we already added the 'current' node to 'back' and we will
     * detect that and not reset the forward list.
     */
    String[] currentLast = backList.peekLast();
    String lastNodeName = null;
    if (currentLast != null) {
      lastNodeName = currentLast[currentLast.length - 1];
    }

    if (currentLast == null || !selectedNodeName.equals(lastNodeName)) {
      // add to the list if the last if not the same as current
      final String[] selectedPath = NodeOp.createPath(selectedNode, em.getRootContext());
      backList.addLast(selectedPath); // add the node to the "backList"
      if (backList.size() > 1) {
        backButton.setEnabled(true);
      } else {
        backButton.setEnabled(false);
      }

      forwardList.clear(); // clear the "forwardList"
      forwardButton.setEnabled(false); // disable the forward Button
    }
  }
 @Override
 public void resultChanged(LookupEvent le) {
   Collection<? extends Person> p = personResult.allInstances();
   if (p.size() == 1) {
     Person currentPerson = p.iterator().next();
     for (Node node : em.getRootContext().getChildren().getNodes()) {
       if (node.getLookup().lookup(Synchronizable.class).getPerson() == currentPerson) {
         try {
           em.setSelectedNodes(new Node[] {node});
         } catch (PropertyVetoException ex) {
           Exceptions.printStackTrace(ex);
         }
       }
     }
   }
 }
 public static void refreshNode() {
   if (null != System.getProperty("derbyHostUrl")) {
     Map properties = new HashMap();
     properties.put("javax.persistence.jdbc.url", System.getProperty("derbyHostUrl"));
     EntityManager entityManager =
         Persistence.createEntityManagerFactory("mpsLibraryPU", properties).createEntityManager();
     properties = null;
     Query query = entityManager.createNamedQuery("Assignments.findAll");
     List<Assignments> resultList = query.getResultList();
     // em.setRootContext(new clientRootNode(Children.create(new ClientChildFactory(resultList),
     // true)));
     em.setRootContext(
         new AbstractNode(Children.create(new AssignmentChildFactory(resultList), true)));
     em.getRootContext().setDisplayName("Assignments");
   }
 }
 @Override
 public void resultChanged(LookupEvent ev) {
   // treeView.removeAll();
   Collection<? extends Clustering> allClusterings = result.allInstances();
   for (Clustering c : allClusterings) {
     root = new ClustersNode(c);
   }
   mgr.setRootContext(root);
 }
 public PersonViewerTopComponent() {
   initComponents();
   setName(Bundle.CTL_PersonViewerTopComponent());
   setToolTipText(Bundle.HINT_PersonViewerTopComponent());
   setLayout(new BorderLayout());
   BeanTreeView btv = new BeanTreeView();
   btv.setRootVisible(false);
   add(btv, BorderLayout.CENTER);
   em.setRootContext(new AbstractNode(Children.create(new PersonChildFactory(), true)));
   associateLookup(ExplorerUtils.createLookup(em, getActionMap()));
 }
  public AssignmentViewerTopComponent() {
    initComponents();
    setName(Bundle.CTL_AssignmentViewerTopComponent());
    setToolTipText(Bundle.HINT_AssignmentViewerTopComponent());
    putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
    putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
    if (null != System.getProperty("derbyHostUrl")) {
      Map properties = new HashMap();
      properties.put("javax.persistence.jdbc.url", System.getProperty("derbyHostUrl"));
      EntityManager entityManager =
          Persistence.createEntityManagerFactory("mpsLibraryPU", properties).createEntityManager();
      properties = null;
      Query query = entityManager.createNamedQuery("Assignments.findAll");
      List<Assignments> resultList = query.getResultList();

      em.setRootContext(
          new AbstractNode(Children.create(new AssignmentChildFactory(resultList), true)));
      em.getRootContext().setDisplayName("Assignments");
    }
    associateLookup(ExplorerUtils.createLookup(em, getActionMap()));
  }
 CopyActionPerformer(GraphEditor editor, ExplorerManager em) {
   this.editor = editor;
   this.em = em;
   em.addPropertyChangeListener(
       new PropertyChangeListener() {
         @Override
         public void propertyChange(PropertyChangeEvent evt) {
           refresh();
         }
       });
   refresh();
 }
Beispiel #14
0
 /**
  * Build a new root node and set it to be the explorer's root context.
  *
  * <p>
  *
  * @param kids root node's children, or Children.LEAF if none.
  */
 private void buildRoot(Children kids) {
   // Use a simple root node for which we can set the display name;
   // otherwise the logical root's properties affect the table headers.
   Node rootNode =
       new AbstractNode(kids) {
         @Override
         public Action[] getActions(boolean b) {
           return new Action[] {
             SystemAction.get(EditAction.class), SystemAction.get(RefreshAction.class),
           };
         }
       };
   explorerManager.setRootContext(rootNode);
 }
  public TreeBrowserTopComponent() {
    initComponents();
    setName(Bundle.CTL_TreeBrowserTopComponent());
    setToolTipText(Bundle.HINT_TreeBrowserTopComponent());

    associateLookup(ExplorerUtils.createLookup(explorerManager, getActionMap()));
    explorerManager.setRootContext(new ServersNode(getServersChildren()));

    ConnectionInformation info = new ConnectionInformation();
    info.setDomain("");

    if (INSTANCE == null) {
      INSTANCE = this;
    }
  }
  private void configureView() {
    rootNode = getChoiceRootNode();

    explorerManager = new ExplorerManager();
    explorerManager.setRootContext(rootNode);

    form.setExplorerManager(explorerManager);
    form.lblTextFilter.setText(rootNode.getTitleForSearch());

    ChoiceBeanTreeView treeView = new ChoiceBeanTreeView();
    treeView.setRootVisible(false);
    form.pnlTreeView.add(treeView, BorderLayout.CENTER);

    loadInfo();
  }
  public SpecSelectionComponent(boolean showSystemOnly) {
    this.tree = new BeanTreeView();
    this.em = new ExplorerManager();
    this.selectionListener = new SelectionListener();
    this.specification = newProperty(SPECIFICATION_PROPERTY, null);
    this.icon = newProperty(ICON_PROPERTY, null);

    tree.setRootVisible(false);
    tree.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    DecoratedNode root =
        new DecoratedNode(
            new DummyWsNode(WorkspaceFactory.getInstance().getActiveWorkspace(), SPECS_ID),
            showSystemOnly ? ItemWsNodeFilter.SYSTEM_ONLY : Predicates.<Node>alwaysTrue());
    for (DecoratedNode o : root.breadthFirstIterable()) {
      o.setPreferredActionDecorator(DecoratedNode.PreferredAction.DO_NOTHING);
    }

    em.setRootContext(root);

    setLayout(new BorderLayout());
    add(tree, BorderLayout.CENTER);
    setPreferredSize(new Dimension(225, 300));

    em.addVetoableChangeListener(selectionListener);
    addPropertyChangeListener(
        new PropertyChangeListener() {
          @Override
          public void propertyChange(PropertyChangeEvent evt) {
            String p = evt.getPropertyName();
            if (p.equals(SPECIFICATION_PROPERTY)) {
              onSpecificationChange();
            }
          }
        });
  }
Beispiel #18
0
  /** Creates new form BrowseFolders */
  public BrowseFolders(SourceGroup[] folders, boolean showFiles) {
    initComponents();
    this.folders = folders;
    this.showFiles = showFiles;
    manager = new ExplorerManager();
    AbstractNode rootNode = new AbstractNode(new SourceGroupsChildren(folders));
    manager.setRootContext(rootNode);

    // Create the templates view
    BeanTreeView btv = new BeanTreeView();
    btv.setRootVisible(false);
    btv.setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION);
    btv.setBorder(SAMPLE_SCROLL_PANE.getBorder());
    btv.getAccessibleContext()
        .setAccessibleDescription(NbBundle.getMessage(BrowseFolders.class, "ACSD_SelectFile"));
    folderPanel.add(btv, java.awt.BorderLayout.CENTER);
  }
Beispiel #19
0
 public ZIPExplorer() {
   setName(Bundle.CTL_ZIPTopComponent());
   setToolTipText(Bundle.HINT_ZIPTopComponent());
   setLayout(new BorderLayout());
   Node rootNode = new AbstractNode(Children.create(new ZIPChildFactory(), false));
   rootNode.setDisplayName("Root");
   BeanTreeView btv = new BeanTreeView();
   btv.setRootVisible(false);
   add(btv, BorderLayout.CENTER);
   ActionMap map = this.getActionMap();
   map.put(DefaultEditorKit.copyAction, ExplorerUtils.actionCopy(mgr));
   map.put(DefaultEditorKit.cutAction, ExplorerUtils.actionCut(mgr));
   map.put(DefaultEditorKit.pasteAction, ExplorerUtils.actionPaste(mgr));
   map.put("delete", ExplorerUtils.actionDelete(mgr, true)); // or false
   mgr.setRootContext(rootNode);
   associateLookup(ExplorerUtils.createLookup(mgr, map));
 }
  public CustomerViewerTopComponent() {
    initComponents();
    setName(Bundle.CTL_CustomerViewerTopComponent());
    setToolTipText(Bundle.HINT_CustomerViewerTopComponent());

    EntityManager entityManager =
        Persistence.createEntityManagerFactory("CustomerLibraryPU").createEntityManager();
    Query query = entityManager.createNamedQuery("Customer.findAll");
    List<Customer> resultList = query.getResultList();

    em.setRootContext(
        new AbstractNode(Children.create(new CustomerChildFactory(resultList), true)));
    //	for (Customer c : resultList) {
    //        jTextArea1.append(c.getName() + " (" + c.getCity() + ")" + "\n");
    // }

    associateLookup(ExplorerUtils.createLookup(em, getActionMap()));
  }
 public void propertyChange(PropertyChangeEvent evt) {
   if (evt.getSource() == manager) {
     if (ExplorerManager.PROP_SELECTED_NODES.equals(evt.getPropertyName())) {
       Node[] nodes = manager.getSelectedNodes();
       if (nodes != null && nodes.length > 0) {
         Node node = nodes[0];
         if (isClientNode(node)) {
           // This is a method node.
           selectedMethod = node;
           setSelectionValid(true);
         } else {
           // This is not a method node.
           selectedMethod = null;
           setSelectionValid(false);
         }
       }
     }
   }
 }
 /**
  * Expands the node if the node's state is not equal to "Not started" (i.e. it has been completed)
  * and selects it. Then, continues down it's children by calling this same method.
  *
  * <p>The recursion stops as soon as it gets to a node which has not been started.
  *
  * @param n The node down which to recurse
  */
 private void openTreeToCurrentStateRecursivly(Node n) {
   if (n instanceof ActivityNode) {
     if (!((ActivityNode) n).getCompletionState().equals("Planned")
         && !((ActivityNode) n).getCompletionState().equals("Contingent")
         && !((ActivityNode) n).getCompletionState().equals("Precluded")) {
       try {
         em.setSelectedNodes(new Node[] {n});
       } catch (PropertyVetoException ex) {
         Exceptions.printStackTrace(ex);
       }
       treeTableView.expandNode(n);
     } else {
     }
   } else {
   }
   for (Node child : n.getChildren().getNodes()) {
     openTreeToCurrentStateRecursivly(child);
   }
 }
  /**
   * Sets the {@link Process} whose information to display
   *
   * @param processFullId
   * @param p
   */
  public void setData(String processFullId, Process p) {
    this.processFullId = processFullId;
    process = p;
    setName(processFullId);
    Activities activities = ((Activities) p.getActivity().getValue());
    AbstractNode root =
        new AbstractNode(
            Children.create(new ActivitiesChildFactory(activities), false), Lookups.singleton(p));
    root.setDisplayName(processFullId);

    em.setRootContext(root);
    Node n = root.getChildren().getNodes()[0];
    Property[] columnProperties = n.getPropertySets()[0].getProperties();
    treeTableView.setProperties(columnProperties);
    treeTableView.setTreePreferredWidth(600);
    treeTableView.setTableColumnPreferredWidth(0, 75);
    treeTableView.setTableColumnPreferredWidth(1, 150);
    ((myTreeTableView) treeTableView).setRenderers();
    openTreeToCurrentState();
  }
 // move into editor?
 private ContainerProxy findComponentsAndParent(List<ComponentProxy> components) {
   Node[] nodes = em.getSelectedNodes();
   ContainerProxy parent = null;
   for (Node node : nodes) {
     ComponentProxy cmp = node.getLookup().lookup(ComponentProxy.class);
     if (cmp != null) {
       ContainerProxy p = cmp.getParent();
       if (p == null || cmp == editor.getContainer()) {
         parent = null;
         break;
       }
       if (parent == null) {
         parent = p;
       } else if (parent != p) {
         parent = null;
         break;
       }
       if (components != null) {
         components.add(cmp);
       }
     }
   }
   return parent;
 }
 @Override
 public void removeNotify() {
   manager.removePropertyChangeListener(nodeChangeListener);
   super.removeNotify();
 }
Beispiel #26
0
  public GraphSceneImpl() {
    mainLayer = new LayerWidget(this);
    connectionLayer = new LayerWidget(this);
    interactionLayer = new LayerWidget(this);
    addChild(mainLayer);
    addChild(connectionLayer);
    addChild(interactionLayer);

    getActions().addAction(ActionFactory.createZoomAction());
    getActions().addAction(ActionFactory.createWheelPanAction());

    //
    // the Childfactory creates Nodes for selected Objects
    final FakeChildFactory childFactory = new FakeChildFactory();

    // A Root Context Node for the ExplorerManager
    root = new AbstractNode(Children.create(childFactory, false));

    // ExplorerManager will create the Proxy Lookups for multiple selected Nodes
    em = new ExplorerManager();
    em.setRootContext(root);

    final ObjectSelectProvider selectProvider = new ObjectSelectProvider(this);
    final WidgetAction selectAction = ActionFactory.createSelectAction(selectProvider);

    // add drag & drop
    getActions()
        .addAction(
            ActionFactory.createAcceptAction(
                new AcceptProvider() {
                  @Override
                  public ConnectorState isAcceptable(
                      Widget widget, Point point, Transferable transferable) {
                    Image dragImage = getImageFromTransferable(transferable);
                    JComponent view = getView();
                    Graphics2D g2 = (Graphics2D) view.getGraphics();
                    Rectangle visRect = view.getVisibleRect();
                    view.paintImmediately(visRect.x, visRect.y, visRect.width, visRect.height);
                    g2.drawImage(
                        dragImage,
                        AffineTransform.getTranslateInstance(
                            point.getLocation().getX(), point.getLocation().getY()),
                        null);
                    return ConnectorState.ACCEPT;
                  }

                  @Override
                  public void accept(Widget widget, Point point, Transferable transferable) {
                    Image image = getImageFromTransferable(transferable);
                    //                Widget w = addNode("1node x - " + nodeCount++); // adding
                    // nodes dynamically
                    //                System.out.println(image.getHeight(null));
                    int imageReceivedHeight = image.getHeight(null);

                    Widget w = null;
                    ConfigNode cn = null;

                    if (imageReceivedHeight < DIMENTION_ICON_LIMIT) {

                      String key = "L2F" + String.valueOf(dimentionCount++);
                      cn = new ConfigNode(image, key);
                      nodeMap.put(key, cn);
                      w = GraphSceneImpl.this.addNode(cn);
                    } else if (imageReceivedHeight < FEATURE_ICON_LIMIT) {

                      String key = "L1F" + String.valueOf(featureCount++);
                      cn = new ConfigNode(image, key);
                      nodeMap.put(key, cn);
                      w = GraphSceneImpl.this.addNode(cn);
                    } else {

                      String key = "L0F" + String.valueOf(perceptionCount++);
                      cn = new PerceptionConfigNode(image, key);
                      nodeMap.put(key, cn);
                      w = GraphSceneImpl.this.addNode(cn);
                    }

                    //                Widget w = GraphSceneImpl.this.addNode(new ConfigNode(image,
                    // "2"));//

                    w.getActions().addAction(selectAction);

                    w.setPreferredLocation(widget.convertLocalToScene(point));
                  }
                }));

    // Object listener
    addObjectSceneListener(
        new ObjectSceneListener() {
          @Override
          public void objectAdded(ObjectSceneEvent ose, Object o) {
            //                throw new UnsupportedOperationException("Not supported yet.");
          }

          @Override
          public void objectRemoved(ObjectSceneEvent ose, Object o) {
            //                throw new UnsupportedOperationException("Not supported yet.");
          }

          @Override
          public void objectStateChanged(
              ObjectSceneEvent ose, Object o, ObjectState os, ObjectState os1) {
            //                throw new UnsupportedOperationException("Not supported yet.");
          }

          @Override
          public void selectionChanged(
              ObjectSceneEvent event, Set<Object> previousSelection, Set<Object> newSelection) {
            //                throw new UnsupportedOperationException("Not supported yet.");
            childFactory.setKeys(newSelection);
            try {
              em.setSelectedNodes(root.getChildren().getNodes());
            } catch (PropertyVetoException ex) {
              Exceptions.printStackTrace(ex);
            }
          }

          @Override
          public void highlightingChanged(ObjectSceneEvent ose, Set<Object> set, Set<Object> set1) {
            //                throw new UnsupportedOperationException("Not supported yet.");
          }

          @Override
          public void hoverChanged(ObjectSceneEvent ose, Object o, Object o1) {
            //                throw new UnsupportedOperationException("Not supported yet.");
          }

          @Override
          public void focusChanged(ObjectSceneEvent ose, Object o, Object o1) {
            //                throw new UnsupportedOperationException("Not supported yet.");
          }
        },
        ObjectSceneEventType.OBJECT_SELECTION_CHANGED);
  }
  /**
   * Called only when top component was closed on all workspaces before and now is opened for the
   * first time on some workspace. The intent is to provide subclasses information about
   * TopComponent's life cycle across all existing workspaces. Subclasses will usually perform
   * initializing tasks here.
   */
  @Override
  public void componentOpened() {
    // change the cursor to "waiting cursor" for this operation
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    try {
      if (Case.existsCurrentCase()) {
        Case currentCase = Case.getCurrentCase();

        // close the top component if there's no image in this case
        if (currentCase.hasData() == false) {
          // this.close();
          ((BeanTreeView) this.jScrollPane1).setRootVisible(false); // hide the root
        } else {
          // if there's at least one image, load the image and open the top component
          List<Object> items = new ArrayList<>();
          final SleuthkitCase tskCase = currentCase.getSleuthkitCase();
          items.add(new DataSources());
          items.add(new Views(tskCase));
          items.add(new Results(tskCase));
          items.add(new Reports());
          contentChildren = new RootContentChildren(items);
          Node root =
              new AbstractNode(contentChildren) {
                /**
                 * to override the right click action in the white blank space area on the directory
                 * tree window
                 */
                @Override
                public Action[] getActions(boolean popup) {
                  return new Action[] {};
                }

                // Overide the AbstractNode use of DefaultHandle to return
                // a handle which can be serialized without a parent
                @Override
                public Node.Handle getHandle() {
                  return new Node.Handle() {
                    @Override
                    public Node getNode() throws IOException {
                      return em.getRootContext();
                    }
                  };
                }
              };

          root = new DirectoryTreeFilterNode(root, true);

          em.setRootContext(root);
          em.getRootContext().setName(currentCase.getName());
          em.getRootContext().setDisplayName(currentCase.getName());
          ((BeanTreeView) this.jScrollPane1).setRootVisible(false); // hide the root

          // Reset the forward and back lists because we're resetting the root context
          resetHistory();

          Children childNodes = em.getRootContext().getChildren();
          TreeView tree = getTree();

          Node results = childNodes.findChild(ResultsNode.NAME);
          tree.expandNode(results);

          Children resultsChilds = results.getChildren();
          tree.expandNode(resultsChilds.findChild(KeywordHits.NAME));
          tree.expandNode(resultsChilds.findChild(ExtractedContent.NAME));

          Node views = childNodes.findChild(ViewsNode.NAME);
          Children viewsChilds = views.getChildren();
          for (Node n : viewsChilds.getNodes()) {
            tree.expandNode(n);
          }

          tree.collapseNode(views);

          // if the dataResult is not opened
          if (!dataResult.isOpened()) {
            dataResult
                .open(); // open the data result top component as well when the directory tree is
                         // opened
          }

          // select the first image node, if there is one
          // (this has to happen after dataResult is opened, because the event
          // of changing the selected node fires a handler that tries to make
          // dataResult active)
          if (childNodes.getNodesCount() > 0) {
            try {
              em.setSelectedNodes(new Node[] {childNodes.getNodeAt(0)});
            } catch (Exception ex) {
              logger.log(Level.SEVERE, "Error setting default selected node.", ex); // NON-NLS
            }
          }
        }
      }
    } finally {
      this.setCursor(null);
    }
  }
  /**
   * The "listener" that listens to any changes made in the Case.java class. It will do something
   * based on the changes in the Case.java class.
   *
   * @param evt the property change event
   */
  @Override
  public void propertyChange(PropertyChangeEvent evt) {
    String changed = evt.getPropertyName();
    Object oldValue = evt.getOldValue();
    Object newValue = evt.getNewValue();

    // change in the case name
    if (changed.equals(Case.Events.NAME.toString())) {
      // set the main title of the window
      String oldCaseName = oldValue.toString();
      String newCaseName = newValue.toString();

      // update the case name
      if ((!oldCaseName.equals("")) && (!newCaseName.equals(""))) {
        // change the root name and display name
        em.getRootContext().setName(newCaseName);
        em.getRootContext().setDisplayName(newCaseName);
      }
    } // changed current case
    else if (changed.equals(Case.Events.CURRENT_CASE.toString())) {
      // When a case is closed, the old value of this property is the
      // closed Case object and the new value is null. When a case is
      // opened, the old value is null and the new value is the new Case
      // object.
      // @@@ This needs to be revisited. Perhaps case closed and case
      // opened events instead of property change events would be a better
      // solution. Either way, more probably needs to be done to clean up
      // data model objects when a case is closed.
      if (oldValue != null && newValue == null) {
        // The current case has been closed. Reset the ExplorerManager.
        Node emptyNode = new AbstractNode(Children.LEAF);
        em.setRootContext(emptyNode);
      } else if (newValue != null) {
        // A new case has been opened. Reset the forward and back
        // buttons. Note that a call to CoreComponentControl.openCoreWindows()
        // by the new Case object will lead to a componentOpened() call
        // that will repopulate the tree.
        // @@@ The repopulation of the tree in this fashion also merits
        // reconsideration.
        resetHistory();
      }
    } // if the image is added to the case
    else if (changed.equals(Case.Events.DATA_SOURCE_ADDED.toString())) {
      componentOpened();
    }
    // change in node selection
    else if (changed.equals(ExplorerManager.PROP_SELECTED_NODES)) {
      respondSelection((Node[]) oldValue, (Node[]) newValue);
    } else if (changed.equals(IngestManager.IngestModuleEvent.DATA_ADDED.toString())) {
      // nothing to do here.
      // all nodes should be listening for these events and update accordingly.
    } else if (changed.equals(IngestManager.IngestJobEvent.COMPLETED.toString())
        || changed.equals(IngestManager.IngestJobEvent.CANCELLED.toString())) {
      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              refreshDataSourceTree();
            }
          });
    } else if (changed.equals(IngestManager.IngestModuleEvent.CONTENT_CHANGED.toString())) {
      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              refreshDataSourceTree();
            }
          });
    }
  }
  @Override
  public void viewArtifact(final BlackboardArtifact art) {
    BlackboardArtifact.ARTIFACT_TYPE type =
        BlackboardArtifact.ARTIFACT_TYPE.fromID(art.getArtifactTypeID());
    Children rootChilds = em.getRootContext().getChildren();
    Node treeNode = null;
    Node resultsNode = rootChilds.findChild(ResultsNode.NAME);
    Children resultsChilds = resultsNode.getChildren();
    if (type.equals(BlackboardArtifact.ARTIFACT_TYPE.TSK_HASHSET_HIT)) {
      Node hashsetRootNode = resultsChilds.findChild(type.getLabel());
      Children hashsetRootChilds = hashsetRootNode.getChildren();
      try {
        String setName = null;
        List<BlackboardAttribute> attributes = art.getAttributes();
        for (BlackboardAttribute att : attributes) {
          int typeId = att.getAttributeTypeID();
          if (typeId == BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID()) {
            setName = att.getValueString();
          }
        }
        treeNode = hashsetRootChilds.findChild(setName);
      } catch (TskException ex) {
        logger.log(Level.WARNING, "Error retrieving attributes", ex); // NON-NLS
      }
    } else if (type.equals(BlackboardArtifact.ARTIFACT_TYPE.TSK_KEYWORD_HIT)) {
      Node keywordRootNode = resultsChilds.findChild(type.getLabel());
      Children keywordRootChilds = keywordRootNode.getChildren();
      try {
        String listName = null;
        String keywordName = null;
        List<BlackboardAttribute> attributes = art.getAttributes();
        for (BlackboardAttribute att : attributes) {
          int typeId = att.getAttributeTypeID();
          if (typeId == BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID()) {
            listName = att.getValueString();
          } else if (typeId == BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD.getTypeID()) {
            keywordName = att.getValueString();
          }
        }
        Node listNode = keywordRootChilds.findChild(listName);
        Children listChildren = listNode.getChildren();
        treeNode = listChildren.findChild(keywordName);
      } catch (TskException ex) {
        logger.log(Level.WARNING, "Error retrieving attributes", ex); // NON-NLS
      }
    } else if (type.equals(BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT)
        || type.equals(BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT)) {
      Node interestingItemsRootNode = resultsChilds.findChild(type.getLabel());
      Children interestingItemsRootChildren = interestingItemsRootNode.getChildren();
      try {
        String setName = null;
        List<BlackboardAttribute> attributes = art.getAttributes();
        for (BlackboardAttribute att : attributes) {
          int typeId = att.getAttributeTypeID();
          if (typeId == BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID()) {
            setName = att.getValueString();
          }
        }
        treeNode = interestingItemsRootChildren.findChild(setName);
      } catch (TskException ex) {
        logger.log(Level.WARNING, "Error retrieving attributes", ex); // NON-NLS
      }
    } else {
      Node extractedContent = resultsChilds.findChild(ExtractedContent.NAME);
      Children extractedChilds = extractedContent.getChildren();
      treeNode = extractedChilds.findChild(type.getLabel());
    }
    try {
      em.setExploredContextAndSelection(treeNode, new Node[] {treeNode});
    } catch (PropertyVetoException ex) {
      logger.log(Level.WARNING, "Property Veto: ", ex); // NON-NLS
    }

    // Another thread is needed because we have to wait for dataResult to populate
    EventQueue.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            Children resultChilds = dataResult.getRootNode().getChildren();
            Node select = resultChilds.findChild(Long.toString(art.getArtifactID()));
            if (select != null) {
              dataResult.requestActive();
              dataResult.setSelectedNodes(new Node[] {select});
              fireViewerComplete();
            }
          }
        });
  }
  /**
   * Event handler to run when selection changed
   *
   * <p>TODO this needs to be revised
   *
   * @param oldNodes
   * @param newNodes
   */
  private void respondSelection(final Node[] oldNodes, final Node[] newNodes) {
    if (!Case.isCaseOpen()) {
      // handle in-between condition when case is being closed
      // and legacy selection events are pumped
      return;
    }

    // Some lock that prevents certain Node operations is set during the
    // ExplorerManager selection-change, so we must handle changes after the
    // selection-change event is processed.
    // TODO find a different way to refresh data result viewer, scheduling this
    // to EDT breaks loading of nodes in the background
    EventQueue.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            // change the cursor to "waiting cursor" for this operation
            DirectoryTreeTopComponent.this.setCursor(
                Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            try {

              // make sure dataResult is open, redundant?
              // dataResult.open();

              Node treeNode = DirectoryTreeTopComponent.this.getSelectedNode();
              if (treeNode != null) {
                OriginalNode origin = treeNode.getLookup().lookup(OriginalNode.class);
                if (origin == null) {
                  return;
                }
                Node originNode = origin.getNode();

                // set node, wrap in filter node first to filter out children
                Node drfn = new DataResultFilterNode(originNode, DirectoryTreeTopComponent.this.em);
                Node kffn =
                    new KnownFileFilterNode(
                        drfn, KnownFileFilterNode.getSelectionContext(originNode));
                dataResult.setNode(new TableFilterNode(kffn, true));

                String displayName = "";
                Content content = originNode.getLookup().lookup(Content.class);
                if (content != null) {
                  try {
                    displayName = content.getUniquePath();
                  } catch (TskCoreException ex) {
                    logger.log(
                        Level.SEVERE,
                        "Exception while calling Content.getUniquePath() for node: "
                            + originNode); // NON-NLS
                  }
                } else if (originNode.getLookup().lookup(String.class) != null) {
                  displayName = originNode.getLookup().lookup(String.class);
                }
                dataResult.setPath(displayName);
              }

              // set the directory listing to be active
              if (oldNodes != null && newNodes != null && (oldNodes.length == newNodes.length)) {
                boolean sameNodes = true;
                for (int i = 0; i < oldNodes.length; i++) {
                  sameNodes = sameNodes && oldNodes[i].getName().equals(newNodes[i].getName());
                }
                if (!sameNodes) {
                  dataResult.requestActive();
                }
              }
            } finally {
              setCursor(null);
            }
          }
        });

    // update the back and forward list
    updateHistory(em.getSelectedNodes());
  }