Beispiel #1
0
        CircuitPopup(Project proj, Tool tool, Circuit circuit) {
            super(_("circuitMenu"));
            this.proj = proj;
            this.circuit = circuit;

            add(editLayout); editLayout.addActionListener(this);
            add(editAppearance); editAppearance.addActionListener(this);
            add(analyze); analyze.addActionListener(this);
            add(stats); stats.addActionListener(this);
            addSeparator();
            add(main); main.addActionListener(this);
            add(remove); remove.addActionListener(this);

            boolean canChange = proj.getLogisimFile().contains(circuit);
            LogisimFile file = proj.getLogisimFile();
            if (circuit == proj.getCurrentCircuit()) {
                if (proj.getFrame().getEditorView().equals(Frame.EDIT_APPEARANCE)) {
                    editAppearance.setEnabled(false);
                } else {
                    editLayout.setEnabled(false);
                }
            }
            main.setEnabled(canChange && file.getMainCircuit() != circuit);
            remove.setEnabled(canChange && file.getCircuitCount() > 1
                    && proj.getDependencies().canRemove(circuit));
        }
  @Override
  public void doAction(Action canvasAction) {
    Circuit circuit = circuitState.getCircuit();
    if (!proj.getLogisimFile().contains(circuit)) {
      return;
    }

    if (canvasAction instanceof ModelReorderAction) {
      int max = getMaxIndex(getModel());
      ModelReorderAction reorder = (ModelReorderAction) canvasAction;
      List<ReorderRequest> rs = reorder.getReorderRequests();
      List<ReorderRequest> mod = new ArrayList<ReorderRequest>(rs.size());
      boolean changed = false;
      boolean movedToMax = false;
      for (ReorderRequest r : rs) {
        CanvasObject o = r.getObject();
        if (o instanceof AppearanceElement) {
          changed = true;
        } else {
          if (r.getToIndex() > max) {
            int from = r.getFromIndex();
            changed = true;
            movedToMax = true;
            if (from == max && !movedToMax) {
              // this change is ineffective - don't add it
            } else {
              mod.add(new ReorderRequest(o, from, max));
            }
          } else {
            if (r.getToIndex() == max) movedToMax = true;
            mod.add(r);
          }
        }
      }
      if (changed) {
        if (mod.isEmpty()) {
          return;
        }
        canvasAction = new ModelReorderAction(getModel(), mod);
      }
    }

    if (canvasAction instanceof ModelAddAction) {
      ModelAddAction addAction = (ModelAddAction) canvasAction;
      int cur = addAction.getDestinationIndex();
      int max = getMaxIndex(getModel());
      if (cur > max) {
        canvasAction = new ModelAddAction(getModel(), addAction.getObjects(), max + 1);
      }
    }

    proj.doAction(new CanvasActionAdapter(circuit, canvasAction));
  }
 @Override
 public void setValueRequested(Attribute<Object> attr, Object value)
         throws AttrTableSetException {
     if (!proj.getLogisimFile().contains(circ)) {
         String msg = _("cannotModifyCircuitError");
         throw new AttrTableSetException(msg);
     } else {
         SetAttributeAction act = new SetAttributeAction(circ,
                 __("changeAttributeAction"));
         act.set(comp, attr, value);
         proj.doAction(act);
     }
 }
Beispiel #4
0
 @Override
 public void mouseDragged(Canvas canvas, Graphics g, MouseEvent e) {
   if (state == MOVING) {
     Project proj = canvas.getProject();
     computeDxDy(proj, e, g);
     handleMoveDrag(canvas, curDx, curDy, e.getModifiersEx());
   } else if (state == RECT_SELECT) {
     Project proj = canvas.getProject();
     curDx = e.getX() - start.getX();
     curDy = e.getY() - start.getY();
     proj.repaintCanvas();
   }
 }
