Ejemplo n.º 1
0
 /**
  * @requires none
  * @modifies focusManager.focusblock && focusManager.focuspoint && blockCanvas
  * @effects Do nothing if "genusName" does not map to a valid block. Otherwise, create and add a
  *     new block with matching genus and label properties to one of the following: 1. the current
  *     block with focus at (0,0) relative to that block. 2. the current block with focus at next
  *     applicable socket location 3. the canvas at the last mouse click point. If label is not an
  *     empty string, then set the block label to that string. Then update any focus and block
  *     connections.
  */
 protected void automateBlockInsertion(
     Workspace workspace, TextualFactoryBlock block, String label) {
   TypeBlockManager typeBlockManager = workspace.getTypeBlockManager();
   if (!typeBlockManager.isEnabled()) {
     System.err.println("AutoMateBlockInsertion invoked but typeBlockManager is disabled.");
     return;
   }
   RenderableBlock createdRB = createRenderableBlock(block);
   // sets the label of the block to whatever the user typed (should only be numbers)
   if (label != EMPTY_LABEL_NAME) {
     createdRB.getBlock().setBlockLabel(label);
   }
   // changes the plus number labels back to +
   if (label.equals(NUMBER_PLUS_OPERATION_LABEL)) {
     createdRB.getBlock().setBlockLabel(PLUS_OPERATION_LABEL);
   }
   // changes the plus text labels back to +
   if (label.equals(TEXT_PLUS_OPERATION_LABEL)) {
     createdRB.getBlock().setBlockLabel(PLUS_OPERATION_LABEL);
   }
   if (createdRB == null) {
     return;
   } else {
     typeBlockManager.addBlock(createdRB);
   }
 }
Ejemplo n.º 2
0
  public void addLoadedBlocks(Collection<RenderableBlock> loadedBlocks, boolean importingPage) {
    for (RenderableBlock rb : loadedBlocks) {
      if (rb != null) {
        // add graphically
        getRBParent().addToBlockLayer(rb);
        rb.setHighlightParent(this.getRBParent());
        // System.out.println("loading rb to canvas: "+rb+" at: "+rb.getBounds());
        // add internallly
        workspace.notifyListeners(
            new WorkspaceEvent(workspace, this, rb.getBlockID(), WorkspaceEvent.BLOCK_ADDED));
        if (importingPage) {
          workspace.getEnv().getBlock(rb.getBlockID()).setFocus(false);
          rb.resetHighlight();
          rb.clearBufferedImage();
        }
      }
    }

    // now we need to redraw all the blocks now that all renderable blocks
    // within this page have been loaded, to update the socket dimensions of
    // blocks, etc.
    for (RenderableBlock rb : this.getTopLevelBlocks()) {
      rb.redrawFromTop();
      if (rb.isCollapsed()) {
        // This insures that blocks connected to a collapsed top level block
        // are located properly and have the proper visibility set.
        // This doesn't work until all blocks are loaded and dimensions are set.
        rb.updateCollapse();
      }
    }
    this.pageJComponent.revalidate();
    this.pageJComponent.repaint();
  }
Ejemplo n.º 3
0
  public Node getSaveNode(Document document) {
    Element pageElement = document.createElement("Page");

    pageElement.setAttribute("page-name", getPageName());
    pageElement.setAttribute(
        "page-color",
        getPageColor().getRed() + " " + getPageColor().getGreen() + " " + getPageColor().getBlue());
    pageElement.setAttribute("page-width", String.valueOf((int) getAbstractWidth()));
    if (fullview) {
      pageElement.setAttribute("page-infullview", "yes");
    } else {
      pageElement.setAttribute("page-infullview", "no");
    }
    if (pageDrawer != null) {
      pageElement.setAttribute("page-drawer", pageDrawer);
    }
    if (pageId != null) {
      pageElement.setAttribute("page-id", pageId);
    }

    // retrieve save strings of blocks within this Page
    Collection<RenderableBlock> blocks = this.getBlocks();
    if (blocks.size() > 0) {
      Element pageBlocksElement = document.createElement("PageBlocks");
      for (RenderableBlock rb : blocks) {
        pageBlocksElement.appendChild(rb.getSaveNode(document));
      }
      pageElement.appendChild(pageBlocksElement);
    }
    return pageElement;
  }
