Add Undo Redo support for the Note plugin (#5606)

Closes #5543
This commit is contained in:
ArthurTsvettsih
2018-09-24 09:05:46 +01:00
committed by Tomas Slusny
parent c0dfe2ec7c
commit ad15999b9c

View File

@@ -26,14 +26,19 @@
package net.runelite.client.plugins.notes;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import lombok.extern.slf4j.Slf4j;
import net.runelite.client.ui.ColorScheme;
import net.runelite.client.ui.PluginPanel;
@@ -42,6 +47,7 @@ import net.runelite.client.ui.PluginPanel;
class NotesPanel extends PluginPanel
{
private final JTextArea notesEditor = new JTextArea();
private final UndoManager undoRedo = new UndoManager();
void init(NotesConfig config)
{
@@ -68,6 +74,53 @@ class NotesPanel extends PluginPanel
String data = config.notesData();
notesEditor.setText(data);
// setting the limit to a 500 as UndoManager registers every key press,
// which means that be default we would be able to undo only a sentence.
// note: the default limit is 100
undoRedo.setLimit(500);
notesEditor.getDocument().addUndoableEditListener(e -> undoRedo.addEdit(e.getEdit()));
notesEditor.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
notesEditor.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
notesEditor.getActionMap().put("Undo", new AbstractAction("Undo")
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
if (undoRedo.canUndo())
{
undoRedo.undo();
}
}
catch (CannotUndoException ex)
{
log.warn("Notes Document Unable To Undo: " + ex);
}
}
});
notesEditor.getActionMap().put("Redo", new AbstractAction("Redo")
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
if (undoRedo.canRedo())
{
undoRedo.redo();
}
}
catch (CannotUndoException ex)
{
log.warn("Notes Document Unable To Redo: " + ex);
}
}
});
notesEditor.addFocusListener(new FocusListener()
{
@Override