From: Carl Hetherington Date: Sat, 25 Feb 2023 22:38:47 +0000 (+0100) Subject: Add word_wrap(). X-Git-Tag: v2.16.45~7 X-Git-Url: https://git.carlh.net/gitweb/?p=dcpomatic.git;a=commitdiff_plain;h=61614dcb37ce1bc3cf3fc2915ccac741cfef68e5 Add word_wrap(). --- 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 #include #include +#include #include #include #include @@ -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 diff --git a/test/util_test.cc b/test/util_test.cc index 872e6f885..49d0b3bc2 100644 --- a/test/util_test.cc +++ b/test/util_test.cc @@ -147,3 +147,11 @@ BOOST_AUTO_TEST_CASE (copy_in_bits_test) check_file ("build/test/random.dat", "build/test/random.dat2"); } } + + +BOOST_AUTO_TEST_CASE(word_wrap_test) +{ + BOOST_CHECK_EQUAL(word_wrap("hello world", 8), "hello \nworld\n"); + BOOST_CHECK(word_wrap("hello this is a longer bit of text and it should be word-wrapped", 31) == string{"hello this is a longer bit of \ntext and it should be word-\nwrapped\n"}); + BOOST_CHECK_EQUAL(word_wrap("hellocan'twrapthissadly", 5), "hello\ncan't\nwrapt\nhissa\ndly\n"); +}