Ejemplo n.º 4
0
 /**
  * @param block - the textual block from which a new RenderableBlock will be constructed
  * @requires
  * @modifies nothing
  * @effects none
  * @return new RenderableBlock instance from the TextualFactoryBlock or null if not possible.
  */
 private RenderableBlock createRenderableBlock(TextualFactoryBlock block) {
   // if textual wrapper is null, return a null instance of RenderableBlock.
   if (block == null) {
     return null;
   }
   // if FactoryBlock wrapped in textual wrapper is invalid, return null RenderableBlock instance.
   if (block.getfactoryBlock() == null
       || block.getfactoryBlock().getBlockID().equals(Block.NULL)) {
     return null;
   }
   // create and get the RenderableBloc instance associated with the Textual wrapper's FactoryBlock
   RenderableBlock createdRB = block.getfactoryBlock().createNewInstance();
   // if the above instance of RenderableBlock is invalid (null or points to null)
   // then DO NOT insert a new block, DO NOT change the focus.
   if (createdRB == null || isNullBlockInstance(createdRB.getBlockID())) {
     throw new RuntimeException(
         "Invariant Violated:" + "May not drop null instances of Renderable Blocks");
   }
   // Please keep the above check rep because it does not
   // make any sense to have an exisitn valid
   // FactoryRenderableBlock point to some non-existing
   // block.  In other words, why would you have a factory
   // that churns out invalid products?
   return createdRB;
 }
Ejemplo n.º 5
0
  /**
   * @param childBlock
   * @param widget
   * @requires widget != null
   * @modifies
   * @effects Does nothing if: childBlock is invalid (null) Otherwise, remove childBlock from it's
   *     parent block if the childBlock has a parent. If it does not have a parent, do nothing.
   */
  private void disconnectBlock(Block childBlock, WorkspaceWidget widget) {
    if (childBlock == null || invalidBlockID(childBlock.getBlockID())) {
      return;
    }
    BlockConnector childPlug = BlockLinkChecker.getPlugEquivalent(childBlock);
    if (childPlug == null || !childPlug.hasBlock() || isNullBlockInstance(childPlug.getBlockID())) {
      return;
    }
    Block parentBlock = workspace.getEnv().getBlock(childPlug.getBlockID());
    BlockConnector parentSocket = parentBlock.getConnectorTo(childBlock.getBlockID());
    if (parentSocket == null) {
      return;
    }
    // disconector if child connector exists and has a block connected to it
    BlockLink link =
        BlockLink.getBlockLink(workspace, childBlock, parentBlock, childPlug, parentSocket);
    if (link == null) {
      return;
    }

    link.disconnect();

    RenderableBlock parentRenderable =
        workspace.getEnv().getRenderableBlock(parentBlock.getBlockID());
    if (parentRenderable == null) {
      throw new RuntimeException(
          "INCONSISTANCY VIOLATION: "
              + "parent block was valid, non-null, and existed.\n\tBut yet, when we get it's renderable"
              + "representation, we recieve a null instance.\n\tIf the Block instance of an ID is non-null"
              + "then its graphical RenderableBlock should be non-null as well");
    }
    parentRenderable.blockDisconnected(parentSocket);
    workspace.notifyListeners(
        new WorkspaceEvent(workspace, widget, link, WorkspaceEvent.BLOCKS_DISCONNECTED));
  }
Ejemplo n.º 6
0
 /**
  * @param workspace The workspace in use
  * @param genusName
  * @param label
  * @requires if (label != null) then associated block.isLabelEditable() should return true
  * @modifies focusManager.focusblock && focusManager.focuspoint && blockCanvas
  * @effects Do nothing if "genusName" does not map to a valid block. Otherwise, create and add a
  *     new block with matching genus and label properties to one of the following: 1. the current
  *     block with focus at (0,0) relative to that block. 2. the current block with focus at next
  *     applicable socket location 3. the canvas at the last mouse click point. Then update any
  *     focus and block connections.
  */
 protected void automateBlockInsertion(Workspace workspace, String genusName, String label) {
   TypeBlockManager typeBlockManager = workspace.getTypeBlockManager();
   if (!typeBlockManager.isEnabled()) {
     System.err.println("AutoMateBlockInsertion invoked but typeBlockManager is disabled.");
     return;
   }
   // if genus is null, DO NOT insert a new block, DO NOT change the focus
   if (genusName == null) {
     return;
   }
   // get matching textual Block
   RenderableBlock createdRB = BlockUtilities.getBlock(workspace, genusName, null);
   if (createdRB == null) {
     return;
   } else {
     // change name of block IF AN DONLY IFF a label was passed
     // and the block's label was editable and the block
     // does not need to have a unique label
     if (label != null
         && workspace.getEnv().getBlock(createdRB.getBlockID()).isLabelEditable()
         && !workspace.getEnv().getBlock(createdRB.getBlockID()).labelMustBeUnique()) {
       workspace.getEnv().getBlock(createdRB.getBlockID()).setBlockLabel(label);
     }
     // add block
     typeBlockManager.addBlock(createdRB);
   }
 }