Beispiel #5
0
 @Override
 public void mouseReleased(Canvas canvas, Graphics g, MouseEvent e) {
   Project proj = canvas.getProject();
   if (state == MOVING) {
     setState(proj, IDLE);
     computeDxDy(proj, e, g);
     int dx = curDx;
     int dy = curDy;
     if (dx != 0 || dy != 0) {
       if (!proj.getLogisimFile().contains(canvas.getCircuit())) {
         canvas.setErrorMessage(Strings.getter("cannotModifyError"));
       } else if (proj.getSelection().hasConflictWhenMoved(dx, dy)) {
         canvas.setErrorMessage(Strings.getter("exclusiveError"));
       } else {
         boolean connect = shouldConnect(canvas, e.getModifiersEx());
         drawConnections = false;
         ReplacementMap repl;
         if (connect) {
           MoveGesture gesture = moveGesture;
           if (gesture == null) {
             gesture =
                 new MoveGesture(
                     new MoveRequestHandler(canvas),
                     canvas.getCircuit(),
                     canvas.getSelection().getAnchoredComponents());
           }
           canvas.setErrorMessage(new ComputingMessage(dx, dy), COLOR_COMPUTING);
           MoveResult result = gesture.forceRequest(dx, dy);
           clearCanvasMessage(canvas, dx, dy);
           repl = result.getReplacementMap();
         } else {
           repl = null;
         }
         Selection sel = proj.getSelection();
         proj.doAction(SelectionActions.translate(sel, dx, dy, repl));
       }
     }
     moveGesture = null;
     proj.repaintCanvas();
   } else if (state == RECT_SELECT) {
     Bounds bds = Bounds.create(start).add(start.getX() + curDx, start.getY() + curDy);
     Circuit circuit = canvas.getCircuit();
     Selection sel = proj.getSelection();
     Collection<Component> in_sel = sel.getComponentsWithin(bds, g);
     for (Component comp : circuit.getAllWithin(bds, g)) {
       if (!in_sel.contains(comp)) sel.add(comp);
     }
     Action act = SelectionActions.drop(sel, in_sel);
     if (act != null) {
       proj.doAction(act);
     }
     setState(proj, IDLE);
     proj.repaintCanvas();
   }
 }
Beispiel #6
0
  @Override
  public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) {
    Project proj = canvas.getProject();
    Selection sel = proj.getSelection();
    Circuit circuit = canvas.getCircuit();
    start = Location.create(e.getX(), e.getY());
    curDx = 0;
    curDy = 0;
    moveGesture = null;

    // if the user clicks into the selection,
    // selection is being modified
    Collection<Component> in_sel = sel.getComponentsContaining(start, g);
    if (!in_sel.isEmpty()) {
      if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) {
        setState(proj, MOVING);
        proj.repaintCanvas();
        return;
      } else {
        Action act = SelectionActions.drop(sel, in_sel);
        if (act != null) {
          proj.doAction(act);
        }
      }
    }

    // if the user clicks into a component outside selection, user
    // wants to add/reset selection
    Collection<Component> clicked = circuit.getAllContaining(start, g);
    if (!clicked.isEmpty()) {
      if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) {
        if (sel.getComponentsContaining(start).isEmpty()) {
          Action act = SelectionActions.dropAll(sel);
          if (act != null) {
            proj.doAction(act);
          }
        }
      }
      for (Component comp : clicked) {
        if (!in_sel.contains(comp)) {
          sel.add(comp);
        }
      }
      setState(proj, MOVING);
      proj.repaintCanvas();
      return;
    }

    // The user clicked on the background. This is a rectangular
    // selection (maybe with the shift key down).
    if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) {
      Action act = SelectionActions.dropAll(sel);
      if (act != null) {
        proj.doAction(act);
      }
    }
    setState(proj, RECT_SELECT);
    proj.repaintCanvas();
  }
  public void actionPerformed(ActionEvent e) {
    Object src = e.getSource();
    Project proj = menubar.getProject();
    if (src == newi) {
      ProjectActions.doNew(proj);
    } else if (src == merge) {
      ProjectActions.doMerge(proj == null ? null : proj.getFrame().getCanvas(), proj);
    } else if (src == open) {
      ProjectActions.doOpen(proj == null ? null : proj.getFrame().getCanvas(), proj);
    } else if (src == close) {
      int result = 0;
      Frame frame = proj.getFrame();
      if (proj.isFileDirty()) {
        /* Must use hardcoded strings here, because the string management is rotten */
        String message =
            "What should happen to your unsaved changes to " + proj.getLogisimFile().getName();
        String[] options = {"Save", "Discard", "Cancel"};
        result =
            JOptionPane.showOptionDialog(
                JOptionPane.getFrameForComponent(this),
                message,
                "Confirm Close",
                0,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[0]);

        if (result == 0) {
          ProjectActions.doSave(proj);
        }
      }

      /* If "cancel" pressed do nothing, otherwise dispose the window, opening one if this was the last opened window */
      if (result != 2) {
        // Get the list of open projects
        List<Project> pl = Projects.getOpenProjects();
        if (pl.size() == 1) {
          // Since we have a single window open, before closing the
          // current
          // project open a new empty one
          ProjectActions.doNew(proj);
        }

        // Close the current project
        frame.dispose();
        OptionsFrame f = proj.getOptionsFrame(false);
        if (f != null) f.dispose();
      }
    } else if (src == save) {
      ProjectActions.doSave(proj);
    } else if (src == saveAs) {
      ProjectActions.doSaveAs(proj);
    } else if (src == prefs) {
      PreferencesFrame.showPreferences();
    } else if (src == quit) {
      ProjectActions.doQuit();
    }
  }
