Skip to content

Commit

Permalink
Implement backspace for UTF-8 strings
Browse files Browse the repository at this point in the history
  • Loading branch information
AJenbo committed Sep 23, 2021
1 parent 2887831 commit fcef839
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
6 changes: 2 additions & 4 deletions Source/DiabloUI/diabloui.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include "utils/sdl_wrap.h"
#include "utils/stubs.h"
#include "utils/language.h"
#include "utils/utf8.h"

#ifdef __SWITCH__
// for virtual keyboard on Switch
Expand Down Expand Up @@ -330,10 +331,7 @@ void UiFocusNavigation(SDL_Event *event)
#endif
case SDLK_BACKSPACE:
case SDLK_LEFT: {
int nameLen = strlen(UiTextInput);
if (nameLen > 0) {
UiTextInput[nameLen - 1] = '\0';
}
UiTextInput[FindLastUft8Symbols(UiTextInput)] = '\0';
return;
}
default:
Expand Down
5 changes: 2 additions & 3 deletions Source/control.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
#include "utils/language.h"
#include "utils/sdl_geometry.h"
#include "utils/stdcompat/optional.hpp"
#include "utils/utf8.h"
#include "options.h"

#ifdef _DEBUG
Expand Down Expand Up @@ -1822,9 +1823,7 @@ bool control_presskeys(int vkey)
} else if (vkey == DVL_VK_RETURN) {
ControlPressEnter();
} else if (vkey == DVL_VK_BACK) {
std::size_t len = strlen(TalkMessage);
if (len > 0)
TalkMessage[len - 1] = '\0';
TalkMessage[FindLastUft8Symbols(TalkMessage)] = '\0';
} else if (vkey == DVL_VK_DOWN) {
ControlUpDown(1);
} else if (vkey == DVL_VK_UP) {
Expand Down
18 changes: 18 additions & 0 deletions Source/utils/utf8.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,21 @@ inline const char *utf8_decode(const char *buf, uint32_t *c, int *e)

return reinterpret_cast<const char *>(next);
}

inline int FindLastUft8Symbols(const char *text)
{
std::string textBuffer(text);
textBuffer.resize(textBuffer.size() + 4); // Buffer must be padded before calling utf8_decode()
const char *textData = textBuffer.data();
const char *previousPosition = textData;

uint32_t next;
int error;
for (; *textData != '\0'; previousPosition = textData) {
textData = utf8_decode(textData, &next, &error);
if (*textData == '\0')
return previousPosition - textBuffer.data();
}

return 0;
}

0 comments on commit fcef839

Please sign in to comment.