Веб-сайт самохостера Lotigara

summaryrefslogtreecommitdiff
path: root/source/windowing/StarTextBoxWidget.cpp
blob: 5bcdfbf5a93d07340e416e511c818fe9e1044826 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#include "StarTextBoxWidget.hpp"
#include "StarRoot.hpp"
#include "StarJsonExtra.hpp"
#include "StarAssets.hpp"

namespace Star {

TextBoxWidget::TextBoxWidget(String const& startingText, String const& hint, WidgetCallbackFunc callback)
  : m_text(startingText), m_hint(hint), m_callback(callback) {
  auto assets = Root::singleton().assets();
  m_regex = ".*";
  m_repeatKeyThreshold = 0;
  m_repeatCode = SpecialRepeatKeyCodes::None;
  m_isPressed = false;
  m_isHover = false;
  m_cursorOffset = startingText.size();
  m_hAnchor = HorizontalAnchor::LeftAnchor;
  m_vAnchor = VerticalAnchor::BottomAnchor;
  m_drawBorder = false;
  m_cursorHoriz = Vec2I();
  m_cursorVert = Vec2I();
  m_overfillMode = true;

  m_maxWidth = assets->json("/interface.config:textBoxDefaultWidth").toInt();
  auto fontConfig = assets->json("/interface.config:font");
  m_fontSize = fontConfig.getInt("baseSize");
  m_processingDirectives = fontConfig.getString("defaultDirectives");
  m_color = Color::rgb(jsonToVec3B(fontConfig.getArray("defaultColor")));

  // Meh, padding is hard-coded here
  setSize({m_maxWidth + 6, m_fontSize + 2});
  m_cursorHoriz = jsonToVec2I(assets->json("/interface.config:textboxCursorHorizontal"));
  m_cursorVert = jsonToVec2I(assets->json("/interface.config:textboxCursorVertical"));
}

void TextBoxWidget::renderImpl() {
  float blueRate = 0;
  if (m_isHover && !m_isPressed)
    blueRate = 0.2f;
  else
    blueRate = 0.0f;

  Vec2F pos(screenPosition());
  if (m_hAnchor == HorizontalAnchor::HMidAnchor)
    pos += Vec2F(size()[0] / 2.0f, 0);
  else if (m_hAnchor == HorizontalAnchor::RightAnchor)
    pos += Vec2F(size()[0], 0);

  if ((m_maxWidth != -1) && m_overfillMode) {
    context()->setFontSize(m_fontSize);
    int shift = std::max(0, getCursorOffset() - m_maxWidth);
    pos += Vec2F(-shift, 0);
  }

  context()->setFontSize(m_fontSize);
  context()->setFontProcessingDirectives(m_processingDirectives);
  if (m_text.empty()) {
    context()->setFontColor(m_color.mix(Color::rgbf(0.3f, 0.3f, 0.3f), 0.8f).mix(Color::rgbf(0.0f, 0.0f, 1.0f), blueRate).toRgba());
    context()->renderInterfaceText(m_hint, {pos, m_hAnchor, m_vAnchor});
  } else {
    context()->setFontColor(m_color.mix(Color::rgbf(0, 0, 1), blueRate).toRgba());
    context()->renderInterfaceText(m_text, {pos, m_hAnchor, m_vAnchor});
  }
  context()->setFontProcessingDirectives("");
  context()->setFontColor(Vec4B::filled(255));

  if (hasFocus()) {
    // render cursor
    float cc = 0.6f + 0.4f * std::sin((double)Time::monotonicMilliseconds() / 300.0);
    Color cursorColor = Color::rgbf(cc, cc, cc);

    context()->drawInterfaceLine(
        pos + Vec2F(getCursorOffset(), m_fontSize * m_cursorVert[0]),
        pos + Vec2F(getCursorOffset(), m_fontSize * m_cursorVert[1]),
        cursorColor.toRgba());
    context()->drawInterfaceLine(
        pos + Vec2F(getCursorOffset() + m_fontSize * m_cursorHoriz[0], m_fontSize * m_cursorVert[0]),
        pos + Vec2F(getCursorOffset() + m_fontSize * m_cursorHoriz[1], m_fontSize * m_cursorVert[0]),
        cursorColor.toRgba());
  }

  if (m_drawBorder)
    context()->drawInterfacePolyLines(PolyF(screenBoundRect()), Color(Color::White).toRgba());
}

int TextBoxWidget::getCursorOffset() { // horizontal only
  float scale;
  context()->setFontSize(m_fontSize);
  if (m_hAnchor == HorizontalAnchor::LeftAnchor) {
    scale = 1.0;
  } else if (m_hAnchor == HorizontalAnchor::HMidAnchor) {
    scale = 0.5;
  } else if (m_hAnchor == HorizontalAnchor::RightAnchor) {
    scale = -1.0;
    return context()->stringInterfaceWidth(m_text) * scale
        + context()->stringInterfaceWidth(m_text.substr(m_cursorOffset, m_text.size()));
  } else {
    throw GuiException("Somehow, the value of m_hAnchor became bad");
  }

  return (int)std::ceil(context()->stringInterfaceWidth(m_text) * scale
      - context()->stringInterfaceWidth(m_text.substr(m_cursorOffset, m_text.size())));
}

void TextBoxWidget::update() {
  Widget::update();
  if (m_repeatCode != SpecialRepeatKeyCodes::None) {
    if (Time::monotonicMilliseconds() >= m_repeatKeyThreshold) {
      m_repeatKeyThreshold += 50;
      if (m_repeatCode == SpecialRepeatKeyCodes::Delete) {
        if (m_cursorOffset < (int)m_text.size())
          modText(m_text.substr(0, m_cursorOffset) + m_text.substr(m_cursorOffset + 1));
      } else if (m_repeatCode == SpecialRepeatKeyCodes::Backspace) {
        if (m_cursorOffset > 0) {
          if (modText(m_text.substr(0, m_cursorOffset - 1) + m_text.substr(m_cursorOffset)))
            m_cursorOffset -= 1;
        }
      } else if (m_repeatCode == SpecialRepeatKeyCodes::Left) {
        if (m_cursorOffset > 0) {
          m_cursorOffset--;
          if (m_cursorOffset < 0)
            m_cursorOffset = 0;
        }
      } else if (m_repeatCode == SpecialRepeatKeyCodes::Right) {
        if (m_cursorOffset < (int)m_text.size()) {
          m_cursorOffset++;
          if (m_cursorOffset > (int)m_text.size())
            m_cursorOffset = m_text.size();
        }
      }
    }
  }
}

String TextBoxWidget::getText() {
  return m_text;
}

bool TextBoxWidget::setText(String const& text, bool callback) {
  if (m_text == text)
    return true;

  if (!newTextValid(text))
    return false;

  m_text = text;
  m_cursorOffset = m_text.size();
  m_repeatCode = SpecialRepeatKeyCodes::None;
  if (callback)
    m_callback(this);
  return true;
}

String TextBoxWidget::getRegex() {
  return m_regex;
}

void TextBoxWidget::setRegex(String const& regex) {
  m_regex = regex;
}

void TextBoxWidget::setColor(Color const& color) {
  m_color = color;
}

void TextBoxWidget::setDirectives(String const& directives) {
  m_processingDirectives = directives;
}

void TextBoxWidget::setFontSize(int fontSize) {
  m_fontSize = fontSize;
}

void TextBoxWidget::setMaxWidth(int maxWidth) {
  m_maxWidth = maxWidth;
  setSize({m_maxWidth + 6, m_fontSize + 2});
}

void TextBoxWidget::setOverfillMode(bool overtype) {
  m_overfillMode = overtype;
}

void TextBoxWidget::setOnBlurCallback(WidgetCallbackFunc onBlur) {
  m_onBlur = onBlur;
}

void TextBoxWidget::setOnEnterKeyCallback(WidgetCallbackFunc onEnterKey) {
  m_onEnterKey = onEnterKey;
}

void TextBoxWidget::setOnEscapeKeyCallback(WidgetCallbackFunc onEscapeKey) {
  m_onEscapeKey = onEscapeKey;
}

void TextBoxWidget::setNextFocus(Maybe<String> nextFocus) {
  m_nextFocus = nextFocus;
}

void TextBoxWidget::setPrevFocus(Maybe<String> prevFocus) {
  m_prevFocus = prevFocus;
}

void TextBoxWidget::mouseOver() {
  Widget::mouseOver();
  m_isHover = true;
}

void TextBoxWidget::mouseOut() {
  Widget::mouseOut();
  m_isHover = false;
  m_isPressed = false;
}

void TextBoxWidget::mouseReturnStillDown() {
  Widget::mouseReturnStillDown();
  m_isHover = true;
  m_isPressed = true;
}

void TextBoxWidget::blur() {
  Widget::blur();
  if (m_onBlur)
    m_onBlur(this);
  m_repeatCode = SpecialRepeatKeyCodes::None;
}

KeyboardCaptureMode TextBoxWidget::keyboardCaptured() const {
  if (active() && hasFocus())
    return KeyboardCaptureMode::TextInput;
  return KeyboardCaptureMode::None;
}

bool TextBoxWidget::sendEvent(InputEvent const& event) {
  if (!hasFocus())
    return false;

  if (event.is<KeyUpEvent>()) {
    m_repeatCode = SpecialRepeatKeyCodes::None;
    m_callback(this);
    return false;
  }

  if (innerSendEvent(event)) {
    m_callback(this);
    return true;
  }

  return false;
}

bool TextBoxWidget::innerSendEvent(InputEvent const& event) {
  if (auto keyDown = event.ptr<KeyDownEvent>()) {
    m_repeatKeyThreshold = Time::monotonicMilliseconds() + 300LL;

    if (keyDown->key == Key::Escape) {
      if (m_onEscapeKey) {
        m_onEscapeKey(this);
        return true;
      }
      return false;
    }
    if (keyDown->key == Key::Return || keyDown->key == Key::Kp_enter) {
      if (m_onEnterKey) {
        m_onEnterKey(this);
        return true;
      }
      return false;
    }
    if (keyDown->key == Key::Tab) {
      if ((KeyMod::LShift & keyDown->mods) == KeyMod::LShift || (KeyMod::RShift & keyDown->mods) == KeyMod::RShift) {
        if (m_prevFocus) {
          if (auto prevWidget = parent()->fetchChild(*m_prevFocus)) {
            prevWidget->focus();
            return true;
          }
        }
      } else {
        if (m_nextFocus) {
          if (auto nextWidget = parent()->fetchChild(*m_nextFocus)) {
            nextWidget->focus();
            return true;
          }
        }
      }
      return false;
    }
    if ((keyDown->mods & (KeyMod::LCtrl | KeyMod::RCtrl)) != KeyMod::NoMod) {
      if (keyDown->key == Key::C) {
        context()->setClipboard(m_text);
        return true;
      }
      if (keyDown->key == Key::X) {
        context()->setClipboard(m_text);
        if (modText(""))
          m_cursorOffset = 0;
        return true;
      }
      if (keyDown->key == Key::V) {
        String clipboard = context()->getClipboard();
        if (modText(m_text.substr(0, m_cursorOffset) + clipboard + m_text.substr(m_cursorOffset)))
          m_cursorOffset += clipboard.size();
        return true;
      }
    }

    int rightSteps = 1;
    int leftSteps = 1;
    if ((keyDown->mods & (KeyMod::LCtrl | KeyMod::RCtrl)) != KeyMod::NoMod || (keyDown->mods & (KeyMod::LAlt | KeyMod::RAlt)) != KeyMod::NoMod) {
      rightSteps = m_text.findNextBoundary(m_cursorOffset) - m_cursorOffset;
      leftSteps = m_cursorOffset - m_text.findNextBoundary(m_cursorOffset, true);

      if (rightSteps < 1)
        rightSteps = 1;
      if (leftSteps < 1)
        leftSteps = 1;
    }

    if (keyDown->key == Key::Backspace) {
      m_repeatCode = SpecialRepeatKeyCodes::Backspace;
      for (int i = 0; i < leftSteps; i++) {
        if (m_cursorOffset > 0) {
          if (modText(m_text.substr(0, m_cursorOffset - 1) + m_text.substr(m_cursorOffset)))
            m_cursorOffset -= 1;
        }
      }
      return true;
    }
    if (keyDown->key == Key::Delete) {
      m_repeatCode = SpecialRepeatKeyCodes::Delete;
      for (int i = 0; i < rightSteps; i++) {
        if (m_cursorOffset < (int)m_text.size())
          modText(m_text.substr(0, m_cursorOffset) + m_text.substr(m_cursorOffset + 1));
      }
      return true;
    }
    if (keyDown->key == Key::Left) {
      m_repeatCode = SpecialRepeatKeyCodes::Left;
      for (int i = 0; i < leftSteps; i++) {
        m_cursorOffset--;
        if (m_cursorOffset < 0)
          m_cursorOffset = 0;
      }
      return true;
    }
    if (keyDown->key == Key::Right) {
      m_repeatCode = SpecialRepeatKeyCodes::Right;
      for (int i = 0; i < rightSteps; i++) {
        m_cursorOffset++;
        if (m_cursorOffset > (int)m_text.size())
          m_cursorOffset = m_text.size();
      }
      return true;
    }
    if (keyDown->key == Key::Home) {
      m_cursorOffset = 0;
      return true;
    }
    if (keyDown->key == Key::End) {
      m_cursorOffset = m_text.size();
      return true;
    }
  }

  if (auto textInput = event.ptr<TextInputEvent>()) {
    if (modText(m_text.substr(0, m_cursorOffset) + textInput->text + m_text.substr(m_cursorOffset)))
      m_cursorOffset += textInput->text.size();
    return true;
  }

  return false;
}

void TextBoxWidget::setDrawBorder(bool drawBorder) {
  m_drawBorder = drawBorder;
}

void TextBoxWidget::setTextAlign(HorizontalAnchor hAnchor) {
  m_hAnchor = hAnchor;
}

bool TextBoxWidget::modText(String const& text) {
  if (m_text != text && newTextValid(text)) {
    m_text = text;
    return true;
  } else {
    return false;
  }
}

bool TextBoxWidget::newTextValid(String const& text) const {
  if (!text.regexMatch(m_regex))
    return false;
  if ((m_maxWidth != -1) && !m_overfillMode) {
    context()->setFontSize(m_fontSize);
    return context()->stringInterfaceWidth(text) <= m_maxWidth;
  }
  return true;
}

}