Beispiel #8
0
    public void editingStopped(CaretEvent e) {
      if (e.getCaret() != caret) {
        e.getCaret().removeCaretListener(this);
        return;
      }
      caret.removeCaretListener(this);
      caretCircuit.removeCircuitListener(this);

      String val = caret.getText();
      boolean isEmpty = (val == null || val.equals(""));
      Action a;
      Project proj = caretCanvas.getProject();
      if (caretCreatingText) {
        if (!isEmpty) {
          CircuitMutation xn = new CircuitMutation(caretCircuit);
          xn.add(caretComponent);
          a = xn.toAction(Strings.getter("addComponentAction", Text.FACTORY.getDisplayGetter()));
        } else {
          a = null; // don't add the blank text field
        }
      } else {
        if (isEmpty && caretComponent.getFactory() instanceof Text) {
          CircuitMutation xn = new CircuitMutation(caretCircuit);
          xn.add(caretComponent);
          a = xn.toAction(Strings.getter("removeComponentAction", Text.FACTORY.getDisplayGetter()));
        } else {
          Object obj = caretComponent.getFeature(TextEditable.class);
          if (obj == null) { // should never happen
            a = null;
          } else {
            TextEditable editable = (TextEditable) obj;
            a = editable.getCommitAction(caretCircuit, e.getOldText(), e.getText());
          }
        }
      }

      caretCircuit = null;
      caretComponent = null;
      caretCreatingText = false;
      caret = null;

      if (a != null) proj.doAction(a);
    }
Beispiel #9
0
 @Override
 public void actionPerformed(ActionEvent e) {
     Object src = e.getSource();
     if (src == unload) {
         ProjectLibraryActions.doUnloadLibrary(proj, lib);
     } else if (src == reload) {
         Loader loader = proj.getLogisimFile().getLoader();
         loader.reload((LoadedLibrary) lib);
     }
 }
Beispiel #10
0
  private void computeDxDy(Project proj, MouseEvent e, Graphics g) {
    Bounds bds = proj.getSelection().getBounds(g);
    int dx;
    int dy;
    if (bds == Bounds.EMPTY_BOUNDS) {
      dx = e.getX() - start.getX();
      dy = e.getY() - start.getY();
    } else {
      dx = Math.max(e.getX() - start.getX(), -bds.getX());
      dy = Math.max(e.getY() - start.getY(), -bds.getY());
    }

    Selection sel = proj.getSelection();
    if (sel.shouldSnap()) {
      dx = Canvas.snapXToGrid(dx);
      dy = Canvas.snapYToGrid(dy);
    }
    curDx = dx;
    curDy = dy;
  }
