javax.swing.undo.UndoableEdit Java Examples

The following examples show how to use javax.swing.undo.UndoableEdit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseDocumentEvent.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public @Override void die() {
       // Super of die()
int size = edits.size();
for (int i = size-1; i >= 0; i--)
{
    UndoableEdit e = (UndoableEdit)edits.elementAt(i);
    e.die();
}

       alive2 = false;
       // End super of die()
       
       if (previous != null) {
           previous.die();
           previous = null;
       }
   }
 
Example #2
Source File: StableCompoundEdit.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
   public String getUndoPresentationName() {
UndoableEdit last = lastEdit();
if (last != null) {
    return last.getUndoPresentationName();
} else {
           String name = getPresentationName();
           if (!"".equals(name)) {
               name = UIManager.getString("AbstractUndoableEdit.undoText")
                       + " " + name;
           } else {
               name = UIManager.getString("AbstractUndoableEdit.undoText");
           }

           return name;
}
   }
 
Example #3
Source File: ArcControllerTest.java    From PIPE with MIT License 6 votes vote down vote up
@Test
public void setWeightsCreatesHistoryItem() throws UnparsableException {
    Map<String, String> tokenWeights = new HashMap<>();
    String oldWeight = "5";
    when(mockArc.getWeightForToken(DEFAULT_TOKEN_ID)).thenReturn(oldWeight);


    String newWeight = "51";
    tokenWeights.put(DEFAULT_TOKEN_ID, newWeight);
    controller.setWeights(tokenWeights);

    UndoableEdit weightAction = new SetArcWeightAction<>(mockArc, DEFAULT_TOKEN_ID, oldWeight, newWeight);
    UndoableEdit edit = new MultipleEdit(Arrays.asList(weightAction));
    verify(listener).undoableEditHappened(argThat(Contains.thisAction(edit)));

}
 
Example #4
Source File: NbDocument.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static <T extends UndoableEdit> T getEditToBeUndoneRedoneOfType(EditorCookie ec, Class<T> type, boolean redone) {
    UndoRedo ur;
    if (ec instanceof CloneableEditorSupport &&
            ((ur = ((CloneableEditorSupport)ec).getUndoRedo()) instanceof UndoRedoManager))
    {
        UndoRedoManager urManager = (UndoRedoManager) ur;
        UndoableEdit edit = urManager.editToBeUndoneRedone(redone);
        if (type.isInstance(edit)) {
            return type.cast(edit);
        } else if (edit instanceof List) {
            @SuppressWarnings("unchecked")
            List<UndoableEdit> listEdit = (List<UndoableEdit>) edit;
            for (int i = listEdit.size() -1; i >= 0; i--) { // Go from most wrapped back
                edit = listEdit.get(i);
                if (type.isInstance(edit)) {
                    @SuppressWarnings("unchecked") T inst = (T) edit;
                    return inst;
                }
            }
        }
    }
    return null;
}
 
Example #5
Source File: FrmMain.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void jMenuItem_CutActionPerformed(ActionEvent evt) {
    VectorLayer layer = (VectorLayer) _mapDocument.getActiveMapFrame().getMapView().getSelectedLayer();
    List<Shape> selShapes = (List<Shape>)layer.getSelectedShapes();

    UndoableEdit edit = (new MapViewUndoRedo()).new RemoveFeaturesEdit(_mapView, layer, selShapes);
    currentUndoManager.addEdit(edit);
    this.refreshUndoRedo();

    for (Shape shape : selShapes) {
        layer.editRemoveShape(shape);
    }
    this.jButton_EditRemoveFeature.setEnabled(false);
    _mapView.paintLayers();

    ShapeSelection shapeSelection = new ShapeSelection(selShapes);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(shapeSelection, null);
}
 
Example #6
Source File: WrapUndoEdit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean replaceEdit(UndoableEdit anEdit) {
    if (undoRedoManager.isAtSavepoint()) { // Prohibit replacing at savepoint
        return false;
    }
    WrapUndoEdit wrapEdit = (WrapUndoEdit) anEdit;
    boolean replaced = delegate.replaceEdit(wrapEdit.delegate);
    undoRedoManager.checkLogOp("WrapUndoEdit.replaceEdit=" + replaced, anEdit);
    if (replaced) {
        undoRedoManager.checkReplaceSavepointEdit(wrapEdit, this);
    }
    return replaced;
}
 