Ejemplo n.º 7
0
 /**
  * @param renderable
  * @param widget
  * @param container
  * @requires renderable != null && renderable.blockID != null && renderable.blockID != Block.NULL
  *     && widget != null && container != null
  * @modifies renderable && children blocks connected to renderable
  * @effects removes renderable from container and widget and re-renders renderable block, widget,
  *     and container appropriately. Repeats for all of renderable's children.
  */
 private void removeBlock(
     RenderableBlock renderable, WorkspaceWidget widget, Container container) {
   widget.removeBlock(renderable);
   container.remove(renderable);
   container.validate();
   container.repaint();
   renderable.setParentWidget(null);
   // Workspace.getInstance().notifyListeners(new WorkspaceEvent(widget, renderable.getBlockID(),
   // WorkspaceEvent.BLOCK_REMOVED));
   for (BlockConnector child :
       BlockLinkChecker.getSocketEquivalents(
           workspace.getEnv().getBlock(renderable.getBlockID()))) {
     if (child == null || child.getBlockID().equals(Block.NULL)) {
       continue;
     }
     RenderableBlock childRenderable = workspace.getEnv().getRenderableBlock(child.getBlockID());
     if (childRenderable == null) {
       continue;
     }
     removeBlock(childRenderable, widget, container);
   }
   if (renderable.hasComment()) {
     renderable.removeComment();
   }
   workspace.notifyListeners(
       new WorkspaceEvent(
           workspace, widget, renderable.getBlockID(), WorkspaceEvent.BLOCK_REMOVED));
 }
Ejemplo n.º 8
0
 /** @overrides WorkspaceWidget.blockDropped() */
 @Override
 public void blockDropped(RenderableBlock block) {
   // add to view at the correct location
   Component oldParent = block.getParent();
   block.setLocation(
       SwingUtilities.convertPoint(oldParent, block.getLocation(), this.pageJComponent));
   addBlock(block);
   this.pageJComponent.setComponentZOrder(block, 0);
   this.pageJComponent.revalidate();
 }
Ejemplo n.º 9
0
  private void loadDefaultArdublockProgram() {
    /*
    InputStream defaultArdublockProgram = this.getClass().getResourceAsStream(DEFAULT_ARDUBLOCK_PROGRAM_PATH);

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          factory.setNamespaceAware(true);
          final DocumentBuilder builder;
          final Document doc;
    try
    {
    	builder = factory.newDocumentBuilder();
    	doc = builder.parse(defaultArdublockProgram);
    	final Element projectRoot = doc.getDocumentElement();
    	workspaceController.resetWorkspace();
    	workspaceController.loadProjectFromElement(projectRoot);
    }
    catch (ParserConfigurationException e)
    {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    }
    catch (SAXException e)
    {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    }
    catch (IllegalArgumentException e)
    {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    	workspaceController.loadFreshWorkspace();
    }
    catch (IOException e)
    {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    	workspaceController.loadFreshWorkspace();
    }
          */

    Workspace workspace = workspaceController.getWorkspace();
    Page page = workspace.getPageNamed("Main");

    FactoryManager manager = workspace.getFactoryManager();
    Block newBlock;
    newBlock = new Block(workspace, "loop", false);
    FactoryRenderableBlock factoryRenderableBlock =
        new FactoryRenderableBlock(workspace, manager, newBlock.getBlockID());
    RenderableBlock renderableBlock = factoryRenderableBlock.createNewInstance();
    renderableBlock.setLocation(100, 100);
    page.addBlock(renderableBlock);
  }
Ejemplo n.º 10
0
 /**
  * Helper method that recursively finds and removes all the blocks connected to the bottom of this
  * block, including this block.
  *
  * @param afterBlock - RenderableBlock we start removing at
  * @param widget - WorkspaceWidget that the block is using
  * @param container - Container the block is stored in
  */
 private void removeAfterBlock(
     RenderableBlock afterBlock, WorkspaceWidget widget, Container container) {
   if (workspace.getEnv().getBlock(afterBlock.getBlockID()).getAfterBlockID() != Block.NULL) {
     removeAfterBlock(
         workspace
             .getEnv()
             .getRenderableBlock(
                 workspace.getEnv().getBlock(afterBlock.getBlockID()).getAfterBlockID()),
         widget,
         container);
   }
   removeChildrenBlock(afterBlock, widget, container);
 }