Beispiel #11
0
 @Override
 public void actionPerformed(ActionEvent e) {
     Object source = e.getSource();
     if (source == editLayout) {
         proj.setCurrentCircuit(circuit);
         proj.getFrame().setEditorView(Frame.EDIT_LAYOUT);
     } else if (source == editAppearance) {
         proj.setCurrentCircuit(circuit);
         proj.getFrame().setEditorView(Frame.EDIT_APPEARANCE);
     } else if (source == analyze) {
         ProjectCircuitActions.doAnalyze(proj, circuit);
     } else if (source == stats) {
         JFrame frame = (JFrame) SwingUtilities.getRoot(this);
         StatisticsDialog.show(frame, proj.getLogisimFile(), circuit);
     } else if (source == main) {
         ProjectCircuitActions.doSetAsMainCircuit(proj, circuit);
     } else if (source == remove) {
         ProjectCircuitActions.doRemoveCircuit(proj, circuit);
     }
 }
Beispiel #12
0
	public void configureMenu(JPopupMenu menu, Project proj) {
		this.proj = proj;
		this.frame = proj.getFrame();
		this.circState = proj.getCircuitState();    
		
		Object attrs = instance.getAttributeSet();
		if (attrs instanceof RomAttributes) {
			((RomAttributes) attrs).setProject(proj);
		}

		boolean enabled = circState != null;
		edit = createItem(enabled, _("ramEditMenuItem"));
		clear = createItem(enabled, _("ramClearMenuItem"));
		load = createItem(enabled, _("ramLoadMenuItem"));
		save = createItem(enabled, _("ramSaveMenuItem"));

		menu.addSeparator();
		menu.add(edit);
		menu.add(clear);
		menu.add(load);
		menu.add(save);
	}
Beispiel #13
0
 public void actionPerformed(ActionEvent e) {
   Object src = e.getSource();
   Project proj = menubar.getProject();
   if (src == newi) {
     ProjectActions.doNew(proj);
   } else if (src == open) {
     ProjectActions.doOpen(proj == null ? null : proj.getFrame().getCanvas(), proj);
   } else if (src == close) {
     Frame frame = proj.getFrame();
     if (frame.confirmClose()) {
       frame.dispose();
       OptionsFrame f = proj.getOptionsFrame(false);
       if (f != null) f.dispose();
     }
   } else if (src == save) {
     ProjectActions.doSave(proj);
   } else if (src == saveAs) {
     ProjectActions.doSaveAs(proj);
   } else if (src == prefs) {
     PreferencesFrame.showPreferences();
   } else if (src == quit) {
     ProjectActions.doQuit();
   }
 }
Beispiel #14
0
	private void doLoad() {
		JFileChooser chooser = proj.createChooser();
		File oldSelected = factory.getCurrentImage(instance);
		if (oldSelected != null) chooser.setSelectedFile(oldSelected);
		chooser.setDialogTitle(_("ramLoadDialogTitle"));
		int choice = chooser.showOpenDialog(frame);
		if (choice == JFileChooser.APPROVE_OPTION) {
			File f = chooser.getSelectedFile();
			try {
				factory.loadImage(circState.getInstanceState(instance), f);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(frame, e.getMessage(),
						_("ramLoadErrorTitle"), JOptionPane.ERROR_MESSAGE);
			}
		}
	}
Beispiel #15
0
	private void doSave() {
		MemState s = factory.getState(instance, circState);

		JFileChooser chooser = proj.createChooser();
		File oldSelected = factory.getCurrentImage(instance);
		if (oldSelected != null) chooser.setSelectedFile(oldSelected);
		chooser.setDialogTitle(_("ramSaveDialogTitle"));
		int choice = chooser.showSaveDialog(frame);
		if (choice == JFileChooser.APPROVE_OPTION) {
			File f = chooser.getSelectedFile();
			try {
				HexFile.save(f, s.getContents());
				factory.setCurrentImage(instance, f);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(frame, e.getMessage(),
					_("ramSaveErrorTitle"), JOptionPane.ERROR_MESSAGE);
			}
		}
	}