Example #7
Source File: ExpectedDocumentContent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public UndoableEdit remove(int offset, int len) throws BadLocationException {
    checkBoundsInDoc(offset, len);
    UndoEdit edit = new UndoEdit(true, offset, getString(offset, len));
    removeEdit(edit);
    return edit;
}
 
Example #8
Source File: RateParameterControllerTest.java    From PIPE with MIT License 5 votes vote down vote up
@Test
public void setIdCreatesUndoItem() {
    String oldId = "id";
    String newId = "id2";
    when(rateParameter.getId()).thenReturn(oldId);

    rateParameterController.setId(newId);

    UndoableEdit changed = new ChangePetriNetComponentName(rateParameter, oldId, newId);
    verify(listener).undoableEditHappened(argThat(Contains.thisAction(changed)));
}
 
Example #9
Source File: MultipleEdit.java    From PIPE with MIT License 5 votes vote down vote up
/**
 * Redoes every action in the multiple edits
 */
@Override
public void redo() {
    super.redo();
    for (UndoableEdit edit : multipleEdits) {
        edit.redo();
    }
}
 
Example #10
Source File: GapContent.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes part of the content.
 *
 * @param where the starting position &gt;= 0, where + nitems &lt; length()
 * @param nitems the number of characters to remove &gt;= 0
 * @return an UndoableEdit object for undoing
 * @exception BadLocationException if the specified position is invalid
 * @see AbstractDocument.Content#remove
 */
public UndoableEdit remove(int where, int nitems) throws BadLocationException {
    if (where + nitems >= length()) {
        throw new BadLocationException("Invalid remove", length() + 1);
    }
    String removedString = getString(where, nitems);
    UndoableEdit edit = new RemoveUndo(where, removedString);
    replace(where, nitems, empty, 0);
    return edit;

}
 
Example #11
Source File: RateParameterController.java    From PIPE with MIT License 5 votes vote down vote up
/**
 * Tries to set the functional expression of the rate
 *
 * @param expression new functional expression
 * @throws InvalidRateException if the funcitonal expression is invalid because either it
 *                              contains a syntax error or it references a component that does not exist
 */
public void setRate(String expression) throws InvalidRateException {
    String oldRate = component.getExpression();
    if (!oldRate.equals(expression)) {
        FunctionalResults<Double> results = petriNet.parseExpression(expression);
        if (results.hasErrors()) {
            throw new InvalidRateException(results.getErrorString("\n"));
        }
        component.setExpression(expression);
        UndoableEdit rateAction = new ChangeRateParameterRate(component, oldRate, expression);
        registerUndoableEdit(rateAction);
    }

}
 
Example #12
Source File: ArcControllerTest.java    From PIPE with MIT License 5 votes vote down vote up
@Test
public void splittingCreatesHistoryItem() {
    ArcPoint nextPoint = new ArcPoint(new Point2D.Double(10, 10), false);
    ArcPoint splitPoint = new ArcPoint(new Point2D.Double(0, 0), true);

    when(mockArc.getNextPoint(splitPoint)).thenReturn(nextPoint);

    controller.splitArcPoint(splitPoint);
    ArcPoint expected = new ArcPoint(new Point2D.Double(5, 5), true);
    UndoableEdit addArcPointAction = new AddArcPathPoint<>(mockArc, expected);

    verify(listener).undoableEditHappened(argThat(Contains.thisAction(addArcPointAction)));
}
 