Ejemplo n.º 11
0
  /**
   * This method serves to help clients sort blocks within a page in some manner.
   *
   * @param page
   * @param topLevelBlocks
   * @requires page != null && topLevelBlocks != null
   * @modifies the location of all topLevelBlocks
   * @effects sort the topLevelBlocks and move them to an order location on the page
   */
  protected static void sortBlockStacks(Page page, Collection<RenderableBlock> topLevelBlocks) {
    blocksToArrange.clear();
    positioningBounds.setBounds(
        BUFFER_BETWEEN_BLOCKS, BUFFER_BETWEEN_BLOCKS, 0, BUFFER_BETWEEN_BLOCKS);
    // created an ordered list of blocks based on x-coordinate position
    blocksToArrange.addAll(topLevelBlocks);

    // Naively places blocks from top to bottom, left to right.
    for (RenderableBlock block : blocksToArrange) {
      Rectangle bounds = block.getStackBounds();
      if (positioningBounds.height + bounds.height > page.getJComponent().getHeight()) {
        // need to go to next column
        positioningBounds.x = positioningBounds.x + positioningBounds.width + BUFFER_BETWEEN_BLOCKS;
        positioningBounds.width = 0;
        positioningBounds.height = BUFFER_BETWEEN_BLOCKS;
      }
      block.setLocation(positioningBounds.x, positioningBounds.height);

      // sets the x and y position for when workspace is unzoomed
      block.setUnzoomedX(block.calculateUnzoomedX(positioningBounds.x));
      block.setUnzoomedY(block.calculateUnzoomedY(positioningBounds.height));
      block.moveConnectedBlocks();

      // update positioning bounds
      positioningBounds.width = Math.max(positioningBounds.width, bounds.width);
      positioningBounds.height = positioningBounds.height + bounds.height + BUFFER_BETWEEN_BLOCKS;

      if (positioningBounds.x + positioningBounds.width > page.getJComponent().getWidth()) {
        // resize page to the difference
        page.addPixelWidth(
            positioningBounds.x + positioningBounds.width - page.getJComponent().getWidth());
      }
    }
  }
Ejemplo n.º 12
0
 /** @overrides ISupportMomento.getState */
 @Override
 public Object getState() {
   PageState state = new PageState();
   // Populate basic page information
   state.name = getPageName();
   state.id = getPageId();
   state.color = getPageColor();
   state.width = this.pageJComponent.getWidth();
   // Fill in block information
   for (RenderableBlock rb : this.getBlocks()) {
     state.renderableBlocks.put(rb.getBlockID(), rb.getState());
   }
   return state;
 }
Ejemplo n.º 13
0
 //////////////////////////
 // SAVING AND LOADING	//
 //////////////////////////
 public ArrayList<RenderableBlock> loadPageFrom(Node pageNode, boolean importingPage) {
   // note: this code is duplicated in BlockCanvas.loadSaveString().
   NodeList pageChildren = pageNode.getChildNodes();
   Node pageChild;
   ArrayList<RenderableBlock> loadedBlocks = new ArrayList<RenderableBlock>();
   HashMap<Long, Long> idMapping = importingPage ? new HashMap<Long, Long>() : null;
   if (importingPage) {
     reset();
   }
   for (int i = 0; i < pageChildren.getLength(); i++) {
     pageChild = pageChildren.item(i);
     if (pageChild.getNodeName().equals("PageBlocks")) {
       NodeList blocks = pageChild.getChildNodes();
       Node blockNode;
       for (int j = 0; j < blocks.getLength(); j++) {
         blockNode = blocks.item(j);
         RenderableBlock rb = RenderableBlock.loadBlockNode(workspace, blockNode, this, idMapping);
         // save the loaded blocks to add later
         loadedBlocks.add(rb);
       }
       break; // should only have one set of page blocks
     }
   }
   return loadedBlocks;
 }
Ejemplo n.º 14
0
 /**
  * @return a collection of top level blocks within this page (blocks with no parents that and are
  *     the first block of each stack) or an empty collection if no blocks are found on this page.
  */
 public Collection<RenderableBlock> getTopLevelBlocks() {
   List<RenderableBlock> topBlocks = new ArrayList<RenderableBlock>();
   for (RenderableBlock renderable : this.getBlocks()) {
     Block block = workspace.getEnv().getBlock(renderable.getBlockID());
     if (block.getPlug() == null
         || block.getPlugBlockID() == null
         || block.getPlugBlockID().equals(Block.NULL)) {
       if (block.getBeforeConnector() == null
           || block.getBeforeBlockID() == null
           || block.getBeforeBlockID().equals(Block.NULL)) {
         topBlocks.add(renderable);
         continue;
       }
     }
   }
   return topBlocks;
 }
Ejemplo n.º 15
0
  /**
   * @param newName - the new name of this page.
   * @requires newName != null
   * @modifies this.name
   * @effects sets the name of this page to be newName.
   */
  public void setPageName(String newName) {
    if (pageDrawer.equals(this.pageJComponent.getName())) {
      pageDrawer = newName;
    }

    this.pageJComponent.setName(newName);
    this.collapse.setText(newName);

    // iterate through blocks and update the ones that are page label enabled
    for (RenderableBlock block : this.getBlocks()) {
      if (workspace.getEnv().getBlock(block.getBlockID()).isPageLabelSetByPage()) {
        workspace.getEnv().getBlock(block.getBlockID()).setPageLabel(this.getPageName());
        block.repaintBlock();
      }
    }

    PageChangeEventManager.notifyListeners();
  }