Beispiel #16
0
  @Override
  public void mousePressed(Canvas canvas, Graphics g, MouseEvent e) {
    Project proj = canvas.getProject();
    Circuit circ = canvas.getCircuit();

    if (!proj.getLogisimFile().contains(circ)) {
      if (caret != null) caret.cancelEditing();
      canvas.setErrorMessage(Strings.getter("cannotModifyError"));
      return;
    }

    // Maybe user is clicking within the current caret.
    if (caret != null) {
      if (caret.getBounds(g).contains(e.getX(), e.getY())) { // Yes
        caret.mousePressed(e);
        proj.repaintCanvas();
        return;
      } else { // No. End the current caret.
        caret.stopEditing();
      }
    }
    // caret will be null at this point

    // Otherwise search for a new caret.
    int x = e.getX();
    int y = e.getY();
    Location loc = Location.create(x, y);
    ComponentUserEvent event = new ComponentUserEvent(canvas, x, y);

    // First search in selection.
    for (Component comp : proj.getSelection().getComponentsContaining(loc, g)) {
      TextEditable editable = (TextEditable) comp.getFeature(TextEditable.class);
      if (editable != null) {
        caret = editable.getTextCaret(event);
        if (caret != null) {
          proj.getFrame().viewComponentAttributes(circ, comp);
          caretComponent = comp;
          caretCreatingText = false;
          break;
        }
      }
    }

    // Then search in circuit
    if (caret == null) {
      for (Component comp : circ.getAllContaining(loc, g)) {
        TextEditable editable = (TextEditable) comp.getFeature(TextEditable.class);
        if (editable != null) {
          caret = editable.getTextCaret(event);
          if (caret != null) {
            proj.getFrame().viewComponentAttributes(circ, comp);
            caretComponent = comp;
            caretCreatingText = false;
            break;
          }
        }
      }
    }

    // if nothing found, create a new label
    if (caret == null) {
      if (loc.getX() < 0 || loc.getY() < 0) return;
      AttributeSet copy = (AttributeSet) attrs.clone();
      caretComponent = Text.FACTORY.createComponent(loc, copy);
      caretCreatingText = true;
      TextEditable editable = (TextEditable) caretComponent.getFeature(TextEditable.class);
      if (editable != null) {
        caret = editable.getTextCaret(event);
        proj.getFrame().viewComponentAttributes(circ, caretComponent);
      }
    }

    if (caret != null) {
      caretCanvas = canvas;
      caretCircuit = canvas.getCircuit();
      caret.addCaretListener(listener);
      caretCircuit.addCircuitListener(listener);
    }
    proj.repaintCanvas();
  }
