From 66a0c15aea3a37967310abfd3b34629808d02f84 Mon Sep 17 00:00:00 2001 From: kamel5 Date: Fri, 17 Jan 2020 16:09:31 +0100 Subject: [PATCH] Final fix for utf8 CutText --- tools.c | 37 +++++++++++++++++++++++++++++++------ tools.h | 1 + 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/tools.c b/tools.c index 229bf9e..04271d3 100644 --- a/tools.c +++ b/tools.c @@ -23,22 +23,47 @@ cPlugin *GetScraperPlugin(void) { /**************************************************************************************** * CUTTEXT ****************************************************************************************/ +std::string utf8_substr(const std::string& str, unsigned int start, long unsigned int leng) { + if (leng==0) { return ""; } + unsigned int c, i, ix, q; + long unsigned int min=std::string::npos, max=std::string::npos; + for (q=0, i=0, ix=str.length(); i < ix; i++, q++) { + if (q==start){ min=i; } + if (q<=start+leng || leng==std::string::npos){ max=i; } + + c = (unsigned char) str[i]; + if (c>=0 && c<=127) i+=0; + else if ((c & 0xE0) == 0xC0) i+=1; + else if ((c & 0xF0) == 0xE0) i+=2; + else if ((c & 0xF8) == 0xF0) i+=3; + //else if (($c & 0xFC) == 0xF8) i+=4; // 111110bb //byte 5, unnecessary in 4 byte UTF-8 + //else if (($c & 0xFE) == 0xFC) i+=5; // 1111110b //byte 6, unnecessary in 4 byte UTF-8 + else return "";//invalid utf8 + } + if (q<=start+leng || leng==std::string::npos){ max=i; } + if (min==std::string::npos || max==std::string::npos) { return ""; } + return str.substr(min,max); +} + std::string CutText(std::string text, int width, const cFont *font) { int actWidth = font->Width(text.c_str()); if (actWidth <= width) { return text.c_str(); } else { - int i = std::max((actWidth - width) / font->Size(), 1); + int i = std::max(width / font->Size(), 1) - 1; + std::string cuttext, oldtext; + cuttext = utf8_substr(text, 0, i); do { - text = text.substr(0, text.length() - i); + oldtext = cuttext; + i++; + cuttext = utf8_substr(text, 0, i); std::stringstream sstrText; - sstrText << text << "...."; + sstrText << cuttext << "..."; actWidth = font->Width(sstrText.str().c_str()); - i = 1; } - while ((actWidth > width) && (text.length() > 0)); + while (actWidth < width); std::stringstream sstrText2; - sstrText2 << text << "..."; + sstrText2 << oldtext << "..."; return sstrText2.str(); } } diff --git a/tools.h b/tools.h index 1ee6782..e09fc6d 100644 --- a/tools.h +++ b/tools.h @@ -9,6 +9,7 @@ cPlugin *GetScraperPlugin(void); +std::string utf8_substr(const std::string& str, unsigned int start=0, long unsigned int leng=std::string::npos); std::string CutText(std::string text, int width, const cFont *font); std::string StrToLowerCase(std::string str); std::string GetDirectoryFromTimer(std::string file);