Ejemplo n.º 16
0
 @Override
 public int compare(RenderableBlock rb1, RenderableBlock rb2) {
   if (rb1 == rb2) {
     return 0;
   } else {
     // translate points to a common reference: the parent of rb1
     Point pt1 = rb1.getLocation();
     Point pt2 =
         SwingUtilities.convertPoint(
             rb2.getParentWidget().getJComponent(),
             rb2.getLocation(),
             rb1.getParentWidget().getJComponent());
     if (pt1.getY() < pt2.getY()) {
       return -1;
     } else {
       return 1;
     }
   }
 }
Ejemplo n.º 17
0
  /**
   * @param block
   * @requires block must be a valid block. That is, block may not be such that block == null ||
   *     block.getBlockID() == null || block.getBlockID() == Block.NULL || block.getBlockID() == -1
   *     || Block.getBlock(block.getBlockID()) == null ||
   *     Block.getBlock(block.getBlockID()).getGenusName() == null ||
   *     Block.getBlock(block.getBlockID()).getGenusName().length() == 0 ||
   *     Block.getBlock(block.getBlockID()).getBlockLabel() == null
   * @modifies Objects modified by this method is undefined
   * @effects The effects of this method is unknown
   */
  private void addBlock(RenderableBlock block) {
    // check invariant
    if (block == null
        || block.getBlockID() == null
        || block.getBlockID().equals(Block.NULL)
        || workspace.getEnv().getBlock(block.getBlockID()) == null
        || workspace.getEnv().getBlock(block.getBlockID()).getGenusName() == null
        || workspace.getEnv().getBlock(block.getBlockID()).getGenusName().length() == 0
        || workspace.getEnv().getBlock(block.getBlockID()).getBlockLabel() == null) {
      throw new RuntimeException(
          "Invariant Violated: may not pass an invalid instance of renderabel block");
    }

    // ignore default arguments
    block.ignoreDefaultArguments();
    this.blockCanvas.getCanvas().add(block, 0);
    block.setLocation(0, 0);
    Long parentBlockID = this.focusManager.getFocusBlockID();
    if (invalidBlockID(parentBlockID)) {
      new BlockDropAnimator(
          workspace,
          this.focusManager.getCanvasPoint(),
          block,
          workspace.getEnv().getRenderableBlock(parentBlockID));
    } else {
      RenderableBlock parentBlock = workspace.getEnv().getRenderableBlock(parentBlockID);
      new BlockDropAnimator(
          workspace,
          SwingUtilities.convertPoint(
              parentBlock, this.focusManager.getBlockPoint(), this.blockCanvas.getCanvas()),
          block,
          workspace.getEnv().getRenderableBlock(parentBlockID));
    }
    this.focusManager.setFocus(block.getBlockID());
  }
Ejemplo n.º 18
0
 private void removeChildrenBlock(
     RenderableBlock renderable, WorkspaceWidget widget, Container container) {
   widget.removeBlock(renderable);
   container.remove(renderable);
   container.validate();
   container.repaint();
   renderable.setParentWidget(null);
   // Workspace.getInstance().notifyListeners(new WorkspaceEvent(widget, renderable.getBlockID(),
   // WorkspaceEvent.BLOCK_REMOVED));
   for (BlockConnector child : workspace.getEnv().getBlock(renderable.getBlockID()).getSockets()) {
     if (child == null || child.getBlockID().equals(Block.NULL)) {
       continue;
     }
     RenderableBlock childRenderable = workspace.getEnv().getRenderableBlock(child.getBlockID());
     if (childRenderable == null) {
       continue;
     }
     removeBlock(childRenderable, widget, container);
   }
   // If it is a procedure block, we want to delete the entire stack
   if (workspace.getEnv().getBlock(renderable.getBlockID()).isProcedureDeclBlock()) {
     if (workspace.getEnv().getBlock(renderable.getBlockID()).getAfterBlockID() != Block.NULL) {
       removeAfterBlock(
           workspace
               .getEnv()
               .getRenderableBlock(
                   workspace.getEnv().getBlock(renderable.getBlockID()).getAfterBlockID()),
           widget,
           container);
       this.disconnectBlock(
           workspace
               .getEnv()
               .getBlock(workspace.getEnv().getBlock(renderable.getBlockID()).getAfterBlockID()),
           widget);
     }
   }
   if (renderable.hasComment()) {
     renderable.removeComment();
   }
   workspace.notifyListeners(
       new WorkspaceEvent(
           workspace, widget, renderable.getBlockID(), WorkspaceEvent.BLOCK_REMOVED));
 }