Example #13
Source File: DuplicateAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void duplicate(Node[] nodes, int dimension, int direction) {
    List<RADComponent> comps = FormUtils.getSelectedLayoutComponents(nodes);
    RADVisualContainer parent = (comps != null) ? getParent(comps) : null;
    if (parent != null) {
        FormModel formModel = parent.getFormModel();
        LayoutModel layoutModel = formModel.getLayoutModel();
        Object layoutUndoMark = layoutModel.getChangeMark();
        UndoableEdit layoutEdit = layoutModel.getUndoableEdit();
        boolean autoUndo = true; // in case of unexpected error, for robustness

        String[] sourceIds = new String[comps.size()];
        String[] targetIds = new String[comps.size()];
        int i = 0;
        MetaComponentCreator creator = formModel.getComponentCreator();
        try {
            for (RADComponent comp : comps) {
                RADComponent copiedComp = creator.copyComponent(comp, parent);
                if (copiedComp == null) {
                    return; // copy failed...
                }
                sourceIds[i] = comp.getId();
                targetIds[i] = copiedComp.getId();
                i++;
            }
            FormEditor.getFormDesigner(formModel).getLayoutDesigner()
                    .duplicateLayout(sourceIds, targetIds, dimension, direction);
            autoUndo = false;
        } finally {
            if (layoutUndoMark != null && !layoutUndoMark.equals(layoutModel.getChangeMark())) {
                formModel.addUndoableEdit(layoutEdit);
            }
            if (autoUndo) {
                formModel.forceUndoOfCompoundEdit();
            }
        }
    }
}
 
Example #14
Source File: GhidraScriptEditorComponentProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private KeyMasterTextArea(String text) {
	super(text);

	setFont(defaultFont);
	setName("EDITOR");
	setWrapStyleWord(false);
	Document document = getDocument();
	document.addUndoableEditListener(e -> {
		UndoableEdit item = e.getEdit();
		undoStack.push(item);
		redoStack.clear();
		updateUndoRedoAction();
	});
	setCaretPosition(0);
}
 
Example #15
Source File: GapContent.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes part of the content.
 *
 * @param where the starting position &gt;= 0, where + nitems &lt; length()
 * @param nitems the number of characters to remove &gt;= 0
 * @return an UndoableEdit object for undoing
 * @exception BadLocationException if the specified position is invalid
 * @see AbstractDocument.Content#remove
 */
public UndoableEdit remove(int where, int nitems) throws BadLocationException {
    if (where + nitems >= length()) {
        throw new BadLocationException("Invalid remove", length() + 1);
    }
    String removedString = getString(where, nitems);
    UndoableEdit edit = new RemoveUndo(where, removedString);
    replace(where, nitems, empty, 0);
    return edit;

}
 
Example #16
Source File: TransitionControllerTest.java    From PIPE with MIT License 5 votes vote down vote up
@Test
public void setNameCreatesUndoItem() {
    String oldName = "oldName";
    String newName = "newName";
    when(transition.getId()).thenReturn(oldName);
    controller.setId(newName);

    UndoableEdit nameEdit = new ChangePetriNetComponentName(transition, oldName, newName);
    verify(listener).undoableEditHappened(argThat(Contains.thisAction(nameEdit)));
}
 
Example #17
Source File: UndoRedoSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void startNewEdit (JTextComponent component, UndoableEdit atomicEdit) {
    if (edit != null) {
        // finish the last edit
        edit.end();
    }
    edit = new MyCompoundEdit();
    edit.addEdit(atomicEdit);
    super.undoableEditHappened(new UndoableEditEvent(component, edit));
    lastOffset = component.getCaretPosition();
    lastLength = component.getDocument().getLength();
}
 
Example #18
Source File: FrmMain.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void jMenuItem_InsertTitleActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    LayoutGraphic text = _mapDocument.getMapLayout().addText("Map Title", _mapDocument.getMapLayout().getWidth() / 2, 20, 12);
    _mapDocument.getMapLayout().paintGraphics();
    UndoableEdit edit = (new MapLayoutUndoRedo()).new AddElementEdit(_mapDocument.getMapLayout(), text);
    undoManager.addEdit(edit);
    this.refreshUndoRedo();
}
 
Example #19
Source File: GapContent.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Removes part of the content.
 *
 * @param where the starting position &gt;= 0, where + nitems &lt; length()
 * @param nitems the number of characters to remove &gt;= 0
 * @return an UndoableEdit object for undoing
 * @exception BadLocationException if the specified position is invalid
 * @see AbstractDocument.Content#remove
 */
