TextInput.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <utility>
  2. #include <GLFW/glfw3.h>
  3. #include "input/TextInput.h"
  4. TextInput::TextInput() : limit(256), active(false) {
  5. }
  6. void TextInput::setLimit(int limit) {
  7. TextInput::limit = limit;
  8. while(input.getLength() > limit) {
  9. input.removeBySwap(limit);
  10. }
  11. }
  12. void TextInput::reset() {
  13. input.clear();
  14. cursor = 0;
  15. }
  16. void TextInput::setActive(bool b) {
  17. active = b;
  18. }
  19. void TextInput::onKeyEvent(int key, int scancode, int action, int mods) {
  20. if(!active || action == GLFW_RELEASE) {
  21. return;
  22. }
  23. (void)scancode;
  24. (void)mods;
  25. switch(key) {
  26. case GLFW_KEY_BACKSPACE:
  27. if(input.getLength() > cursor - 1 && cursor > 0) {
  28. input.remove(cursor - 1);
  29. cursor--;
  30. }
  31. break;
  32. case GLFW_KEY_LEFT:
  33. if(cursor > 0) {
  34. cursor--;
  35. }
  36. break;
  37. case GLFW_KEY_RIGHT:
  38. if(cursor < input.getLength()) {
  39. cursor++;
  40. }
  41. break;
  42. }
  43. }
  44. void TextInput::onCharEvent(uint32 codepoint) {
  45. if(!active || input.getLength() >= limit) {
  46. return;
  47. }
  48. input.add(codepoint);
  49. for(int i = input.getLength() - 1; i > cursor; i--) {
  50. std::swap(input[i], input[i - 1]);
  51. }
  52. cursor++;
  53. }
  54. static uint32 read(int& index, const char* s) {
  55. if(s[index] == '\0') {
  56. return '\0';
  57. }
  58. return s[index++];
  59. }
  60. static uint32 readUnicode(int& index, const char* s) {
  61. uint32 c = read(index, s);
  62. if((c & 0xE0) == 0xC0) {
  63. c = ((c & 0x1F) << 6) | (read(index, s) & 0x3F);
  64. } else if((c & 0xF0) == 0xE0) {
  65. c = ((c & 0xF) << 12) | ((read(index, s) & 0x3F) << 6);
  66. c |= read(index, s) & 0x3F;
  67. } else if((c & 0xF8) == 0xF0) {
  68. c = ((c & 0x7) << 18) | ((read(index, s) & 0x3F) << 12);
  69. c |= (read(index, s) & 0x3F) << 6;
  70. c |= read(index, s) & 0x3F;
  71. }
  72. return c;
  73. }
  74. void TextInput::fill(const char* s) {
  75. int index = 0;
  76. reset();
  77. while(true) {
  78. uint32 c = readUnicode(index, s);
  79. if(c == '\0') {
  80. break;
  81. }
  82. onCharEvent(c);
  83. }
  84. }
  85. int TextInput::getCursor() const {
  86. return cursor;
  87. }