Ejemplo n.º 19
0
 /** @overrides ISupportMomento.loadState() */
 @Override
 public void loadState(Object memento) {
   assert (memento instanceof PageState) : "ISupportMemento contract violated in Page";
   if (memento instanceof PageState) {
     PageState state = (PageState) memento;
     // load basic page information
     this.setPageName(state.name);
     this.setPageId(state.id);
     this.setPageColor(state.color);
     this.setPixelWidth(state.width);
     // Load block information
     Map<Long, Object> renderableBlockStates = state.renderableBlocks;
     List<Long> unloadedRenderableBlockStates = new LinkedList<Long>();
     List<Long> loadedBlocks = new LinkedList<Long>();
     for (Long id : renderableBlockStates.keySet()) {
       unloadedRenderableBlockStates.add(id);
     }
     // First, load all the blocks that are in the state to be loaded
     // against all the blocks that already exist.
     for (RenderableBlock existingBlock : getBlocks()) {
       Long existingBlockID = existingBlock.getBlockID();
       if (renderableBlockStates.containsKey(existingBlockID)) {
         existingBlock.loadState(renderableBlockStates.get(existingBlockID));
         unloadedRenderableBlockStates.remove(existingBlockID);
         loadedBlocks.add(existingBlockID);
       }
     }
     ArrayList<RenderableBlock> blocksToRemove = new ArrayList<RenderableBlock>();
     // Now, find all the blocks that don't exist in the save state and flag them to be removed.
     for (RenderableBlock existingBlock : this.getBlocks()) {
       Long existingBlockID = existingBlock.getBlockID();
       if (!loadedBlocks.contains(existingBlockID)) {
         blocksToRemove.add(existingBlock);
       }
     }
     // This loop is necessary to avoid a concurrent modification error that occurs
     // if the loop above removes the block while iterating over an unmodifiable
     // iterator.
     for (RenderableBlock toBeRemovedBlock : blocksToRemove) {
       this.removeBlock(toBeRemovedBlock);
     }
     // Finally, add all the remaining blocks that weren't there before
     ArrayList<RenderableBlock> blocksToAdd = new ArrayList<RenderableBlock>();
     for (Long newBlockID : unloadedRenderableBlockStates) {
       RenderableBlock newBlock = new RenderableBlock(workspace, this, newBlockID);
       newBlock.loadState(renderableBlockStates.get(newBlockID));
       blocksToAdd.add(newBlock);
     }
     this.addBlocks(blocksToAdd);
     this.pageJComponent.repaint();
   }
 }
Ejemplo n.º 20
0
  private void pasteStack(BlockNode node) {
    //		====================>>>>>>>>>>>>>>>>>>>>>>>>>
    //		====================focus coming in>>>>>>>>>> TODO
    //		====================>>>>>>>>>>>>>>>>>>>>>>>>>
    if (node == null) {
      return;
    }
    WorkspaceWidget widget = null;
    Iterable<WorkspaceWidget> widgets = null;
    Point spot = null;
    if (invalidBlockID(focusManager.getFocusBlockID())) {
      // canvas has focus
      Point location =
          SwingUtilities.convertPoint(
              this.blockCanvas.getCanvas(), this.focusManager.getCanvasPoint(), workspace);
      widget = workspace.getWidgetAt(location);
      spot =
          SwingUtilities.convertPoint(
              this.blockCanvas.getCanvas(),
              this.focusManager.getCanvasPoint(),
              widget.getJComponent());
    } else {
      RenderableBlock focusRenderable =
          workspace.getEnv().getRenderableBlock(focusManager.getFocusBlockID());
      widget = focusRenderable.getParentWidget();
      spot = focusRenderable.getLocation();
    }

    if (widget == null) {
      // TODO: To be examined and fixed, occurs on macs
      JOptionPane.showMessageDialog(
          frame, "Please click somewhere on the canvas first.", "Error", JOptionPane.PLAIN_MESSAGE);
      // throw new RuntimeException("Why are we adding a block to a null widget?");
    } else {
      // checks to see if the copied block still exists
      if (BlockUtilities.blockExists(workspace, node)) {
        // create mirror block and mirror childrens
        spot.translate(10, 10);
        RenderableBlock mirror = BlockUtilities.makeRenderable(workspace, node, widget);
        mirror.setLocation(spot);
        mirror.moveConnectedBlocks(); // make sure the childrens are placed correctly
      } else {
        // TODO: future version, allow them to paste
        JOptionPane.showMessageDialog(
            frame,
            "You cannot paste blocks that are currently NOT on the canvas."
                + "\nThis function will be available in a future version.\n",
            "Error",
            JOptionPane.PLAIN_MESSAGE);
      }
    }
  }
Ejemplo n.º 21
0
 public void highlightBlock(RenderableBlock block) {
   block.updateInSearchResults(true);
   highlightBlockSet.add(block);
 }
Ejemplo n.º 22
0
 public void cancelHighlightBlock(RenderableBlock block) {
   block.updateInSearchResults(false);
   highlightBlockSet.remove(block);
 }
