diff options
| author | yum <yum.food.vr@gmail.com> | 2022-12-27 16:07:10 -0800 |
|---|---|---|
| committer | yum <yum.food.vr@gmail.com> | 2022-12-27 16:07:10 -0800 |
| commit | f48ae0fffcd06f3cddd6cfc99b4c3d3a18c20038 (patch) | |
| tree | 16c22867f2d7c51ac50efd74f042c615f8f35d0e /Scripts/text_wrapping.py | |
| parent | 3659518cb0ba5e8298d13215441a18ad8b275465 (diff) | |
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
Diffstat (limited to 'Scripts/text_wrapping.py')
| -rw-r--r-- | Scripts/text_wrapping.py | 55 |
1 files changed, 55 insertions, 0 deletions
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 ", " "]]) + |
