diff --git a/firmware/firmware.ino b/firmware/firmware.ino index 997b225..bbda449 100644 --- a/firmware/firmware.ino +++ b/firmware/firmware.ino @@ -31,21 +31,16 @@ String replaceMissingGlyphs(const String& text) { for (size_t index = 0; index < text.length();) { const uint8_t firstByte = static_cast(text[index]); - uint32_t codePoint = 0; size_t byteCount = 0; // UTF-8の先頭バイトから、1文字のバイト数を判定します。 if (firstByte < 0x80) { - codePoint = firstByte; byteCount = 1; } else if ((firstByte & 0xE0) == 0xC0 && index + 1 < text.length()) { - codePoint = firstByte & 0x1F; byteCount = 2; } else if ((firstByte & 0xF0) == 0xE0 && index + 2 < text.length()) { - codePoint = firstByte & 0x0F; byteCount = 3; } else if ((firstByte & 0xF8) == 0xF0 && index + 3 < text.length()) { - codePoint = firstByte & 0x07; byteCount = 4; } else { // 壊れたUTF-8も、表示できない文字としてトーフにします。 @@ -54,7 +49,7 @@ String replaceMissingGlyphs(const String& text) { continue; } - // 2バイト目以降をつなげて、Unicodeの文字コードを作ります。 + // 2バイト目以降がUTF-8の続きになっているか確認します。 bool valid = true; for (size_t offset = 1; offset < byteCount; ++offset) { const uint8_t nextByte = static_cast(text[index + offset]); @@ -62,7 +57,6 @@ String replaceMissingGlyphs(const String& text) { valid = false; break; } - codePoint = (codePoint << 6) | (nextByte & 0x3F); } if (!valid) { @@ -71,11 +65,15 @@ String replaceMissingGlyphs(const String& text) { continue; } + // 1文字分のUTF-8文字列を作ります。 + String character = text.substring(index, index + byteCount); + // 幅が0なら、その文字の絵がフォントにないと判断します。 - if (u8g2.getGlyphWidth(codePoint) == 0) { + // getGlyphWidthは使えるU8g2の版が限られるため、getUTF8Widthを使います。 + if (u8g2.getUTF8Width(character.c_str()) == 0) { result += "□"; } else { - result += text.substring(index, index + byteCount); + result += character; } index += byteCount; }