Ejemplo n.º 23
0
  /** @overrides WorkspaceWidget.addBlock() */
  @Override
  public void addBlock(RenderableBlock block) {
    // update parent widget if dropped block
    WorkspaceWidget oldParent = block.getParentWidget();
    if (oldParent != this) {
      if (oldParent != null) {
        oldParent.removeBlock(block);
        if (block.hasComment()) {
          block.getComment().getParent().remove(block.getComment());
        }
      }
      block.setParentWidget(this);
      if (block.hasComment()) {
        block.getComment().setParent(block.getParentWidget().getJComponent());
      }
    }

    this.getRBParent().addToBlockLayer(block);
    block.setHighlightParent(this.getRBParent());

    // if block has page labels enabled, in other words, if it can, then set page label to this
    if (workspace.getEnv().getBlock(block.getBlockID()).isPageLabelSetByPage()) {
      workspace.getEnv().getBlock(block.getBlockID()).setPageLabel(this.getPageName());
    }

    // notify block to link default args if it has any
    block.linkDefArgs();

    // fire to workspace that block was added to canvas if oldParent != this
    if (oldParent != this) {
      workspace.notifyListeners(
          new WorkspaceEvent(workspace, oldParent, block.getBlockID(), WorkspaceEvent.BLOCK_MOVED));
      workspace.notifyListeners(
          new WorkspaceEvent(
              workspace, this, block.getBlockID(), WorkspaceEvent.BLOCK_ADDED, true));
    }

    // if the block is off the edge, shift everything or grow as needed to fully show it
    this.reformBlockPosition(block);

    this.pageJComponent.setComponentZOrder(block, 0);
  }
Ejemplo n.º 24
0
  /**
   * @param block - the new block being added whose position must be revalidated
   * @requires block != null
   * @modifies block.location or this page's abstract width
   * @effects shifts this block into the page or increases the width of this page to fit the new
   *     block. It must then notify listeners that the page's size may have changed
   */
  public void reformBlockPosition(RenderableBlock block) {
    // move blocks in
    Point p =
        SwingUtilities.convertPoint(block.getParent(), block.getLocation(), this.pageJComponent);
    if (p.x < block.getHighlightStrokeWidth() / 2 + 1) {
      block.setLocation(block.getHighlightStrokeWidth() / 2 + 1, p.y);
      block.moveConnectedBlocks();
      // the block has moved, so update p
      p = SwingUtilities.convertPoint(block.getParent(), block.getLocation(), this.pageJComponent);
    } else if (p.x + block.getWidth() + block.getHighlightStrokeWidth() / 2 + 1
        > this.pageJComponent.getWidth()) {
      this.setPixelWidth(p.x + block.getWidth() + block.getHighlightStrokeWidth() / 2 + 1);
    }

    if (p.y < block.getHighlightStrokeWidth() / 2 + 1) {
      block.setLocation(p.x, block.getHighlightStrokeWidth() / 2 + 1);
      block.moveConnectedBlocks();
    } else if (p.y + block.getStackBounds().height + block.getHighlightStrokeWidth() / 2 + 1
        > this.pageJComponent.getHeight()) {
      block.setLocation(
          p.x,
          this.pageJComponent.getHeight()
              - block.getStackBounds().height
              - block.getHighlightStrokeWidth() / 2
              + 1);
      block.moveConnectedBlocks();
    }

    if (block.hasComment()) {
      // p = SwingUtilities.convertPoint(block.getComment().getParent(),
      // block.getComment().getLocation(), this.pageJComponent);
      p = block.getComment().getLocation();
      if (p.x + block.getComment().getWidth() + 1 > this.pageJComponent.getWidth()) {
        this.setPixelWidth(p.x + block.getComment().getWidth() + 1);
      }
    }

    // repaint all pages
    PageChangeEventManager.notifyListeners();
  }
Ejemplo n.º 25
0
  /**
   * @modifies this.miniPixelWidth
   * @effects sets the minimumPixelWidth such that the following condition holds:
   *     DEFAULT_MINIMUMWIDTH < new minimumPixelWidth && for each block, b, in this page's set of
   *     blocks { b.x+b.width < new minimumPixelWidth}
   */
  public void reformMinimumPixelWidth() {
    minimumPixelWidth = 0; // reset min to 0

    // loop through blocks, growing min to fit each block
    for (RenderableBlock b : this.getBlocks()) {
      if (b.getX() + b.getWidth() + b.getHighlightStrokeWidth() / 2 > minimumPixelWidth) {
        // increase min width to fit this block
        minimumPixelWidth = b.getX() + b.getWidth() + b.getHighlightStrokeWidth() / 2 + 1;
      }

      if (b.hasComment()) {
        if (b.getComment().getX() + b.getComment().getWidth() > minimumPixelWidth) {
          // increase min width to fit this block
          minimumPixelWidth = b.getComment().getX() + b.getComment().getWidth() + 1;
        }
      }
    }
    if (this.minimumPixelWidth < Page.DEFAULT_MINUMUM_WIDTH * zoom) {
      this.minimumPixelWidth = (int) (Page.DEFAULT_MINUMUM_WIDTH * zoom);
    }
  }
