Final fix for utf8 CutText

This commit is contained in:
kamel5 2020-01-17 16:09:31 +01:00
parent 8db88c2556
commit 66a0c15aea
2 changed files with 32 additions and 6 deletions

37
tools.c
View File

@ -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();
}
}

View File

@ -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);