Compare commits

...

7 Commits
1.12.2 ... main

14 changed files with 229 additions and 169 deletions

View File

@ -5,9 +5,11 @@ This application was developed in order to make the production of written books
## Using Block Book Binder
To get started, look for the [**Releases**](https://github.com/andrewlalis/BlockBookBinder/releases) section on this page, and find the latest release. Download the executable JAR file and you're ready to go. Simply paste some plain text into the _Source_ panel on the right-hand side, and press the button _Convert to Book_ to process that text into a series of pages which will appear on the left-hand side.
To get started, look for the [**Releases**](https://github.com/andrewlalis/BlockBookBinder/releases) section on this page, and find the latest release. Download the executable JAR file, and make sure you have Java version 17 or higher installed to run it.
Once you're happy with how the pages are formatted, you can click the _Export_ button to begin exporting pages to your clipboard. Once you give an affirmative response to the confirmation popup that appears, the first page will be loaded into your clipboard. You can then use `CTRL + V` to paste the page into your book. Each time you do, the program will take about a second to load the next page into your clipboard, so that you can paste it without even having to leave your game.
Start the program, and you'll be greeted with a window that has **Book Preview** and **Source Text** panels. Enter the text you'd like to work with into the **Source Text** panel. In the top menu under **Book**, you'll find a **Clean Source** button, which will remove extra whitespace from the text to make it more friendly for Minecraft's cramped style. You'll also find **Compile from Source**, which will compile your source text into a book in the **Book Preview** panel.
Once you're happy with how the pages are formatted, you can click the **Export to Minecraft** button to begin exporting pages to your clipboard.
## Demo Video on YouTube
https://youtu.be/Mu7Hv1na7Sw

13
pom.xml
View File

@ -6,11 +6,12 @@
<groupId>nl.andrewlalis</groupId>
<artifactId>BlockBookBinder</artifactId>
<version>1.2.0</version>
<version>1.3.1</version>
<properties>
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
@ -46,7 +47,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.14</version>
<version>1.18.28</version>
<scope>provided</scope>
</dependency>
@ -60,13 +61,13 @@
<dependency>
<groupId>com.formdev</groupId>
<artifactId>flatlaf</artifactId>
<version>1.0-rc3</version>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>3.6.3</version>
<version>3.9.3</version>
</dependency>
</dependencies>
</project>

View File

@ -1,7 +1,6 @@
package nl.andrewlalis.blockbookbinder;
import com.formdev.flatlaf.FlatDarkLaf;
import nl.andrewlalis.blockbookbinder.util.VersionReader;
import nl.andrewlalis.blockbookbinder.view.MainFrame;
import javax.swing.*;
@ -10,11 +9,9 @@ import javax.swing.*;
* The main class for the application.
*/
public class BlockBookBinder {
public static final String VERSION = VersionReader.getVersion();
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
FlatDarkLaf.install();
FlatDarkLaf.setup();
var mainFrame = new MainFrame();
mainFrame.setupAndShow();
});

View File

@ -27,7 +27,7 @@ public class ExportBookToMinecraftAction extends AbstractAction {
if (book == null || book.getPageCount() == 0) {
JOptionPane.showMessageDialog(
this.bookPreviewPanel.getRootPane(),
"Cannot export an empty book.",
"Cannot export an empty book.\nChoose \"Compile to Source\" first, and then export.",
"Empty Book",
JOptionPane.WARNING_MESSAGE
);

View File

@ -5,7 +5,7 @@ import org.jnativehook.keyboard.NativeKeyListener;
/**
* Native key listener that's used during the export process, to detect when the
* user performs certain key actions outside of the focus of this program.
* user performs certain key actions outside the focus of this program.
*/
public class ExporterKeyListener implements NativeKeyListener {
private final BookExporter exporterRunnable;

View File

@ -3,10 +3,12 @@ package nl.andrewlalis.blockbookbinder.control.source;
import lombok.Getter;
import lombok.Setter;
import nl.andrewlalis.blockbookbinder.model.build.BookBuilder;
import nl.andrewlalis.blockbookbinder.util.ApplicationProperties;
import nl.andrewlalis.blockbookbinder.view.SourceTextPanel;
import nl.andrewlalis.blockbookbinder.view.book.BookPreviewPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class CompileFromSourceAction extends AbstractAction {
@ -25,8 +27,22 @@ public class CompileFromSourceAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
this.bookPreviewPanel.setBook(
new BookBuilder().build(this.sourceTextPanel.getSourceText())
);
String text = this.sourceTextPanel.getSourceText();
if (text.isBlank()) {
JOptionPane.showMessageDialog(
SwingUtilities.getWindowAncestor((Component) e.getSource()),
"No source text to compile.\nEnter some text into the \"Source Text\" panel first.",
"No Source Text",
JOptionPane.WARNING_MESSAGE
);
} else {
this.bookPreviewPanel.setBook(
new BookBuilder(
ApplicationProperties.getIntProp("book.page_max_lines"),
ApplicationProperties.getIntProp("book.page_max_chars"),
ApplicationProperties.getIntProp("book.page_max_width")
).addText(this.sourceTextPanel.getSourceText()).build()
);
}
}
}

View File

@ -1,14 +1,27 @@
package nl.andrewlalis.blockbookbinder.control.source;
import lombok.Getter;
import lombok.Setter;
import nl.andrewlalis.blockbookbinder.BlockBookBinder;
import nl.andrewlalis.blockbookbinder.view.SourceTextPanel;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.prefs.Preferences;
public class ImportSourceAction extends AbstractAction {
@Getter
private static final ImportSourceAction instance = new ImportSourceAction();
@Setter
private SourceTextPanel sourceTextPanel;
public ImportSourceAction() {
super("Import Source");
this.putValue(SHORT_DESCRIPTION, "Import source text from a file.");
@ -16,6 +29,24 @@ public class ImportSourceAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
Preferences prefs = Preferences.userNodeForPackage(BlockBookBinder.class);
String dir = prefs.get("source-import-dir", ".");
JFileChooser fileChooser = new JFileChooser(dir);
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", ".txt"));
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.setMultiSelectionEnabled(false);
final Component parent = SwingUtilities.getWindowAncestor((Component) e.getSource());
int result = fileChooser.showOpenDialog(parent);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
Path filePath = file.toPath();
sourceTextPanel.setSourceText(Files.readString(filePath));
prefs.put("source-import-dir", filePath.getParent().toAbsolutePath().toString());
} catch (IOException exc) {
exc.printStackTrace();
JOptionPane.showMessageDialog(parent, "Failed to read file:\n" + exc.getMessage(), "Read Failed", JOptionPane.ERROR_MESSAGE);
}
}
}
}

View File

@ -17,8 +17,20 @@ public class CharWidthMapper {
this.initCharWidthMap();
}
public int getWidth(char c) {
return this.charWidthMap.getOrDefault(c, 6);
public static int getWidth(char c) {
return instance.charWidthMap.getOrDefault(c, 6);
}
public static int getWidth(String s) {
if (s.length() == 0) return 0;
int width = 0;
for (int i = 0; i < s.length(); i++) {
width += getWidth(s.charAt(i));
if (i < s.length() - 1) {
width++;
}
}
return width;
}
private void initCharWidthMap() {

View File

@ -3,112 +3,123 @@ package nl.andrewlalis.blockbookbinder.model.build;
import nl.andrewlalis.blockbookbinder.model.Book;
import nl.andrewlalis.blockbookbinder.model.BookPage;
import nl.andrewlalis.blockbookbinder.model.CharWidthMapper;
import nl.andrewlalis.blockbookbinder.util.ApplicationProperties;
import java.util.ArrayList;
import java.util.List;
public class BookBuilder {
/**
* Builds a full book of pages from the given source text.
* @param source The source text to convert.
* @return A book containing the source text formatted for a minecraft book.
*/
public Book build(String source) {
final int maxLines = ApplicationProperties.getIntProp("book.page_max_lines");
List<String> lines = this.convertSourceToLines(source);
Book book = new Book();
BookPage page = new BookPage();
int currentPageLineCount = 0;
private final int MAX_LINES_PER_PAGE;
private final int MAX_CHARS_PER_PAGE;
private final int MAX_LINE_PIXEL_WIDTH;
for (String line : lines) {
page.addLine(line);
currentPageLineCount++;
if (currentPageLineCount == maxLines) {
book.addPage(page);
page = new BookPage();
currentPageLineCount = 0;
}
}
private final List<String> lines;
if (page.hasContent()) {
book.addPage(page);
}
private final StringBuilder lineBuilder;
private final StringBuilder wordBuilder;
return book;
}
public BookBuilder(int maxLinesPerPage, int maxCharsPerPage, int maxLinePixelWidth) {
this.MAX_LINES_PER_PAGE = maxLinesPerPage;
this.MAX_CHARS_PER_PAGE = maxCharsPerPage;
this.MAX_LINE_PIXEL_WIDTH = maxLinePixelWidth;
this.lines = new ArrayList<>();
this.lineBuilder = new StringBuilder(64);
this.wordBuilder = new StringBuilder(64);
}
/**
* Converts the given source string into a formatted list of lines that can
* be copied to a minecraft book.
* @param source The source string.
* @return A list of lines.
*/
private List<String> convertSourceToLines(String source) {
List<String> lines = new ArrayList<>();
final char[] sourceChars = source.toCharArray();
final int maxLinePixelWidth = ApplicationProperties.getIntProp("book.page_max_width");
int sourceIndex = 0;
StringBuilder lineBuilder = new StringBuilder(64);
int linePixelWidth = 0;
StringBuilder symbolBuilder = new StringBuilder(64);
public BookBuilder addText(String text) {
int idx = 0;
while (idx < text.length()) {
final char c = text.charAt(idx++);
if (c == '\n') {
appendLine();
} else if (c == ' ' && lineBuilder.length() == 0) {
continue; // Skip spaces at the start of lines.
} else if (Character.isWhitespace(c)) {
if (CharWidthMapper.getWidth(lineBuilder.toString() + c) > MAX_LINE_PIXEL_WIDTH) {
appendLine();
if (c != ' ') {
lineBuilder.append(c);
}
} else {
lineBuilder.append(c);
}
} else { // Read a continuous word.
String word = readWord(text, idx - 1);
idx += word.length() - 1;
if (CharWidthMapper.getWidth(lineBuilder + word) <= MAX_LINE_PIXEL_WIDTH) {
// Append the word if it'll fit completely.
lineBuilder.append(word);
} else if (CharWidthMapper.getWidth(word) <= MAX_LINE_PIXEL_WIDTH) {
// Go to the next line and put the word there, since it'll fit.
appendLine();
lineBuilder.append(word);
} else {
// The word is so large that it doesn't fit on a line on its own.
// Find the largest substring of the word that'll fit with a hyphen.
int subStringSize = word.length() - 2;
while (CharWidthMapper.getWidth(word.substring(0, subStringSize) + "-") > MAX_LINE_PIXEL_WIDTH) {
subStringSize--;
}
appendLine();
lineBuilder.append(word, 0, subStringSize).append('-');
appendLine();
lineBuilder.append(word.substring(subStringSize));
}
}
}
return this;
}
while (sourceIndex < sourceChars.length) {
final char c = sourceChars[sourceIndex];
sourceIndex++;
symbolBuilder.setLength(0);
symbolBuilder.append(c);
int symbolWidth = CharWidthMapper.getInstance().getWidth(c);
public Book build() {
Book book = new Book();
BookPage page = new BookPage();
int currentPageLineCount = 0;
int currentPageCharCount = 0;
// Since there's a 1-pixel gap between characters, add it to the width if this isn't the first char.
if (lineBuilder.length() > 0) {
symbolWidth++;
}
// Flush anything remaining in lineBuilder to a final line.
if (lineBuilder.length() > 0) {
appendLine();
}
// If we encounter a non-newline whitespace at the beginning of the line, skip it.
if (c == ' ' && lineBuilder.length() == 0) {
continue;
}
for (String line : lines) {
if (currentPageCharCount + line.length() > MAX_CHARS_PER_PAGE) {
book.addPage(page);
page = new BookPage();
currentPageLineCount = 0;
currentPageCharCount = 0;
}
page.addLine(line);
currentPageLineCount++;
currentPageCharCount += line.length();
if (currentPageLineCount == MAX_LINES_PER_PAGE) {
book.addPage(page);
page = new BookPage();
currentPageLineCount = 0;
currentPageCharCount = 0;
}
}
if (page.hasContent()) {
book.addPage(page);
}
return book;
}
// If we encounter a newline, immediately skip to a new line.
if (c == '\n') {
lines.add(lineBuilder.toString());
lineBuilder.setLength(0);
linePixelWidth = 0;
continue;
}
private String readWord(String text, int firstCharIdx) {
wordBuilder.setLength(0);
int idx = firstCharIdx;
while (idx < text.length()) {
char c = text.charAt(idx++);
if (!Character.isWhitespace(c)) {
wordBuilder.append(c);
} else {
break;
}
}
return wordBuilder.toString();
}
// If we encounter a word, keep accepting characters until we reach the end.
if (Character.isLetterOrDigit(c)) {
while (
sourceIndex < sourceChars.length
&& Character.isLetterOrDigit(sourceChars[sourceIndex])
) {
char nextChar = sourceChars[sourceIndex];
symbolBuilder.append(nextChar);
symbolWidth += 1 + CharWidthMapper.getInstance().getWidth(nextChar);
sourceIndex++;
}
}
final String symbol = symbolBuilder.toString();
// Check if we need to go to the next line to fit the symbol.
if (linePixelWidth + symbolWidth > maxLinePixelWidth) {
lines.add(lineBuilder.toString());
lineBuilder.setLength(0);
linePixelWidth = 0;
}
// Finally, append the symbol.
lineBuilder.append(symbol);
linePixelWidth += symbolWidth;
}
// Append any remaining text.
if (lineBuilder.length() > 0) {
lines.add(lineBuilder.toString());
}
return lines;
}
private void appendLine() {
this.lines.add(this.lineBuilder.toString());
this.lineBuilder.setLength(0);
}
}

View File

@ -1,30 +0,0 @@
package nl.andrewlalis.blockbookbinder.util;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class VersionReader {
public static String getVersion() {
MavenXpp3Reader reader = new MavenXpp3Reader();
try {
Model model;
if ((new File("pom.xml")).exists()) {
model = reader.read(new FileReader("pom.xml"));
} else {
model = reader.read(new InputStreamReader(
VersionReader.class.getResourceAsStream("/META-INF/maven/nl.andrewlalis/BlockBookBinder/pom.xml")
));
}
return model.getVersion();
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
return "Unknown";
}
}
}

View File

@ -1,6 +1,5 @@
package nl.andrewlalis.blockbookbinder.view;
import nl.andrewlalis.blockbookbinder.BlockBookBinder;
import nl.andrewlalis.blockbookbinder.control.export.ExportBookToMinecraftAction;
import nl.andrewlalis.blockbookbinder.control.source.CleanSourceAction;
import nl.andrewlalis.blockbookbinder.control.source.CompileFromSourceAction;
@ -22,7 +21,7 @@ public class MainFrame extends JFrame {
ApplicationProperties.getIntProp("frame.default_width"),
ApplicationProperties.getIntProp("frame.default_height")
));
this.setTitle(ApplicationProperties.getProp("frame.title") + " Version " + BlockBookBinder.VERSION);
this.setTitle(ApplicationProperties.getProp("frame.title") + " Version " + ApplicationProperties.getProp("version"));
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final URL iconUrl = this.getClass().getClassLoader().getResource("images/book_and_quill.png");
if (iconUrl != null) {
@ -50,6 +49,7 @@ public class MainFrame extends JFrame {
doublePanel.add(sourceTextPanel);
CompileFromSourceAction.getInstance().setSourceTextPanel(sourceTextPanel);
CleanSourceAction.getInstance().setSourceTextPanel(sourceTextPanel);
ImportSourceAction.getInstance().setSourceTextPanel(sourceTextPanel);
mainPanel.add(doublePanel, BorderLayout.CENTER);

View File

@ -51,25 +51,32 @@ public class ExportToBookDialog extends JDialog {
private Container buildContentPane() {
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel setupPanel = new JPanel();
setupPanel.setLayout(new BoxLayout(setupPanel, BoxLayout.PAGE_AXIS));
JPanel setupPanel = new JPanel(new GridBagLayout());
String[] labels = {"", "First Page", "Last Page", "Auto-Paste Delay (Seconds)"};
this.autoCheckbox = new JCheckBox("Auto-paste", true);
this.firstPageSpinner = new JSpinner(new SpinnerNumberModel(1, 1, this.book.getPageCount(), 1));
JPanel firstPageSpinnerPanel = new JPanel(new BorderLayout());
firstPageSpinnerPanel.add(new JLabel("First Page:"), BorderLayout.WEST);
firstPageSpinnerPanel.add(this.firstPageSpinner, BorderLayout.CENTER);
this.lastPageSpinner = new JSpinner(new SpinnerNumberModel(this.book.getPageCount(), 1, this.book.getPageCount(), 1));
JPanel lastPageSpinnerPanel = new JPanel(new BorderLayout());
lastPageSpinnerPanel.add(new JLabel("Last Page:"), BorderLayout.WEST);
lastPageSpinnerPanel.add(this.lastPageSpinner, BorderLayout.CENTER);
this.autoPasteDelaySpinner = new JSpinner(new SpinnerNumberModel(0.2, 0.1, 5.0, 0.1));
JPanel autoPasteDelaySpinnerPanel = new JPanel(new BorderLayout());
autoPasteDelaySpinnerPanel.add(new JLabel("Auto-Paste Delay (s):"), BorderLayout.WEST);
autoPasteDelaySpinnerPanel.add(this.autoPasteDelaySpinner, BorderLayout.CENTER);
setupPanel.add(this.autoCheckbox);
setupPanel.add(firstPageSpinnerPanel);
setupPanel.add(lastPageSpinnerPanel);
setupPanel.add(autoPasteDelaySpinnerPanel);
JComponent[] fields = {autoCheckbox, firstPageSpinner, lastPageSpinner, autoPasteDelaySpinner};
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 0.5;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(5, 5, 5, 5);
for (String label : labels) {
setupPanel.add(new JLabel(label), c);
c.gridy++;
}
c.gridx = 1;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
for (JComponent field : fields) {
setupPanel.add(field, c);
c.gridy++;
}
this.exportStatusPanel = new ExportStatusPanel();
@ -191,9 +198,11 @@ public class ExportToBookDialog extends JDialog {
) {
JOptionPane.showMessageDialog(
this,
"Invalid page range. Please follow the rules below:\n" +
"1. First page must be lower or equal to the last page.\n" +
"2. Number of pages to export cannot exceed 100.\n",
"""
Invalid page range. Please follow the rules below:
1. First page must be lower or equal to the last page.
2. Number of pages to export cannot exceed 100.
""",
"Invalid Page Range",
JOptionPane.WARNING_MESSAGE
);

View File

@ -1,4 +1,4 @@
version=1.2.0
version=1.3.1
# Settings for the application's GUI.
frame.title=Block Book Binder
@ -19,5 +19,5 @@ about_dialog.source=html/about.html
book.max_pages=100
book.page_max_lines=14
book.page_max_width=113
book.page_max_chars=255
book.page_max_chars=700
book.default_char_width=5

View File

@ -9,15 +9,15 @@
<h1>About BlockBookBinder</h1>
<p>
The <em>BlockBookBinder</em> is a simple application that gives you the power to write books faster than ever before! All you need to do is copy and paste some text into the <em>Source</em> panel on the right-hand side of the application, and click <strong>Convert to Book</strong>. Your text will be transformed so that it can fit onto written books in Minecraft, and you can preview the book in the <em>Book Preview</em> panel on the left-hand side of the application, using the navigation buttons below.
The <em>BlockBookBinder</em> is a simple application that gives you the power to write books faster than ever before! All you need to do is copy and paste some text into the <em>Source</em> panel on the right-hand side of the application, and click <strong>Compile from Source</strong>. Your text will be transformed so that it can fit onto written books in Minecraft, and you can preview the book in the <em>Book Preview</em> panel on the left-hand side of the application, using the navigation buttons below.
</p>
<p><em>
Note that your text might benefit from the <strong>Clean</strong> functionality, where extra new-line and other unnecessary whitespace characters are removed so that the text can be better compressed into Minecraft's limited format.
Note that your text might benefit from the <strong>Clean Source</strong> functionality, where extra new-line and other unnecessary whitespace characters are removed so that the text can be better compressed into Minecraft's limited format.
</em></p>
<p>
Once you've prepared a book and you want to actually copy it into Minecraft, click on <strong>Export to Book</strong>. This will open up a popup with a few different buttons:
Once you've prepared a book and you want to actually copy it into Minecraft, click on <strong>Export to Minecraft</strong>. This will open up a popup with a few different buttons:
</p>
<ul>
@ -38,6 +38,17 @@
When all pages have been exported, you'll be prompted with a little popup, after which the export popup closes and you have the option to export again, or simply close the application if you're done.
</p>
<h3>Troubleshooting</h3>
<p>
This program works by hijacking your PC's input system to automatically transfer text to the system's clipboard, and then paste it by pressing <em>CTRL+V</em> for you. Because of the nature of such applications, there's no guarantee that this process will work on every computer. Here are some tips to try and get things working.
</p>
<ul>
<li>Try to increase the auto-paste delay to 1 second or more, if you notice some pages being skipped during the export process.</li>
<li>If the automated approach fails, you can always select and copy each page from the book preview.</li>
</ul>
<hr>
<p>