Ejemplo n.º 26
0
 public void resetHightlightBlock() {
   for (RenderableBlock rb : highlightBlockSet) {
     rb.updateInSearchResults(false);
   }
   highlightBlockSet.clear();
 }
Ejemplo n.º 27
0
  /**
   * @requires the current block with focus must exist with non-null ID in a non-null widget with a
   *     non-null parent
   * @modifies the current block with focus
   * @effects removes the current block with focus and children from the GUI and destroys the link
   *     between the block with focus and it's parent block if one exist and children blocks if it
   *     has childrens.
   */
  private void deleteBlockAndChildren() {
    //		====================>>>>>>>>>>>>>>>>>>>>>>>>>
    //		====================focus coming in>>>>>>>>>>TODO
    //		====================>>>>>>>>>>>>>>>>>>>>>>>>>

    // Do not delete null block references.  Otherwise, get Block and RenderableBlock instances.
    if (isNullBlockInstance(focusManager.getFocusBlockID())) {
      throw new RuntimeException("TypeBlockManager: deleting a null block references.");
    }
    Block block = workspace.getEnv().getBlock(focusManager.getFocusBlockID());
    RenderableBlock renderable = workspace.getEnv().getRenderableBlock(block.getBlockID());

    // get workspace widget associated with current focus
    WorkspaceWidget widget = renderable.getParentWidget();
    // do not delete block instances in null widgets
    if (widget == null) {
      throw new RuntimeException("TypeBlockManager: do not delete blocks with no parent widget.");
      // return;
    }
    // get parent container of this graphical representation
    Container container = renderable.getParent();
    // do not delete block instances in null parents
    if (container == null) {
      throw new RuntimeException(
          "TypeBlockManager: do not delete blocks with no parent container.");
      // return;
    }
    // get the Block's location on the canvas
    Point location =
        SwingUtilities.convertPoint(renderable, new Point(0, 0), this.blockCanvas.getCanvas());

    // for every valid and active connection, disconnect it.
    Long parentID = null;
    if (validConnection(block.getPlug())) {
      parentID = block.getPlugBlockID();
      this.disconnectBlock(block, widget);
      if (validConnection(block.getAfterConnector())) {
        disconnectBlock(workspace.getEnv().getBlock(block.getAfterBlockID()), widget);
      }
    } else if (validConnection(block.getBeforeConnector())) {
      parentID = block.getBeforeBlockID();
      BlockConnector parentConnectorToBlock =
          workspace.getEnv().getBlock(parentID).getConnectorTo(block.getBlockID());
      this.disconnectBlock(block, widget);
      if (validConnection(block.getAfterConnector())) {
        Long afterBlockID = block.getAfterBlockID();
        disconnectBlock(workspace.getEnv().getBlock(afterBlockID), widget);
        if (parentID != null) {
          BlockLink link =
              BlockLinkChecker.canLink(
                  workspace,
                  workspace.getEnv().getBlock(parentID),
                  workspace.getEnv().getBlock(afterBlockID),
                  parentConnectorToBlock,
                  workspace.getEnv().getBlock(afterBlockID).getBeforeConnector());
          if (link != null) {
            link.connect();
            workspace.notifyListeners(
                new WorkspaceEvent(
                    workspace,
                    workspace.getEnv().getRenderableBlock(link.getPlugBlockID()).getParentWidget(),
                    link,
                    WorkspaceEvent.BLOCKS_CONNECTED));
            workspace.getEnv().getRenderableBlock(link.getPlugBlockID()).repaintBlock();
            workspace.getEnv().getRenderableBlock(link.getPlugBlockID()).repaint();
            workspace.getEnv().getRenderableBlock(link.getPlugBlockID()).moveConnectedBlocks();
            workspace.getEnv().getRenderableBlock(link.getSocketBlockID()).repaintBlock();
            workspace.getEnv().getRenderableBlock(link.getSocketBlockID()).repaint();
          }
        }
      }
    } else if (validConnection(block.getAfterConnector())) {
      parentID = block.getAfterBlockID();
    }

    // remove form widget and container
    this.removeChildrenBlock(renderable, widget, container);

    //		<<<<<<<<<<<<<<<<<<<<<<<<<<==========================
    //		<<<<<<<<<<<<<<<<<<<<<<<<<<focus changing, coming out TODO
    //		<<<<<<<<<<<<<<<<<<<<<<<<<<==========================
    // If the deleted block had a parent, give the parent the focus,
    // Otherwise, give the focus to the canvas (NOT BLOCK CANVAS)
    if (invalidBlockID(parentID)) {
      this.focusManager.setFocus(location, Block.NULL);
      this.blockCanvas.getCanvas().requestFocus();
      return;
    } else {
      this.focusManager.setFocus(parentID);
      this.blockCanvas.getCanvas().requestFocus();
      return;
    }
  }