SerialMonitor: limit buffering without autoscroll

When the "autoscroll" checkbox is deselected the buffer may continue
to grow up to twice of the maximum size.

This is a compromise to ensure a better user experience and, at the
same time, reduce the chance to lose data and get "holes" in the
serial stream.

See #2491
This commit is contained in:
Cristian Maglie 2014-12-23 14:06:23 +01:00
parent 63f5d26ae9
commit 8e0a311e87
2 changed files with 25 additions and 11 deletions

View File

@ -69,7 +69,7 @@ public class SerialMonitor extends JFrame implements ActionListener {
Font editorFont = Preferences.getFont("editor.font");
Font font = new Font(consoleFont.getName(), consoleFont.getStyle(), editorFont.getSize());
textArea = new TextAreaFIFO(4000000);
textArea = new TextAreaFIFO(8000000);
textArea.setRows(16);
textArea.setColumns(40);
textArea.setEditable(false);
@ -244,11 +244,11 @@ public class SerialMonitor extends JFrame implements ActionListener {
final String s = consumeUpdateBuffer();
if (s.length() > 0) {
//System.out.println("gui append " + s.length());
boolean scroll = autoscrollBox.isSelected();
textArea.allowTrim(scroll);
textArea.append(s);
if (scroll) {
if (autoscrollBox.isSelected()) {
textArea.appendTrim(s);
textArea.setCaretPosition(textArea.getDocument().getLength());
} else {
textArea.appendNoTrim(s);
}
}
}

View File

@ -30,6 +30,7 @@ import javax.swing.text.BadLocationException;
public class TextAreaFIFO extends JTextArea implements DocumentListener {
private int maxChars;
private int trimMaxChars;
private int updateCount; // limit how often we trim the document
@ -37,15 +38,12 @@ public class TextAreaFIFO extends JTextArea implements DocumentListener {
public TextAreaFIFO(int max) {
maxChars = max;
trimMaxChars = max / 2;
updateCount = 0;
doTrim = true;
getDocument().addDocumentListener(this);
}
public void allowTrim(boolean trim) {
doTrim = trim;
}
public void insertUpdate(DocumentEvent e) {
if (++updateCount > 150 && doTrim) {
updateCount = 0;
@ -66,8 +64,8 @@ public class TextAreaFIFO extends JTextArea implements DocumentListener {
public void trimDocument() {
int len = 0;
len = getDocument().getLength();
if (len > maxChars) {
int n = len - maxChars;
if (len > trimMaxChars) {
int n = len - trimMaxChars;
//System.out.println("trimDocument: remove " + n + " chars");
try {
getDocument().remove(0, n);
@ -75,4 +73,20 @@ public class TextAreaFIFO extends JTextArea implements DocumentListener {
}
}
}
public void appendNoTrim(String s) {
int free = maxChars - getDocument().getLength();
if (free <= 0)
return;
if (s.length() > free)
append(s.substring(0, free));
else
append(s);
doTrim = false;
}
public void appendTrim(String str) {
append(str);
doTrim = true;
}
}