Added CleanSourceActionListener.

This commit is contained in:
Andrew Lalis 2020-11-08 19:03:23 +01:00
parent 91ad9b191f
commit e5e3c08c6e
2 changed files with 54 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package nl.andrewlalis.blockbookbinder.control;
import nl.andrewlalis.blockbookbinder.view.SourceTextPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Listener for an action where the source text is 'cleaned' by removing any
* trailing whitespace, and removing unnecessary newlines.
*/
public class CleanSourceActionListener implements ActionListener {
private final SourceTextPanel sourceTextPanel;
public CleanSourceActionListener(SourceTextPanel sourceTextPanel) {
this.sourceTextPanel = sourceTextPanel;
}
@Override
public void actionPerformed(ActionEvent e) {
final String source = this.sourceTextPanel.getSourceText();
String updated = source.trim()
.replaceAll("(?>\\v)+(\\v)", "\n\n") // Replace large chunks of newline with just two.
.replace(" ", " "); // Remove any double spaces.
updated = this.removeNewlineWrapping(updated);
this.sourceTextPanel.setSourceText(updated);
}
private String removeNewlineWrapping(String source) {
final StringBuilder sb = new StringBuilder(source.length());
final char[] sourceChars = source.toCharArray();
for (int i = 0; i < sourceChars.length; i++) {
char c = sourceChars[i];
if (
c == '\n'
&& (i - 1 >= 0 && !Character.isWhitespace(sourceChars[i - 1]))
&& (i + 1 < sourceChars.length && !Character.isWhitespace(sourceChars[i + 1]))
) {
c = ' ';
}
sb.append(c);
}
return sb.toString();
}
}

View File

@ -1,5 +1,6 @@
package nl.andrewlalis.blockbookbinder.view;
import nl.andrewlalis.blockbookbinder.control.CleanSourceActionListener;
import nl.andrewlalis.blockbookbinder.control.ConvertToBookActionListener;
import javax.swing.*;
@ -38,9 +39,17 @@ public class SourceTextPanel extends JPanel {
JButton convertButton = new JButton("Convert to Book");
convertButton.addActionListener(new ConvertToBookActionListener(this, bookPreviewPanel));
rightPanelButtonPanel.add(convertButton);
JButton cleanButton = new JButton("Clean");
cleanButton.addActionListener(new CleanSourceActionListener(this));
rightPanelButtonPanel.add(cleanButton);
}
public String getSourceText() {
return this.textArea.getText();
}
public void setSourceText(String text) {
this.textArea.setText(text);
}
}