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
MenuItemWidget.cs
1using System.Drawing;
2using System.Numerics;
7using SkiaSharp;
8
10
12public sealed class MenuItemWidget : WidgetBase
13{
14 private readonly MenuBarTheme _theme;
15 private readonly MenuDropDownWidget _owner;
16 private readonly Action? _action;
17 private readonly Action<bool>? _checkedAction;
18 private readonly MenuIndicatorDrawing _marker;
19 private readonly MenuIndicatorDrawing _arrow;
20 private bool _disposed;
21 private bool _isPointerOver;
22 private bool _isSelected;
23 private bool _isEnabled = true;
24
25 internal event Action<MenuItemWidget>? Hovered;
26
28 public event Action<MenuItemWidget>? Invoked;
29
30 internal MenuItemWidget(
32 View view,
33 Rectangle bounds,
34 string text,
35 string? shortcutText,
36 Action? action,
37 MenuBarTheme theme,
38 string nickname,
40 string? key,
41 KeyGesture? shortcut,
42 char? mnemonic,
43 SKImage? icon,
44 bool checkable,
45 string? radioGroup,
46 Action<bool>? checkedAction,
47 MenuDropDownWidget? subMenu)
48 : base(
49 host,
51 bounds.Location,
52 nickname)
53 {
54 _theme = theme;
55 _owner = owner;
56 _action = action;
57 _checkedAction = checkedAction;
58 Text = text;
59 Key = key;
60 Shortcut = shortcut;
61 ShortcutText = shortcut?.ToString() ?? shortcutText ?? string.Empty;
62 Mnemonic = mnemonic;
63 Icon = icon;
64 IsCheckable = checkable;
65 RadioGroup = radioGroup;
66 SubMenu = subMenu;
67
69 theme.ItemNormalColor,
70 host,
71 view,
72 bounds,
73 $"{Nickname}.background")
74 .SetFilled(true).SetStrokeWidth(0f);
75
76 Label = CreateText(
77 host,
78 view,
79 bounds,
80 "label",
81 SKTextAlign.Left).SetText(Text);
82
83 ShortcutLabel = CreateText(
84 host,
85 view,
86 bounds,
87 "shortcut",
88 SKTextAlign.Right).SetText(ShortcutText);
89
90 _marker = new MenuIndicatorDrawing(
91 host,
92 view,
93 bounds,
94 radioGroup is null ? MenuIndicatorDrawing.Shape.Check : MenuIndicatorDrawing.Shape.Radio,
95 theme,
96 $"{Nickname}.marker");
97
98 _arrow = new MenuIndicatorDrawing(
99 host,
100 view,
101 bounds,
102 MenuIndicatorDrawing.Shape.Arrow,
103 theme,
104 $"{Nickname}.arrow");
105
107 Add(Label);
109 Add(Marker);
110 Add(Arrow);
111
112 if (icon is not null)
113 {
115 icon,
116 host,
117 view,
118 bounds,
119 $"{Nickname}.icon")
121
123 }
124
125 CanReceiveFocus = true;
128 UpdateVisualState();
129 }
130
132 public string? Key { get; }
133
135 public string Text { get; }
136
138 public KeyGesture? Shortcut { get; }
139
141 public string ShortcutText { get; }
142
144 public char? Mnemonic { get; }
145
147 public SKImage? Icon { get; }
148
150 public DirectImage? IconDrawing { get; }
151
153 public bool IsCheckable { get; }
154
156 public bool IsChecked { get; private set; }
157
159 public string? RadioGroup { get; }
160
163
166
168 public TextBlock Label { get; }
169
171 public TextBlock ShortcutLabel { get; }
172
175
178
180 public bool IsEnabled => _isEnabled;
181
183 public bool IsSelected => _isSelected;
184
185 internal bool CanInvoke => !_disposed && _isEnabled && _owner.CanInvoke;
186
190 public MenuItemWidget SetEnabled(bool enabled)
191 {
192 ObjectDisposedException.ThrowIf(_disposed, this);
193 _isEnabled = enabled;
194 ApplyInputState(_owner.IsOpen);
195
196 if (!enabled)
197 _owner.OnItemDisabled(this);
198
199 UpdateVisualState();
200 return this;
201 }
202
206 public MenuItemWidget SetChecked(bool isChecked)
207 {
208 ObjectDisposedException.ThrowIf(_disposed, this);
209
210 if (!IsCheckable)
211 throw new InvalidOperationException("This menu item is not checkable.");
212
213 if (isChecked && RadioGroup is not null)
214 _owner.UncheckRadioPeers(this);
215
216 IsChecked = isChecked;
217 UpdateVisualState();
218 return this;
219 }
220
223 public void PerformClick()
224 {
225 if (!CanInvoke)
226 return;
227
228 if (SubMenu is not null)
229 {
230 _owner.OpenSubMenu(this, selectFirst: true);
231 return;
232 }
233
234 if (IsCheckable)
235 SetChecked(RadioGroup is not null || !IsChecked);
236
237 bool checkedState = IsChecked;
238 _owner.NotifyInvoked(this);
239 Invoked?.Invoke(this);
240 _checkedAction?.Invoke(checkedState);
241 _action?.Invoke();
242 }
243
244 internal void SetSelected(bool selected)
245 {
246 _isSelected = selected;
247
248 if (!selected)
249 _isPointerOver = false;
250
251 UpdateVisualState();
252 }
253
254 internal void ApplyInputState(bool menuAcceptsInput)
255 {
256 bool enabled = menuAcceptsInput && _isEnabled && !_disposed;
257 IsInputEnabled = enabled;
258 IsPointerInputEnabled = enabled;
259 IsKeyboardInputEnabled = enabled;
260 CanReceiveFocus = enabled;
261 }
262
263 internal void SetItemZOrder(int zOrder)
264 {
265 Background.ZOrder = zOrder;
266
267 foreach (var drawing in new DirectDrawingBase[] { Label, ShortcutLabel, Marker, Arrow })
268 drawing.ZOrder = zOrder + 1;
269
270 if (IconDrawing is not null)
271 IconDrawing.ZOrder = zOrder + 1;
272 }
273
274 internal void SetBounds(
275 Rectangle bounds,
276 int markerWidth,
277 int iconWidth,
278 int shortcutWidth,
279 int arrowWidth)
280 {
281 SetPosition(bounds.X, bounds.Y);
282 Background.ScreenBounds = bounds;
283 int x = bounds.X + _theme.ItemHorizontalPadding;
284
285 Place(
286 Marker,
287 new Rectangle(
288 x,
289 bounds.Y,
290 Math.Max(1, markerWidth),
291 bounds.Height));
292
293 x += markerWidth;
294
295 if (IconDrawing is not null)
296 Place(
298 new Rectangle(
299 x,
300 bounds.Y + (bounds.Height - _theme.IconSize) / 2,
301 _theme.IconSize,
302 _theme.IconSize));
303
304 x += iconWidth;
305 int right = bounds.Right - _theme.ItemHorizontalPadding;
306
307 Place(
308 Arrow,
309 new Rectangle(
310 right - arrowWidth,
311 bounds.Y,
312 Math.Max(1, arrowWidth),
313 bounds.Height));
314
315 right -= arrowWidth;
316
317 Place(
319 new Rectangle(
320 right - shortcutWidth,
321 bounds.Y,
322 Math.Max(1, shortcutWidth),
323 bounds.Height));
324
325 if (shortcutWidth > 0)
326 right -= shortcutWidth + _theme.ShortcutGap;
327
328 Place(
329 Label,
330 new Rectangle(
331 x,
332 bounds.Y,
333 Math.Max(1, right - x),
334 bounds.Height));
335
336 Label.HorizontalPadding = ShortcutLabel.HorizontalPadding = 0;
337 }
338
339 private void Place(DirectDrawingBase drawing, Rectangle bounds)
340 {
342 (IDirectCompositeChild)drawing,
343 new Vector2(bounds.X - GetPosition().X, bounds.Y - GetPosition().Y));
344
345 drawing.ScreenBounds = bounds;
346 }
347
348 private TextBlock CreateText(
349 RenderSurfaceHostBase host,
350 View view,
351 Rectangle bounds,
352 string name,
353 SKTextAlign alignment) =>
354 new TextBlock(
355 host,
356 view,
357 bounds,
358 $"{Nickname}.{name}")
359 .SetFont(SKTypeface.Default, _theme.FontSize, _theme.MinimumFontSize)
360 .SetAlignment(alignment, TextBlock.VerticalAlign.Center).EnableWrapping(false);
361
363 public override void Dispose()
364 {
365 if (_disposed)
366 return;
367
368 _disposed = true;
369 _owner.UnregisterItem(this);
370 Hovered = null;
371 Invoked = null;
372 base.Dispose();
373 }
374
376 protected override void OnPointerEnter(WidgetPointerEventArgs args)
377 {
378 base.OnPointerEnter(args);
379
380 if (!_isEnabled)
381 return;
382
383 _isPointerOver = true;
384 Hovered?.Invoke(this);
385 UpdateVisualState();
386 }
387
389 protected override void OnPointerLeave(WidgetPointerEventArgs args)
390 {
391 base.OnPointerLeave(args);
392 _isPointerOver = false;
393 UpdateVisualState();
394 }
395
397 protected override void OnPointerDown(WidgetPointerEventArgs args)
398 {
399 base.OnPointerDown(args);
400
401 if (_isEnabled && args.IsPrimaryButton)
402 SetBackgroundColor(_theme.ItemPressedColor);
403 }
404
406 protected override void OnPointerUp(WidgetPointerEventArgs args)
407 {
408 base.OnPointerUp(args);
409 UpdateVisualState();
410 }
411
413 protected override void OnPointerClick(WidgetPointerEventArgs args)
414 {
415 base.OnPointerClick(args);
416
417 if (!_isEnabled || !args.IsPrimaryButton)
418 return;
419
420 args.Handled = true;
421 PerformClick();
422 }
423
425 protected override void OnKeyboardInput(WidgetKeyboardEventArgs args)
426 {
427 base.OnKeyboardInput(args);
428
429 // Open-menu navigation bubbles to the bar, which knows the active depth.
430 if (_owner.IsOpen || args.Handled || args.KeyAction != KeyAction.Pressed || args.Key is not 13 and not 32)
431 return;
432
433 if (!CanInvoke)
434 return;
435
436 args.Handled = true;
437 PerformClick();
438 }
439
440 private void UpdateVisualState()
441 {
442 SetBackgroundColor(
443 _isEnabled && (_isPointerOver || _isSelected) ? _theme.ItemHoverColor : _theme.ItemNormalColor);
444
445 Label.SetColors(ToSkColor(_isEnabled ? _theme.TextColor : _theme.DisabledTextColor), SKColors.Transparent);
446
448 ToSkColor(_isEnabled ? _theme.ShortcutTextColor : _theme.DisabledTextColor),
449 SKColors.Transparent);
450
451 var indicator = ToSkColor(_isEnabled ? _theme.IndicatorColor : _theme.DisabledTextColor);
452 _marker.SetState(IsChecked, indicator);
453 _arrow.SetState(SubMenu is not null, indicator);
454 IconDrawing?.SetTint(_isEnabled ? SKColors.White : ToSkColor(_theme.DisabledTextColor));
455 }
456
457 private void SetBackgroundColor(Color color)
458 {
459 Background.SetColor(color);
461 }
462
463 private static SKColor ToSkColor(Color color) => new(
464 color.R,
465 color.G,
466 color.B,
467 color.A);
468}
DirectComposite SetLocalOffset(IDirectCompositeChild child, Vector2 newLocalOffsetPx)
Changes one child's local offset and reapplies its position.
View? View
Gets the view shared by all children in view mode.
Vector2 GetPosition()
Gets the current composite anchor.
virtual DirectComposite Add(IDirectCompositeChild child, bool keepCurrentOffset=true, Vector2? explicitLocalOffsetPx=null)
Adds a composite-compatible direct drawable as a child.
void SetPosition(Vector2 position)
Sets the composite anchor and repositions all children from their stored offsets.
Provides the base implementation for direct drawing objects that can be rendered to the backbuffer wi...
Provides an abstract base class for direct drawings that support physics-based movement.
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 bitmap or image to a rectangular region with support for scaling modes, source clipping,...
DirectImage SetScaleMode(ScaleMode mode)
Sets how the image is scaled to fit within the destination rectangle.
DirectImage SetTint(SKColor color)
Applies a color tint (multiplicative blend) to the image.
ScaleMode
Defines how an image is scaled to fit within the destination rectangle.
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 SetColor(Color color)
Sets the base color used for both fill and stroke (unless a distinct border color is specified).
DirectRectangle SetStrokeWidth(float width)
Sets the width (thickness) of the rectangle's stroke (outline) in pixels.
A retained-mode text drawable with wrapping, multi-line ( ) support, horizontal/vertical alignment,...
Definition TextBlock.cs:44
TextBlock SetColors(SKColor fg, SKColor bg)
Sets the foreground (text) and background colors using Skia colors.
Definition TextBlock.cs:430
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
Represents a popup command list owned by a header or submenu item.
override void OnPointerDown(WidgetPointerEventArgs args)
Called when a pointer press begins on the widget.
char? Mnemonic
Gets the explicit, case-insensitive access character.
DirectDrawingMovableBase Marker
Gets the check/radio indicator drawing.
TextBlock ShortcutLabel
Gets the shortcut drawing.
string Text
Gets the command label.
bool IsCheckable
Gets whether this item has check or radio state.
override void OnPointerLeave(WidgetPointerEventArgs args)
Called when a pointer leaves the widget bounds.
MenuItemWidget SetEnabled(bool enabled)
Enables or disables the item.
override void OnPointerClick(WidgetPointerEventArgs args)
Called when a pointer click is dispatched to the widget.
override void OnPointerEnter(WidgetPointerEventArgs args)
Called when a pointer enters the widget bounds.
DirectRectangle Background
Gets the background drawing.
string? RadioGroup
Gets the radio group, scoped to the containing dropdown.
void PerformClick()
Invokes an enabled command, even while its dropdown is closed, or opens its submenu.
KeyGesture? Shortcut
Gets the executable gesture, if any.
Action< MenuItemWidget >? Invoked
Occurs after state changes and hierarchy closure, before the command callback.
override void OnKeyboardInput(WidgetKeyboardEventArgs args)
Called when keyboard input is routed to the widget.
bool IsEnabled
Gets whether this item is enabled.
DirectImage? IconDrawing
Gets the retained icon drawing, if configured.
bool IsChecked
Gets the current checked state.
string ShortcutText
Gets gesture-generated text, or the legacy display-only shortcut text.
MenuDropDownWidget? SubMenu
Gets the child dropdown, if this item owns a submenu.
override void Dispose()
Disposes the composite and every child it owns.
bool IsSelected
Gets whether this item is selected by pointer or keyboard.
SKImage? Icon
Gets the caller-owned image. Keep it alive until the item is disposed.
DirectDrawingMovableBase Arrow
Gets the submenu arrow drawing.
MenuItemWidget SetChecked(bool isChecked)
Changes state without invoking callbacks. Checking a radio item clears its group peers.
string? Key
Gets the immutable optional key, unique within the menu bar.
override void OnPointerUp(WidgetPointerEventArgs args)
Called when a pointer press is released for the widget.
TextBlock Label
Gets the label drawing.
bool CanReceiveFocus
Gets or sets a value indicating whether the widget can receive keyboard focus.
bool IsPointerInputEnabled
Gets or sets a value indicating whether the widget can receive pointer input.
WidgetBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, PointF anchor=default, string? nickname=null)
Initializes a new instance of the WidgetBase class.
Definition WidgetBase.cs:95
bool IsKeyboardInputEnabled
Gets or sets a value indicating whether the widget can receive keyboard input.
bool IsInputEnabled
Gets or sets a value indicating whether the widget can participate in input routing.
bool Handled
Gets or sets whether this widget interaction was handled.
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.
KeyAction
Represents the type of action performed on a keyboard key, indicating whether the key was pressed,...
Definition KeyAction.cs:10
record MenuBarTheme
Defines the dimensions and colors used by menu bar widgets.
A host key code and an exact combination of keyboard modifiers.
Definition KeyGesture.cs:9
override string ToString()
Returns a display label such as Ctrl+O or Alt+F4.
Definition KeyGesture.cs:43