Beispiel #17
0
  @Override
  public void draw(Canvas canvas, ComponentDrawContext context) {
    Project proj = canvas.getProject();
    int dx = curDx;
    int dy = curDy;
    if (state == MOVING) {
      proj.getSelection().drawGhostsShifted(context, dx, dy);

      MoveGesture gesture = moveGesture;
      if (gesture != null && drawConnections && (dx != 0 || dy != 0)) {
        MoveResult result = gesture.findResult(dx, dy);
        if (result != null) {
          Collection<Wire> wiresToAdd = result.getWiresToAdd();
          Graphics g = context.getGraphics();
          GraphicsUtil.switchToWidth(g, 3);
          g.setColor(Color.GRAY);
          for (Wire w : wiresToAdd) {
            Location loc0 = w.getEnd0();
            Location loc1 = w.getEnd1();
            g.drawLine(loc0.getX(), loc0.getY(), loc1.getX(), loc1.getY());
          }
          GraphicsUtil.switchToWidth(g, 1);
          g.setColor(COLOR_UNMATCHED);
          for (Location conn : result.getUnconnectedLocations()) {
            int connX = conn.getX();
            int connY = conn.getY();
            g.fillOval(connX - 3, connY - 3, 6, 6);
            g.fillOval(connX + dx - 3, connY + dy - 3, 6, 6);
          }
        }
      }
    } else if (state == RECT_SELECT) {
      int left = start.getX();
      int right = left + dx;
      if (left > right) {
        int i = left;
        left = right;
        right = i;
      }
      int top = start.getY();
      int bot = top + dy;
      if (top > bot) {
        int i = top;
        top = bot;
        bot = i;
      }

      Graphics gBase = context.getGraphics();
      int w = right - left - 1;
      int h = bot - top - 1;
      if (w > 2 && h > 2) {
        gBase.setColor(BACKGROUND_RECT_SELECT);
        gBase.fillRect(left + 1, top + 1, w - 1, h - 1);
      }

      Circuit circ = canvas.getCircuit();
      Bounds bds = Bounds.create(left, top, right - left, bot - top);
      for (Component c : circ.getAllWithin(bds)) {
        Location cloc = c.getLocation();
        Graphics gDup = gBase.create();
        context.setGraphics(gDup);
        c.getFactory()
            .drawGhost(context, COLOR_RECT_SELECT, cloc.getX(), cloc.getY(), c.getAttributeSet());
        gDup.dispose();
      }

      gBase.setColor(COLOR_RECT_SELECT);
      GraphicsUtil.switchToWidth(gBase, 2);
      if (w < 0) w = 0;
      if (h < 0) h = 0;
      gBase.drawRect(left, top, w, h);
    }
  }
  @Override
  public void computeEnabled() {
    Project proj = canvas.getProject();
    Circuit circ = canvas.getCircuit();
    Selection sel = canvas.getSelection();
    boolean selEmpty = sel.isEmpty();
    boolean canChange = proj.getLogisimFile().contains(circ);
    boolean clipExists = !Clipboard.isEmpty();
    boolean selHasRemovable = false;
    for (CanvasObject o : sel.getSelected()) {
      if (!(o instanceof AppearanceElement)) {
        selHasRemovable = true;
      }
    }
    boolean canRaise;
    boolean canLower;
    if (!selEmpty && canChange) {
      Map<CanvasObject, Integer> zs = ZOrder.getZIndex(sel.getSelected(), canvas.getModel());
      int zmin = Integer.MAX_VALUE;
      int zmax = Integer.MIN_VALUE;
      int count = 0;
      for (Map.Entry<CanvasObject, Integer> entry : zs.entrySet()) {
        if (!(entry.getKey() instanceof AppearanceElement)) {
          count++;
          int z = entry.getValue().intValue();
          if (z < zmin) zmin = z;
          if (z > zmax) zmax = z;
        }
      }
      int maxPoss = AppearanceCanvas.getMaxIndex(canvas.getModel());
      if (count > 0 && count <= maxPoss) {
        canRaise = zmin <= maxPoss - count;
        canLower = zmax >= count;
      } else {
        canRaise = false;
        canLower = false;
      }
    } else {
      canRaise = false;
      canLower = false;
    }
    boolean canAddCtrl = false;
    boolean canRemCtrl = false;
    Handle handle = sel.getSelectedHandle();
    if (handle != null && canChange) {
      CanvasObject o = handle.getObject();
      canAddCtrl = o.canInsertHandle(handle.getLocation()) != null;
      canRemCtrl = o.canDeleteHandle(handle.getLocation()) != null;
    }

    setEnabled(LogisimMenuBar.CUT, selHasRemovable && canChange);
    setEnabled(LogisimMenuBar.COPY, !selEmpty);
    setEnabled(LogisimMenuBar.PASTE, canChange && clipExists);
    setEnabled(LogisimMenuBar.DELETE, selHasRemovable && canChange);
    setEnabled(LogisimMenuBar.DUPLICATE, !selEmpty && canChange);
    setEnabled(LogisimMenuBar.SELECT_ALL, true);
    setEnabled(LogisimMenuBar.RAISE, canRaise);
    setEnabled(LogisimMenuBar.LOWER, canLower);
    setEnabled(LogisimMenuBar.RAISE_TOP, canRaise);
    setEnabled(LogisimMenuBar.LOWER_BOTTOM, canLower);
    setEnabled(LogisimMenuBar.ADD_CONTROL, canAddCtrl);
    setEnabled(LogisimMenuBar.REMOVE_CONTROL, canRemCtrl);
  }
Beispiel #19
0
  private void setState(Project proj, int new_state) {
    if (state == new_state) return; // do nothing if state not new

    state = new_state;
    proj.getFrame().getCanvas().setCursor(getCursor());
  }