Jelajahi Sumber

:recycle: line input now has maximum input length of 40 characters

Felix Bytow 1 tahun lalu
induk
melakukan
878ff500dd
3 mengubah file dengan 24 tambahan dan 6 penghapusan
  1. 6 6
      game/AssetManager.cxx
  2. 16 0
      game/ui/LineInput.cxx
  3. 2 0
      game/ui/LineInput.hxx

+ 6 - 6
game/AssetManager.cxx

@@ -19,16 +19,16 @@ AssetManager::AssetManager(SDLRenderer& renderer)
 
   auto const current_path = fs::current_path();
   std::array const asset_paths{
-    current_path/"assets",
-    current_path.parent_path()/"assets",
-    current_path.parent_path()/"Resources"/"assets", // MacOS bundle
-    INSTALLED_ASSETS_PATH,
+      current_path/"assets",
+      current_path.parent_path()/"assets",
+      current_path.parent_path()/"Resources"/"assets", // MacOS bundle
+      INSTALLED_ASSETS_PATH,
   };
 
-  auto const it = std::ranges::find_if(asset_paths, [](fs::path const& p){
+  auto const it = std::ranges::find_if(asset_paths, [](fs::path const& p) {
     return fs::exists(p);
   });
-  if (it == std::end(asset_paths)) {
+  if (it==std::end(asset_paths)) {
     throw std::runtime_error("Assets directory not found.");
   }
 

+ 16 - 0
game/ui/LineInput.cxx

@@ -86,6 +86,22 @@ void LineInput::on_event(SDL_Event const& evt)
 
   if (evt.type==SDL_TEXTINPUT) {
     value_ += evt.text.text;
+    auto it = value_.begin();
+    auto const end = value_.end();
+    int len = 0;
+    // we assume valid UTF-8 here
+    while (it!=end && len<MAX_CHARACTERS) {
+      ++len;
+      if ((*it & 0x80)==0)
+        ++it;
+      else if ((*it & 0xE0)==0xC0)
+        std::advance(it, 2);
+      else if ((*it & 0xF0)==0xE0)
+        std::advance(it, 3);
+      else if ((*it & 0xF8)==0xF0)
+        std::advance(it, 4);
+    }
+    value_.erase(it, end);
   }
   else if (evt.type==SDL_KEYDOWN && evt.key.keysym.sym==SDLK_BACKSPACE) {
     if (!value_.empty()) {

+ 2 - 0
game/ui/LineInput.hxx

@@ -14,6 +14,8 @@ public:
   static int constexpr MIN_WIDTH = 16;
   static int constexpr MIN_HEIGHT = 15;
 
+  static int constexpr MAX_CHARACTERS = 40;
+
   LineInput(int x, int y, int w, int h, std::string value = "");
 
   void on_event(SDL_Event const& evt);