From 605f6026bbf37856ee54741b8a0697337ca50039 Mon Sep 17 00:00:00 2001 From: poire-z Date: Sat, 18 Jan 2020 00:04:32 +0100 Subject: [PATCH] TextWidget: adds getFittedText() (#5776) bump base for xtext:getText(). --- base | 2 +- frontend/ui/widget/textwidget.lua | 51 +++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/base b/base index 4e068f89c..9751e5ae7 160000 --- a/base +++ b/base @@ -1 +1 @@ -Subproject commit 4e068f89c3d477996a97cb2bd537320a1e7c9a41 +Subproject commit 9751e5ae735ecaf6282b7b2c8982e41cca8ebedd diff --git a/frontend/ui/widget/textwidget.lua b/frontend/ui/widget/textwidget.lua index b98a461a3..c0ccac3c9 100644 --- a/frontend/ui/widget/textwidget.lua +++ b/frontend/ui/widget/textwidget.lua @@ -201,6 +201,57 @@ function TextWidget:_measureWithXText() end end +-- Returns the substring of text that fits in self.max_width +-- The substring does not include the ellipsis that could +-- be added when drawn. +-- 2nd returned value is nil if no truncation, false when truncated +-- and no ellipsis would be added, true if truncated and an ellipsis +-- will be added (on the right or left of string in logical order, +-- caller knows the side from the provided 'truncate_left'). +function TextWidget:getFittedText() + if not self.max_width then + return self.text, nil + end + self:updateSize() + if self._is_empty then + return "", nil + end + if not self.use_xtext then + if self._text_to_draw == self.text then + return self.text, nil + end + if not self.truncate_with_ellipsis then + return self._text_to_draw, false + end + -- ellipsis is 3 bytes + if self.truncate_left then + return self._text_to_draw:sub(3), true + else + return self._text_to_draw:sub(1, -4), true + end + end + if self._shape_start == 1 and self._shape_end == #self.text then + -- not truncated + return self.text, nil + end + local with_ellipsis = false + local start_idx, end_idx = self._shape_start, self._shape_end + if self._shape_idx_to_substitute_with_ellipsis then + with_ellipsis = true + if self.truncate_left then + start_idx = start_idx + 1 + else + end_idx = end_idx - 1 + end + end + -- These start and end indexes are in the internal unicode + -- string of the xtext object, and we can't use them as + -- indices of the UTF-8 self.text. + -- So, get the UTF-8 directly from xtext. + local text = self._xtext:getText(start_idx, end_idx) + return text, with_ellipsis +end + function TextWidget:getSize() self:updateSize() return Geom:new{