diff options
| author | Carl Hetherington <cth@carlh.net> | 2023-02-25 23:38:47 +0100 |
|---|---|---|
| committer | Carl Hetherington <cth@carlh.net> | 2023-03-03 01:17:41 +0100 |
| commit | 61614dcb37ce1bc3cf3fc2915ccac741cfef68e5 (patch) | |
| tree | d7aabdeb32a79bc12c863e607ecc1101684ad31f /src | |
| parent | 230e5c57553a8c19863bb1c9d0aa4136a359cf61 (diff) | |
Add word_wrap().
Diffstat (limited to 'src')
| -rw-r--r-- | src/lib/util.cc | 37 | ||||
| -rw-r--r-- | src/lib/util.h | 1 |
2 files changed, 38 insertions, 0 deletions
diff --git a/src/lib/util.cc b/src/lib/util.cc index 6ed66c40f..20a965781 100644 --- a/src/lib/util.cc +++ b/src/lib/util.cc @@ -47,6 +47,7 @@ #include "ratio.h" #include "rect.h" #include "render_text.h" +#include "scope_guard.h" #include "string_text.h" #include "text_decoder.h" #include "util.h" @@ -73,6 +74,7 @@ LIBDCP_ENABLE_WARNINGS #include <unicode/utypes.h> #include <unicode/unistr.h> #include <unicode/translit.h> +#include <unicode/brkiter.h> #include <boost/algorithm/string.hpp> #include <boost/range/algorithm/replace_if.hpp> #include <boost/thread.hpp> @@ -1079,3 +1081,38 @@ contains_assetmap(boost::filesystem::path dir) return boost::filesystem::is_regular_file(dir / "ASSETMAP") || boost::filesystem::is_regular_file(dir / "ASSETMAP.xml"); } + +string +word_wrap(string input, int columns) +{ + icu::Locale locale; + UErrorCode status = U_ZERO_ERROR; + auto iter = icu::BreakIterator::createLineInstance(locale, status); + ScopeGuard sg = [iter]() { delete iter; }; + if (U_FAILURE(status)) { + return input; + } + + auto input_icu = icu::UnicodeString::fromUTF8(icu::StringPiece(input)); + iter->setText(input_icu); + + int position = 0; + string output; + while (position < input_icu.length()) { + int end_of_line = iter->preceding(position + columns + 1); + icu::UnicodeString line; + if (end_of_line <= position) { + /* There's no good line-break position; just break in the middle of a word */ + line = input_icu.tempSubString(position, columns); + position += columns; + } else { + line = input_icu.tempSubString(position, end_of_line - position); + position = end_of_line; + } + line.toUTF8String(output); + output += "\n"; + } + + return output; +} + diff --git a/src/lib/util.h b/src/lib/util.h index d53fc06e0..4c8a2b1b7 100644 --- a/src/lib/util.h +++ b/src/lib/util.h @@ -95,5 +95,6 @@ extern boost::filesystem::path default_font_file (); extern void start_of_thread (std::string name); extern std::string error_details(boost::system::error_code ec); extern bool contains_assetmap(boost::filesystem::path dir); +extern std::string word_wrap(std::string input, int columns); #endif |