public UndoableEdit remove(int where, int nitems) throws BadLocationException {
    if (where + nitems >= length()) {
        throw new BadLocationException("Invalid remove", length() + 1);
    }
    String removedString = getString(where, nitems);
    UndoableEdit edit = new RemoveUndo(where, removedString);
    replace(where, nitems, empty, 0);
    return edit;

}
 
Example #20
Source File: MultipleEdit.java    From PIPE with MIT License 5 votes vote down vote up
/**
 * Undoes every action in the multiple edits
 */
@Override
public void undo() {
    super.undo();

    for (UndoableEdit edit : multipleEdits) {
        edit.undo();
    }
}
 
Example #21
Source File: BaseDocument.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public @Override boolean replaceEdit(UndoableEdit anEdit) {
    if (nonSignificant) { // Non-significant edit must be replacing
        previousEdit = anEdit;
        // Becomes significant
        nonSignificant = false;
        return true;
    }
    if (!undoMergeReset && mergeEditIndex >= 0) { // Only merge if this edit contains BaseDocumentEvent child item
        List<UndoableEdit> thisEdits = getEdits();
        BaseDocumentEvent thisMergeEdit = (BaseDocumentEvent) thisEdits.get(mergeEditIndex);
        if (anEdit instanceof BaseDocument.AtomicCompoundEdit) {
            BaseDocument.AtomicCompoundEdit anAtomicEdit
                    = (BaseDocument.AtomicCompoundEdit)anEdit;
            List<UndoableEdit> anAtomicEditChildren = anAtomicEdit.getEdits();
            for (int i = 0; i < anAtomicEditChildren.size(); i++) {
                UndoableEdit child = (UndoableEdit)anAtomicEditChildren.get(i);
                if (child instanceof BaseDocumentEvent && thisMergeEdit.canMerge((BaseDocumentEvent)child)) {
                    previousEdit = anEdit;
                    return true;
                }
            }
        } else if (anEdit instanceof BaseDocumentEvent) {
            BaseDocumentEvent evt = (BaseDocumentEvent)anEdit;

            if (thisMergeEdit.canMerge(evt)) {
                previousEdit = anEdit;
                return true;
            }
        }
    }
    return false;
}
 
Example #22
Source File: EditorDocumentContent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public UndoableEdit insertString(int offset, String text) throws BadLocationException {
    if (text.length() == 0) {
        // Empty insert should be eliminated in parent (Document impl).
        // It could break MarkVector.insertUpdate() operation
        throw new IllegalArgumentException("EditorDocumentContent: Empty insert"); // NOI18N
    }
    checkOffsetInDoc(offset);
    InsertEdit insertEdit = new InsertEdit(this, offset, text);
    insertEdit(insertEdit, ""); // NOI18N
    return insertEdit;
}
 
Example #23
Source File: FormDesigner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void updateComponentLayer(final boolean fireChange) {
    if (formModel == null) { // the form can be closed just after opened, before this gets called (#70439)
        return;
    }
    if (getLayoutDesigner() == null) {
        return;
    }

    // Ensure that the components are laid out
    componentLayer.revalidate(); // Add componentLayer among components to validate
    RepaintManager.currentManager(componentLayer).validateInvalidComponents();

    LayoutModel layoutModel = formModel.getLayoutModel();
    // If after a change (FormModel has a compound edit started, i.e. it's not
    // just after form loaded) that was not primarily in layout, start undo
    // edit in LayoutModel as well: some changes can be done when updating to
    // actual visual state that was affected by changes elsewhere.
    UndoableEdit layoutUndoEdit = formModel.isCompoundEditInProgress()
                                  && !layoutModel.isUndoableEditInProgress()
            ? layoutModel.getUndoableEdit() : null;

    if (getLayoutDesigner().updateCurrentState() && fireChange) {
        formModel.fireFormChanged(true); // hack: to regenerate code once again
    }

    if (layoutModel.endUndoableEdit() && layoutUndoEdit != null) {
        formModel.addUndoableEdit(layoutUndoEdit);
    }

    updateResizabilityActions();
    componentLayer.repaint();
}
 
Example #24
Source File: FormDesigner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Aligns selected components in the specified direction.
 *
 * @param closed determines if closed group should be created.
 * @param dimension dimension to align in.
 * @param alignment requested alignment.
 */
