From f48ae0fffcd06f3cddd6cfc99b4c3d3a18c20038 Mon Sep 17 00:00:00 2001 From: yum Date: Tue, 27 Dec 2022 16:07:10 -0800 Subject: Encapsulate paging & text wrapping logic Define proper interfaces for these things. Simplify osc_ctrl, temporarily dropping support for emotes (they were broken anyway). * Bugfix: Japanese no longer crashes transcribe.py, but it still doesn't show up in the wxTextCtrl --- Scripts/text_wrapping.py | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Scripts/text_wrapping.py (limited to 'Scripts/text_wrapping.py') diff --git a/Scripts/text_wrapping.py b/Scripts/text_wrapping.py new file mode 100644 index 0000000..7576b78 --- /dev/null +++ b/Scripts/text_wrapping.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 + +class TextWrapper: + def __init__(self, rows, cols): + self.rows = rows + self.cols = cols + + # Split `msg` along line boundaries. Long words tend to just go onto new + # lines. Words that are too long to fit on any line are hyphenated and + # split. + # Lines are padded with space (" ") characters so they're all `self.cols` + # characters long. Pages are padded with lines full of space characters so + # they're all `self.rows` lines long. + def wrap(self, msg: str) -> list[list[str]]: + pages = [] + lines = [] + line = "" + for word in msg.split(): + if len(line) + 1 + len(word) <= self.cols: + if len(line): + line += " " + line += word + continue + # Word won't fit onto this line. End the line. + if len(line): + line += " " * (self.cols - len(line)) + lines.append(line) + line = "" + while len(word) > self.cols: + prefix = word[0:self.cols-1] + "-" + lines.append(prefix) + suffix = word[self.cols-1:] + word = suffix + if len(word): + line = word + if len(line): + line += " " * (self.cols - len(line)) + lines.append(line) + while len(lines): + pages.append(lines[0:self.rows]) + lines = lines[self.rows:] + if len(pages): + num_extra_lines = (self.rows - (len(pages[-1]) % self.rows)) % self.rows + pages[-1] += [" " * self.cols] * num_extra_lines + return pages + +if __name__ == "__main__": + w = TextWrapper(2, 5) + + assert(w.wrap("foo") == [["foo ", " "]]) + assert(w.wrap("foo bar") == [["foo ", "bar "]]) + assert(w.wrap("bagel") == [["bagel", " "]]) + assert(w.wrap("bagels") == [["bage-", "ls "]]) + assert(w.wrap("hot bagels") == [["hot ", "bage-"], ["ls ", " "]]) + -- cgit v1.2.3