Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
TextBoxWidget.cs
1using System.Drawing;
8using SkiaSharp;
9
11
22public sealed class TextBoxWidget : WidgetBase
23{
24 private Color _backgroundColor = Color.FromArgb(
25 255,
26 32,
27 32,
28 40);
29
30 private Color _borderColor = Color.FromArgb(
31 255,
32 135,
33 135,
34 150);
35
36 private Color _focusedBorderColor = Color.FromArgb(
37 255,
38 105,
39 155,
40 230);
41
42 private SKColor _textColor = SKColors.White;
43 private SKColor _placeholderColor = new(170, 170, 180);
44
45 private string _text = string.Empty;
46 private string _placeholder = string.Empty;
47 private int _caretIndex;
48 private int? _maxLength;
49 private double _initialKeyRepeatDelaySeconds = 1.25;
50 private double _repeatedKeyIntervalSeconds = 0.05;
51 private int? _repeatingKey;
52 private long _keyPressedTick;
53 private long _lastRepeatTick;
54 private Func<WidgetKeyboardEventArgs, char?> _characterResolver = ResolveWindowsVirtualKeyCharacter;
55
59 public event Action<string>? TextChanged;
60
64 public event Action<string>? Submitted;
65
76 RenderSurfaceHostBase renderSurfaceHost,
77 View view,
78 Rectangle bounds,
79 string text = "",
80 string? placeholder = null,
81 string? nickname = null)
82 : base(
83 renderSurfaceHost,
85 ValidateBounds(bounds).Location,
86 nickname)
87 {
88 ArgumentNullException.ThrowIfNull(view);
89
90 _text = NormalizeText(text);
91 _placeholder = placeholder ?? string.Empty;
92 _caretIndex = _text.Length;
93
94 Background = CreateBackground(renderSurfaceHost, view, bounds);
95 TextBlock = CreateTextBlock(renderSurfaceHost, view, bounds);
96
99
100 CompleteInitialization();
101 }
102
113 RenderSurfaceHostBase renderSurfaceHost,
114 SceneLayer sceneLayer,
115 Rectangle bounds,
116 string text = "",
117 string? placeholder = null,
118 string? nickname = null)
119 : base(
120 renderSurfaceHost,
122 ValidateBounds(bounds).Location,
123 nickname)
124 {
125 ArgumentNullException.ThrowIfNull(sceneLayer);
126
127 _text = NormalizeText(text);
128 _placeholder = placeholder ?? string.Empty;
129 _caretIndex = _text.Length;
130
131 Background = CreateBackground(renderSurfaceHost, sceneLayer, bounds);
132 TextBlock = CreateTextBlock(renderSurfaceHost, sceneLayer, bounds);
133
135 Add(TextBlock);
136
137 CompleteInitialization();
138 }
139
144
148 public TextBlock TextBlock { get; }
149
153 public string Text
154 {
155 get => _text;
156 set => SetText(value);
157 }
158
162 public string Placeholder
163 {
164 get => _placeholder;
165 set
166 {
167 _placeholder = value ?? string.Empty;
168 RefreshDisplayedText();
169 }
170 }
171
175 public int CaretIndex
176 {
177 get => _caretIndex;
178 set
179 {
180 _caretIndex = Math.Clamp(value, 0, _text.Length);
181 RefreshDisplayedText();
182 }
183 }
184
188 public int? MaxLength
189 {
190 get => _maxLength;
191 set
192 {
193 if (value.HasValue && value.Value < 0)
194 throw new ArgumentOutOfRangeException(nameof(value));
195
196 _maxLength = value;
197
198 if (_maxLength.HasValue && _text.Length > _maxLength.Value)
199 SetText(_text[.._maxLength.Value]);
200 }
201 }
202
208 {
209 get => _initialKeyRepeatDelaySeconds;
210 set
211 {
212 if (!double.IsFinite(value) || value < 0d)
213 throw new ArgumentOutOfRangeException(nameof(value));
214
215 _initialKeyRepeatDelaySeconds = value;
216 }
217 }
218
225 {
226 get => _repeatedKeyIntervalSeconds;
227 set
228 {
229 if (!double.IsFinite(value) || value < 0d)
230 throw new ArgumentOutOfRangeException(nameof(value));
231
232 _repeatedKeyIntervalSeconds = value;
233 }
234 }
235
239 public bool IsReadOnly { get; set; }
240
244 public Rectangle Bounds => Mode == DirectDrawingMode.View
245 ? Background.ScreenBounds
246 : Background.WorldBounds;
247
251 public int SubmitKey { get; set; } = 13;
252
256 public int BackspaceKey { get; set; } = 8;
257
261 public int DeleteKey { get; set; } = 46;
262
266 public int LeftKey { get; set; } = 37;
267
271 public int RightKey { get; set; } = 39;
272
276 public int HomeKey { get; set; } = 36;
277
281 public int EndKey { get; set; } = 35;
282
286 public Func<WidgetKeyboardEventArgs, char?> CharacterResolver
287 {
288 get => _characterResolver;
289 set => _characterResolver = value ?? NoCharacterResolver;
290 }
291
297 public TextBoxWidget SetText(string? text)
298 {
299 string normalized = NormalizeText(text);
300
301 if (MaxLength.HasValue && normalized.Length > MaxLength.Value)
302 normalized = normalized[..MaxLength.Value];
303
304 if (_text == normalized)
305 {
306 _caretIndex = Math.Min(_caretIndex, _text.Length);
307 RefreshDisplayedText();
308 return this;
309 }
310
311 _text = normalized;
312 _caretIndex = _text.Length;
313 RefreshDisplayedText();
314 TextChanged?.Invoke(_text);
315 return this;
316 }
317
323 public TextBoxWidget InsertText(string? text)
324 {
325 if (IsReadOnly || string.IsNullOrEmpty(text))
326 return this;
327
328 string insertion = NormalizeText(text);
329
330 if (insertion.Length == 0)
331 return this;
332
333 if (MaxLength.HasValue)
334 {
335 int available = MaxLength.Value - _text.Length;
336
337 if (available <= 0)
338 return this;
339
340 if (insertion.Length > available)
341 insertion = insertion[..available];
342 }
343
344 _text = _text.Insert(_caretIndex, insertion);
345 _caretIndex += insertion.Length;
346 RefreshDisplayedText();
347 TextChanged?.Invoke(_text);
348 return this;
349 }
350
356 {
357 if (IsReadOnly || _caretIndex <= 0 || _text.Length == 0)
358 return this;
359
360 _text = _text.Remove(_caretIndex - 1, 1);
361 _caretIndex--;
362 RefreshDisplayedText();
363 TextChanged?.Invoke(_text);
364 return this;
365 }
366
372 {
373 if (IsReadOnly || _caretIndex < 0 || _caretIndex >= _text.Length)
374 return this;
375
376 _text = _text.Remove(_caretIndex, 1);
377 RefreshDisplayedText();
378 TextChanged?.Invoke(_text);
379 return this;
380 }
381
387 public TextBoxWidget MoveCaret(int delta)
388 {
389 CaretIndex = Math.Clamp(_caretIndex + delta, 0, _text.Length);
390 return this;
391 }
392
401 Color background,
402 Color border,
403 Color focusedBorder)
404 {
405 _backgroundColor = background;
406 _borderColor = border;
407 _focusedBorderColor = focusedBorder;
408
409 Background.SetColor(_backgroundColor)
410 .SetBorderColor(IsFocused ? _focusedBorderColor : _borderColor);
411
412 Refresh(Background);
413 return this;
414 }
415
422 public TextBoxWidget SetTextColors(SKColor text, SKColor placeholder)
423 {
424 _textColor = text;
425 _placeholderColor = placeholder;
426 RefreshDisplayedText();
427 return this;
428 }
429
436 {
437 Background.ZOrder = zOrder;
438 TextBlock.ZOrder = zOrder + 1;
439 return this;
440 }
441
443 protected override void OnPointerClick(WidgetPointerEventArgs args)
444 {
445 base.OnPointerClick(args);
446
447 if (!args.IsPrimaryButton)
448 return;
449
450 _caretIndex = _text.Length;
451 RefreshDisplayedText();
452 args.Handled = true;
453 }
454
456 protected override void OnFocusGained()
457 {
458 base.OnFocusGained();
459 Background.SetBorderColor(_focusedBorderColor);
460 Refresh(Background);
461 RefreshDisplayedText();
462 }
463
465 protected override void OnFocusLost()
466 {
467 base.OnFocusLost();
468 ResetKeyRepeatState();
469 Background.SetBorderColor(_borderColor);
470 Refresh(Background);
471 RefreshDisplayedText();
472 }
473
475 protected override void OnKeyboardInput(WidgetKeyboardEventArgs args)
476 {
477 base.OnKeyboardInput(args);
478
479 if (args.KeyAction == KeyAction.Released)
480 {
481 if (_repeatingKey == args.Key)
482 ResetKeyRepeatState();
483
484 return;
485 }
486
487 if (args.KeyAction is not KeyAction.Pressed and not KeyAction.Repeated)
488 return;
489
490 long currentTick = HighResTimer.GetCurrentTick();
491
492 if (args.KeyAction == KeyAction.Pressed)
493 {
494 _repeatingKey = args.Key;
495 _keyPressedTick = currentTick;
496 _lastRepeatTick = currentTick;
497 }
498 else
499 {
500 if (_repeatingKey != args.Key ||
501 _keyPressedTick == 0 ||
502 HighResTimer.GetDuration(_keyPressedTick, currentTick) < _initialKeyRepeatDelaySeconds ||
503 (_lastRepeatTick != 0 &&
504 HighResTimer.GetDuration(_lastRepeatTick, currentTick) < _repeatedKeyIntervalSeconds))
505 {
506 args.Handled = true;
507 return;
508 }
509
510 _lastRepeatTick = currentTick;
511 }
512
513 if (args.Key == SubmitKey)
514 {
515 if (args.KeyAction != KeyAction.Pressed)
516 return;
517
518 args.Handled = true;
519 Submitted?.Invoke(_text);
520 return;
521 }
522
523 if (args.Key == LeftKey)
524 {
525 args.Handled = true;
526 MoveCaret(-1);
527 return;
528 }
529
530 if (args.Key == RightKey)
531 {
532 args.Handled = true;
533 MoveCaret(1);
534 return;
535 }
536
537 if (args.Key == HomeKey)
538 {
539 args.Handled = true;
540 CaretIndex = 0;
541 return;
542 }
543
544 if (args.Key == EndKey)
545 {
546 args.Handled = true;
547 CaretIndex = _text.Length;
548 return;
549 }
550
551 if (args.Key == BackspaceKey)
552 {
553 args.Handled = true;
554 Backspace();
555 return;
556 }
557
558 if (args.Key == DeleteKey)
559 {
560 args.Handled = true;
561 Delete();
562 return;
563 }
564
565 if (IsReadOnly)
566 return;
567
568 char? character = CharacterResolver(args);
569
570 if (!character.HasValue)
571 return;
572
573 args.Handled = true;
574 InsertText(character.Value.ToString());
575 }
576
577 private void ResetKeyRepeatState()
578 {
579 _repeatingKey = null;
580 _keyPressedTick = 0;
581 _lastRepeatTick = 0;
582 }
583
584 private void CompleteInitialization()
585 {
586 CanReceiveFocus = true;
589 RefreshDisplayedText();
590 }
591
592 private void RefreshDisplayedText()
593 {
594 if (IsFocused)
595 {
596 string withCaret = _text.Insert(_caretIndex, "|");
597
598 TextBlock.SetText(withCaret)
599 .SetColors(_textColor, SKColors.Transparent);
600
601 return;
602 }
603
604 bool showPlaceholder = _text.Length == 0 && _placeholder.Length > 0;
605
606 TextBlock.SetText(showPlaceholder ? _placeholder : _text)
607 .SetColors(showPlaceholder ? _placeholderColor : _textColor, SKColors.Transparent);
608 }
609
610 private DirectRectangle CreateBackground(
611 RenderSurfaceHostBase host,
612 View view,
613 Rectangle bounds)
614 {
615 return ConfigureBackground(
616 new DirectRectangle(
617 _backgroundColor,
618 host,
619 view,
620 bounds));
621 }
622
623 private DirectRectangle CreateBackground(
624 RenderSurfaceHostBase host,
625 SceneLayer layer,
626 Rectangle bounds)
627 {
628 return ConfigureBackground(
629 new DirectRectangle(
630 _backgroundColor,
631 host,
632 layer,
633 bounds));
634 }
635
636 private DirectRectangle ConfigureBackground(DirectRectangle background)
637 {
638 return background.SetFilled(true)
639 .SetBorderColor(_borderColor)
640 .SetStrokeWidth(1.5f)
641 .SetCornerRadius(4f);
642 }
643
644 private static TextBlock CreateTextBlock(
645 RenderSurfaceHostBase host,
646 View view,
647 Rectangle bounds)
648 {
649 return ConfigureTextBlock(new TextBlock(host, view, bounds));
650 }
651
652 private static TextBlock CreateTextBlock(
653 RenderSurfaceHostBase host,
654 SceneLayer layer,
655 Rectangle bounds)
656 {
657 return ConfigureTextBlock(
658 new TextBlock(
659 host,
660 layer,
661 view: null,
662 worldBounds: bounds));
663 }
664
665 private static TextBlock ConfigureTextBlock(TextBlock textBlock)
666 {
667 return textBlock.SetFont(SKTypeface.Default, 16f, minSize: 10f)
668 .SetColors(SKColors.White, SKColors.Transparent)
669 .SetAlignment(SKTextAlign.Left, TextBlock.VerticalAlign.Center)
670 .SetPadding(8f, 0f)
671 .EnableWrapping(false);
672 }
673
674 private static string NormalizeText(string? text)
675 {
676 return (text ?? string.Empty)
677 .Replace('\r', ' ')
678 .Replace('\n', ' ');
679 }
680
681 private static char? NoCharacterResolver(WidgetKeyboardEventArgs args)
682 {
683 return null;
684 }
685
686 private static char? ResolveWindowsVirtualKeyCharacter(WidgetKeyboardEventArgs args)
687 {
688 if ((args.Modifiers & (KeyboardModifierState.Ctrl | KeyboardModifierState.Alt)) != 0)
689 return null;
690
691 bool shift = (args.Modifiers & KeyboardModifierState.Shift) != 0;
692 int key = args.Key;
693
694 if (key is >= 65 and <= 90)
695 {
696 char letter = (char)key;
697 return shift ? letter : char.ToLowerInvariant(letter);
698 }
699
700 if (key is >= 48 and <= 57)
701 {
702 if (!shift)
703 return (char)key;
704
705 const string shiftedDigits = ")!@#$%^&*(";
706 return shiftedDigits[key - 48];
707 }
708
709 if (key is >= 96 and <= 105)
710 return (char)('0' + key - 96);
711
712 return key switch
713 {
714 32 => ' ',
715 106 => '*',
716 107 => '+',
717 109 => '-',
718 110 => '.',
719 111 => '/',
720 186 => shift ? ':' : ';',
721 187 => shift ? '+' : '=',
722 188 => shift ? '<' : ',',
723 189 => shift ? '_' : '-',
724 190 => shift ? '>' : '.',
725 191 => shift ? '?' : '/',
726 192 => shift ? '~' : '`',
727 219 => shift ? '{' : '[',
728 220 => shift ? '|' : '\\',
729 221 => shift ? '}' : ']',
730 222 => shift ? '"' : '\'',
731 _ => null
732 };
733 }
734
735 private static void Refresh(DirectRectangle rectangle)
736 {
737 rectangle.SetPosition(rectangle.GetPosition());
738 }
739
740 private static Rectangle ValidateBounds(Rectangle bounds)
741 {
742 if (bounds.Width < 40 || bounds.Height < 18)
743 throw new ArgumentOutOfRangeException(nameof(bounds), bounds, "Text-box bounds are too small.");
744
745 return bounds;
746 }
747}
virtual DirectComposite Remove(IDirectCompositeChild child)
Removes a child without disposing it.
SceneLayer? SceneLayer
Gets the scene layer shared by all children in scene-layer mode.
View? View
Gets the view shared by all children in view mode.
virtual DirectComposite Add(IDirectCompositeChild child, bool keepCurrentOffset=true, Vector2? explicitLocalOffsetPx=null)
Adds a composite-compatible direct drawable as a child.
DirectDrawingMode Mode
Gets the coordinate mode shared by the composite and its children.
int ZOrder
Gets or sets the Z-order (depth) used for sorting this direct drawing relative to other drawables.
Vector2 GetPosition()
Gets the current position of this direct drawing in pixel coordinates.
void SetPosition(Vector2 p)
Sets the position of this direct drawing to the specified pixel coordinates.
Renders a configurable rectangle with support for fill, border, rounded corners, dash patterns,...
DirectRectangle SetFilled(bool isFilled)
Sets whether the rectangle interior is filled with the base color (or pattern).
DirectRectangle SetBorderColor(Color color)
Sets a distinct border (stroke) color, independent of the fill color.
DirectRectangle SetStrokeWidth(float width)
Sets the width (thickness) of the rectangle's stroke (outline) in pixels.
DirectRectangle SetCornerRadius(float radius)
Sets the radius for rounded corners in pixels.
A retained-mode text drawable with wrapping, multi-line ( ) support, horizontal/vertical alignment,...
Definition TextBlock.cs:44
TextBlock SetFont(SKTypeface typeface, float size, float? minSize=null)
Sets the font face and size (and optional minimum size for auto-shrink).
Definition TextBlock.cs:414
TextBlock EnableWrapping(bool enable=true)
Enables or disables word wrapping when laying out paragraphs.
Definition TextBlock.cs:527
TextBlock SetAlignment(SKTextAlign h, VerticalAlign v)
Sets the horizontal and vertical alignment used when drawing the laid-out lines within the bounds.
Definition TextBlock.cs:453
TextBlock SetPadding(float horizontal, float vertical)
Sets symmetric horizontal and vertical padding and invalidates cached layout.
Definition TextBlock.cs:336
TextBlock SetColors(SKColor fg, SKColor bg)
Sets the foreground (text) and background colors using Skia colors.
Definition TextBlock.cs:430
TextBlock SetText(string text)
Sets the current text content and rebuilds layout as needed. If no reveal animation is active,...
Definition TextBlock.cs:378
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
override void OnPointerClick(WidgetPointerEventArgs args)
Called when a pointer click is dispatched to the widget.
Action< string >? TextChanged
Occurs when the text changes.
TextBoxWidget InsertText(string? text)
Inserts text at the current caret position.
double InitialKeyRepeatDelaySeconds
Gets or sets the delay, in seconds, before a held key begins repeating. Pressed events remain immedia...
override void OnFocusLost()
Called when the widget loses focus.
TextBoxWidget SetText(string? text)
Replaces the text and moves the caret to the end.
Func< WidgetKeyboardEventArgs, char?> CharacterResolver
Gets or sets the function used to convert routed key events into printable characters.
TextBoxWidget SetTextColors(SKColor text, SKColor placeholder)
Sets the text and placeholder colors.
TextBoxWidget MoveCaret(int delta)
Moves the caret by the specified character delta.
override void OnKeyboardInput(WidgetKeyboardEventArgs args)
Called when keyboard input is routed to the widget.
TextBoxWidget Backspace()
Removes the character before the caret when possible.
string Placeholder
Gets or sets placeholder text shown while the control is empty and unfocused.
int RightKey
Gets or sets the key code used to move right. Defaults to 39.
string Text
Gets or sets the current text.
int LeftKey
Gets or sets the key code used to move left. Defaults to 37.
TextBoxWidget(RenderSurfaceHostBase renderSurfaceHost, View view, Rectangle bounds, string text="", string? placeholder=null, string? nickname=null)
Creates a view-level text box.
Action< string >? Submitted
Occurs when the configured submit key is pressed.
TextBoxWidget Delete()
Removes the character at the caret when possible.
bool IsReadOnly
Gets or sets whether user editing is disabled.
TextBoxWidget SetColors(Color background, Color border, Color focusedBorder)
Sets the background and border colors used for normal and focused states.
int EndKey
Gets or sets the key code used to move to the end. Defaults to 35.
DirectRectangle Background
Gets the text-box background and border drawing.
int BackspaceKey
Gets or sets the key code used for backspace. Defaults to 8.
TextBlock TextBlock
Gets the text drawing used by the text box.
override void OnFocusGained()
Called when the widget gains focus.
Rectangle Bounds
Gets the text-box bounds in its native coordinate space.
int? MaxLength
Gets or sets the maximum permitted text length. A null value means unlimited.
int DeleteKey
Gets or sets the key code used for Delete. Defaults to 46.
int SubmitKey
Gets or sets the key code used to submit the text. Defaults to Enter (13).
double RepeatedKeyIntervalSeconds
Gets or sets the minimum interval, in seconds, between repeated held-key actions after InitialKeyRepe...
TextBoxWidget(RenderSurfaceHostBase renderSurfaceHost, SceneLayer sceneLayer, Rectangle bounds, string text="", string? placeholder=null, string? nickname=null)
Creates a scene-layer text box.
int CaretIndex
Gets or sets the caret position in the range zero through Text length.
int HomeKey
Gets or sets the key code used to move to the beginning. Defaults to 36.
TextBoxWidget SetTextBoxZOrder(int zOrder)
Sets the base Z-order used by the text-box visuals.
bool CanReceiveFocus
Gets or sets a value indicating whether the widget can receive keyboard focus.
WidgetBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, PointF anchor=default, string? nickname=null)
Initializes a new instance of the WidgetBase class.
Definition WidgetBase.cs:95
bool IsFocused
Gets a value indicating whether the widget currently has keyboard focus.
bool IsKeyboardInputEnabled
Gets or sets a value indicating whether the widget can receive keyboard input.
Provides data for widget keyboard input events routed by WidgetInputRouter.
int Key
Gets the integer key identifier.
KeyAction KeyAction
Gets the action associated with this key event.
Event arguments for pointer-based widget callbacks.
bool IsPrimaryButton
Gets whether the pointer event represents a primary-button interaction.
@ Rectangle
Particles are spawned uniformly within a rectangular area. This is the default distribution.
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
@ View
Performs direct drawing at the view level using screen-space coordinates.
KeyboardModifierState
Represents the state of keyboard modifier keys (Shift, Ctrl, Alt) that can be pressed simultaneously ...
KeyAction
Represents the type of action performed on a keyboard key, indicating whether the key was pressed,...
Definition KeyAction.cs:10