void align(boolean closed, int dimension, int alignment) {
    // Check that the action is enabled
    Action action = null;
    Iterator iter = getDesignerActions(true).iterator();
    while (iter.hasNext()) {
        Action candidate = (Action)iter.next();
        if (candidate instanceof AlignAction) {
            AlignAction alignCandidate = (AlignAction)candidate;
            if ((alignCandidate.getAlignment() == alignment) && (alignCandidate.getDimension() == dimension)) {
                action = alignCandidate;
                break;
            }
        }
    }
    if ((action == null) || (!action.isEnabled())) {
        return;
    }
    Collection selectedIds = selectedLayoutComponentIds();
    RADComponent parent = commonParent(selectedIds);
    LayoutModel layoutModel = formModel.getLayoutModel();
    Object layoutUndoMark = layoutModel.getChangeMark();
    javax.swing.undo.UndoableEdit ue = layoutModel.getUndoableEdit();
    boolean autoUndo = true;
    try {
        getLayoutDesigner().align(selectedIds, closed, dimension, alignment);
        autoUndo = false;
    } finally {
        formModel.fireContainerLayoutChanged((RADVisualContainer)parent, null, null, null);
        if (!layoutUndoMark.equals(layoutModel.getChangeMark())) {
            formModel.addUndoableEdit(ue);
        }
        if (autoUndo) {
            formModel.forceUndoOfCompoundEdit();
        }
    }
}
 
Example #25
Source File: PropertiesEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Overrides superclass method. Adds StampFlag to UndoableEdit. */
        @Override
        public synchronized boolean addEdit(UndoableEdit anEdit) {
            stampFlags.put(anEdit, new StampFlag(System.currentTimeMillis(),
//                ((PropertiesDataObject)PropertiesEditorSupport.this.myEntry.getDataObject()).getOpenSupport().atomicUndoRedoFlag ));
                PropertiesEditorSupport.this.myEntry.atomicUndoRedoFlag ));
            return super.addEdit(anEdit);
        }
 
Example #26
Source File: InstantRefactoringPerformer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private UndoableEditDelegate(UndoableEdit ed, BaseDocument doc, InstantRefactoringPerformer performer) {
    DataObject dob = (DataObject) doc.getProperty(BaseDocument.StreamDescriptionProperty);
    this.ces = dob.getLookup().lookup(CloneableEditorSupport.class);
    this.inner = new CompoundEdit();
    this.inner.addEdit(ed);
    this.delegate = ed;
    this.performer = performer;
}
 
Example #27
Source File: ArcController.java    From PIPE with MIT License 5 votes vote down vote up
/**
 * Creates a historyItem for updating weight and applies it
 * @param token token id to associate the expression with
 * @param expr new weight expression for the arc
 * @return the UndoableEdit associated with this action
 */
private UndoableEdit updateWeightForArc(String token,
                                String expr) {
    String oldWeight = arc.getWeightForToken(token);
    arc.setWeight(token, expr);

    return new SetArcWeightAction<>(arc, token, oldWeight, expr);
}
 
Example #28
Source File: TransitionControllerTest.java    From PIPE with MIT License 5 votes vote down vote up
@Test
public void setRateCreatesRateUndoItemForRateParameter() {
    Rate oldRate = new NormalRate("1");
    when(transition.getRate()).thenReturn(oldRate);
    Rate rate = new FunctionalRateParameter("2", "foo", "foo");
    controller.setRate(rate);
    UndoableEdit rateEdit = new SetRateParameter(transition, oldRate, rate);
    verify(listener).undoableEditHappened(argThat(Contains.thisAction(rateEdit)));
}
 
Example #29
Source File: StableCompoundEdit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
   public String getPresentationName() {
UndoableEdit last = lastEdit();
if (last != null) {
    return last.getPresentationName();
} else {
    return "";
}
   }
 
Example #30
Source File: ModRootElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Reset modifications and start new accounting.
 * @param compoundEdit compound edit to add the resulting edit to. When null no adding is done.
 */
public void resetMods(UndoableEdit compoundEdit) {
    ResetModsEdit edit = new ResetModsEdit();
    if (compoundEdit != null) {
        compoundEdit.addEdit(edit);
    }
    edit.run();
}