File: widgbase.h

package info (click to toggle)
warzone2100 4.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 660,320 kB
  • sloc: cpp: 676,209; ansic: 391,201; javascript: 78,238; python: 16,632; php: 4,294; sh: 4,094; makefile: 2,629; lisp: 1,492; cs: 489; xml: 404; perl: 224; ruby: 156; java: 89
file content (566 lines) | stat: -rw-r--r-- 15,904 bytes parent folder | download
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/*
	This file is part of Warzone 2100.
	Copyright (C) 1999-2004  Eidos Interactive
	Copyright (C) 2005-2020  Warzone 2100 Project

	Warzone 2100 is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	Warzone 2100 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Warzone 2100; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/** @file
 *  Definitions for the basic widget types.
 */

#ifndef __INCLUDED_LIB_WIDGET_WIDGBASE_H__
#define __INCLUDED_LIB_WIDGET_WIDGBASE_H__

#include "lib/framework/frame.h"
#include "lib/ivis_opengl/piedef.h"
#include "lib/ivis_opengl/textdraw.h"
#include <vector>
#include <functional>
#include <string>
#include <set>
#include <nonstd/optional.hpp>
#include "lib/framework/geometry.h"
#include "lib/framework/wzstring.h"


/* Forward definitions */
class WIDGET;
struct W_CONTEXT;
class W_FORM;
struct W_INIT;
struct W_SCREEN;
class W_EDITBOX;
class W_BARGRAPH;
class W_BUTTON;
class W_LABEL;
class W_SLIDER;
class StateButton;
class ListWidget;
class ScrollBarWidget;
struct WIDGET_KEYSTATE;

/* The display function prototype */
typedef void (*WIDGET_DISPLAY)(WIDGET *psWidget, UDWORD xOffset, UDWORD yOffset);

/* The optional user callback function */
typedef void (*WIDGET_CALLBACK)(WIDGET *psWidget, const W_CONTEXT *psContext);
typedef void (*WIDGET_AUDIOCALLBACK)(int AudioID);

/* The optional "calc layout" callback function, to support runtime layout recalculation */
typedef std::function<void (WIDGET *psWidget)> WIDGET_CALCLAYOUT_FUNC;

// To avoid typing, use the following define to construct a lambda for WIDGET_CALCLAYOUT_FUNC
// psWidget is the widget
// The { } are still required (for clarity).
#define LAMBDA_CALCLAYOUT_SIMPLE(x) [](WIDGET *psWidget) x

/* The optional "onDelete" callback function */
typedef std::function<void (WIDGET *psWidget)> WIDGET_ONDELETE_FUNC;

/* The optional hit-testing function, used for custom hit-testing within the outer bounding rectangle */
typedef std::function<bool (const WIDGET *psWidget, int x, int y)> WIDGET_HITTEST_FUNC;


/* The different base types of widget */
enum WIDGET_TYPE
{
	WIDG_FORM,
	WIDG_LABEL,
	WIDG_BUTTON,
	WIDG_EDITBOX,
	WIDG_BARGRAPH,
	WIDG_SLIDER,
	WIDG_UNSPECIFIED_TYPE,
};

/* The keys that can be used to press a button */
enum WIDGET_KEY
{
	WKEY_NONE,
	WKEY_PRIMARY,
	WKEY_SECONDARY,
};

enum
{
	WIDG_HIDDEN = 0x8000,  ///< The widget is initially hidden
};

// Possible states for a button or clickform.
enum ButtonState
{
	WBUT_DISABLE   = 0x01,  ///< Disable (grey out) a button.
	WBUT_LOCK      = 0x02,  ///< Fix a button down.
	WBUT_CLICKLOCK = 0x04,  ///< Fix a button down but it is still clickable.
	WBUT_FLASH     = 0x08,  ///< Make a button flash.
	WBUT_DOWN      = 0x10,  ///< Button is down.
	WBUT_HIGHLIGHT = 0x20,  ///< Button is highlighted.
};

class WidgetGraphicsContext
{
private:
	Vector2i offset = {0, 0};
	WzRect clipRect = {0, 0, 0, 0};
	bool clipped = false;
	bool allowChildDisplayIfSelfClipped = false;

public:
	int32_t getXOffset() const
	{
		return offset.x;
	}

	int32_t getYOffset() const
	{
		return offset.y;
	}

	bool allowChildDisplayRecursiveIfSelfClipped() const
	{
		return allowChildDisplayIfSelfClipped;
	}

	bool clipContains(WzRect const& rect) const;

	bool clipIntersects(WzRect const& rect, WzRect* output_intersection) const;

	WidgetGraphicsContext translatedBy(int32_t x, int32_t y) const;

	WidgetGraphicsContext clippedBy(WzRect const &newRect) const;

	WidgetGraphicsContext setAllowChildDisplayRecursiveIfSelfClipped(bool val) const;
};

struct WidgetHelp
{
public:
	enum class InteractionTriggers: uint8_t
	{
		PrimaryClick,
		SecondaryClick,
		ClickAndHold,
		Misc
	};
	static constexpr size_t NUM_WIDGET_INTERACTION_TRIGGERS = static_cast<size_t>(InteractionTriggers::Misc) + 1;
	typedef std::set<InteractionTriggers> WidgetInteractionTriggerFlagSet;
	struct InteractionDescription
	{
		WidgetInteractionTriggerFlagSet triggers;
		WzString description;
	};
	struct KeybindingInfo
	{
		std::string keybindingName; // for lookup on display with the input manager
	};
public:
	WzString title;
	WzString description;
	std::vector<InteractionDescription> interactions;
	std::vector<KeybindingInfo> relatedKeybindings;
public:
	WidgetHelp() { }
	WidgetHelp& setTitle(const WzString& newValue)
	{
		title = newValue;
		return *this;
	}
	WidgetHelp& setDescription(const WzString& newValue)
	{
		description = newValue;
		return *this;
	}
	WidgetHelp& addInteraction(WidgetInteractionTriggerFlagSet triggers, const WzString& effectDescription)
	{
		interactions.push_back({triggers, effectDescription});
		return *this;
	}
	WidgetHelp& addRelatedKeybinding(const std::string& keybindingName)
	{
		relatedKeybindings.push_back({keybindingName});
		return *this;
	}
};

/* The base widget data type */
class WIDGET: public std::enable_shared_from_this<WIDGET>
{

public:
	typedef std::vector<std::shared_ptr<WIDGET>> Children;

	WIDGET(WIDGET_TYPE type = WIDG_UNSPECIFIED_TYPE);
	WIDGET(W_INIT const *init, WIDGET_TYPE type = WIDG_UNSPECIFIED_TYPE);
	virtual ~WIDGET();

	void deleteLater();  ///< Like "delete this;", but safe to call from display/run callbacks.

	virtual void widgetLost(WIDGET *);

	virtual void focusLost() {}
	virtual void clicked(W_CONTEXT *, WIDGET_KEY = WKEY_PRIMARY) {}
	virtual std::string getTip()
	{
		return "";
	}
	virtual WidgetHelp const * getHelp() const
	{
		return nullptr;
	}

	virtual bool capturesMouseDrag(WIDGET_KEY) { return false; }

	virtual void released(W_CONTEXT *, WIDGET_KEY = WKEY_PRIMARY) {}
	virtual void highlight(W_CONTEXT *) {}
	virtual void highlightLost() {}

protected:
	virtual void run(W_CONTEXT *) {}
	virtual void display(int, int) {}
	virtual void geometryChanged() {}

	virtual bool hitTest(int x, int y) const;

	// handling mouse drag
	virtual void mouseDragged(WIDGET_KEY, W_CONTEXT *start, W_CONTEXT *current) {}

public:
	virtual unsigned getState() const;
	virtual void setState(unsigned state);
	virtual void setFlash(bool enable);
	virtual WzString getString() const;
	virtual void setString(WzString string);
	virtual void setTip(std::string string); // tooltip
	virtual void setHelp(optional<WidgetHelp> help); // formatted help information for this UI element

	virtual void screenSizeDidChange(int oldWidth, int oldHeight, int newWidth, int newHeight); // used to handle screen resizing

	void show(bool doShow = true)
	{
		style = (style & ~WIDG_HIDDEN) | (!doShow * WIDG_HIDDEN);
	}
	void hide()
	{
		show(false);
	}
	bool visible()
	{
		return (style & WIDG_HIDDEN) == 0;
	}

	void setTip(char const *stringUtf8)
	{
		setTip((stringUtf8 != nullptr) ? std::string(stringUtf8) : std::string());
	}

	std::shared_ptr<WIDGET> parent() const
	{
		return parentWidget.lock();
	}
	Children const &children() const
	{
		return childWidgets;
	}
	void removeAllChildren()
	{
		for (auto& child : childWidgets)
		{
			if (child->parent().get() == this)
			{
				child->parentWidget.reset();
				child->setScreenPointer(nullptr);
			}
		}
		childWidgets = {};
	}
	WzRect screenGeometry() const
	{
		return WzRect(screenPosX(), screenPosY(), width(), height());
	}
	WzRect const &geometry() const
	{
		return dim;
	}
	int x() const
	{
		return dim.x();
	}
	int y() const
	{
		return dim.y();
	}
	virtual int parentRelativeXOffset(int coord) const
	{
		return x() + coord;
	}
	virtual int parentRelativeYOffset(int coord) const
	{
		return y() + coord;
	}
	int screenPosX() const
	{
		int screenX = x();
		for (auto psParent = parent(); psParent != nullptr; psParent = psParent->parent())
		{
			screenX = psParent->parentRelativeXOffset(screenX);
		}
		return screenX;
	}
	int screenPosY() const
	{
		int screenY = y();
		for (auto psParent = parent(); psParent != nullptr; psParent = psParent->parent())
		{
			screenY = psParent->parentRelativeYOffset(screenY);
		}
		return screenY;
	}
	bool hasAncestor(const WIDGET* psWidget) const
	{
		for (auto psParent = parent(); psParent != nullptr; psParent = psParent->parent())
		{
			if (psParent.get() == psWidget)
			{
				return true;
			}
		}
		return false;
	}
	int width() const
	{
		return dim.width();
	}
	int height() const
	{
		return dim.height();
	}
	void move(int x, int y)
	{
		setGeometry(WzRect(x, y, width(), height()));
	}
	void setGeometry(int x, int y, int w, int h)
	{
		setGeometry(WzRect(x, y, w, h));
	}
	void setGeometry(WzRect const &r);
	virtual void setGeometryFromScreenRect(WzRect const &r);

	enum class ChildZPos {
		Front,
		Back
	};

	void attach(const std::shared_ptr<WIDGET> &widget, ChildZPos zPos = ChildZPos::Front);
	/**
	 * @deprecated use `void WIDGET::attach(const std::shared_ptr<WIDGET> &widget)` instead
	 **/
	void attach(WIDGET *widget) { attach(widget->shared_from_this()); }

	void detach(const std::shared_ptr<WIDGET> &widget);
	/**
	 * @deprecated use `void WIDGET::detach(const std::shared_ptr<WIDGET> &widget)` instead
	 **/
	void detach(WIDGET *widget) { detach(widget->shared_from_this()); }

	void setCalcLayout(const WIDGET_CALCLAYOUT_FUNC& calcLayoutFunc);
	void callCalcLayout();

	void setOnDelete(const WIDGET_ONDELETE_FUNC& onDeleteFunc);

	void setCustomHitTest(const WIDGET_HITTEST_FUNC& newCustomHitTestFunc);

	bool isMouseOverWidget() const;

	void setTransparentToClicks(bool hasClickTransparency);
	void setTransparentToMouse(bool hasMouseTransparency);
	bool transparentToClicks() const;
	bool transparentToMouse() const { return isTransparentToMouse; }

	virtual int32_t idealWidth();
	virtual int32_t idealHeight();

	void manuallyCallRun(W_CONTEXT *);

	virtual nonstd::optional<std::vector<uint32_t>> getScrollSnapOffsets()
	{
		return nonstd::nullopt;
	}

	UDWORD                  id;                     ///< The user set ID number for the widget. This is returned when e.g. a button is pressed.
	WIDGET_TYPE             type;                   ///< The widget type
	UDWORD                  style;                  ///< The style of the widget
	WIDGET_DISPLAY          displayFunction;        ///< Override function to display the widget.
	WIDGET_CALLBACK         callback;               ///< User callback (if any)
	void                   *pUserData;              ///< Pointer to a user data block (if any)
	UDWORD                  UserData;               ///< User data (if any)
	std::weak_ptr<W_SCREEN> screenPointer;          ///< Pointer to screen the widget is on (if attached).

protected:
	nonstd::optional<int32_t> defaultIdealWidth;
	nonstd::optional<int32_t> defaultIdealHeight;

private:
	WIDGET_CALCLAYOUT_FUNC  calcLayout;				///< Optional calc layout callback
	WIDGET_ONDELETE_FUNC	onDelete;				///< Optional callback called when the Widget is about to be deleted
	WIDGET_HITTEST_FUNC		customHitTest;			///< Optional hit-testing custom function
protected:
	friend struct W_SCREEN;
	void setScreenPointer(const std::shared_ptr<W_SCREEN> &screen); ///< Set screen pointer for us and all children.
public:
	// Recursively find the target widget for this context + mouse event
	// Updates psContext with the context for the return (mouse over) widget
	// NOTE: Does not actually trigger events (that's handled by higher-level code, like widgRunScreen)
	//       but passes in the `key` & `wasPressed` info anyway because some special widgets like to know
	//		 if an event will impact a descendant widget.
	virtual std::shared_ptr<WIDGET> findMouseTargetRecursive(W_CONTEXT *psContext, WIDGET_KEY key, bool wasPressed);

	std::shared_ptr<WIDGET> processClick(W_CONTEXT *psContext, WIDGET_KEY key, bool wasPressed);

	virtual void runRecursive(W_CONTEXT *psContext);
	void processCallbacksRecursive(W_CONTEXT *psContext);
	virtual void displayRecursive(WidgetGraphicsContext const &context);  ///< Display this widget, and all visible children.
	void displayRecursive()
	{
		WidgetGraphicsContext context;
		displayRecursive(context);
	}
	static void processMouseDragEvent(const W_CONTEXT &sContext, WIDGET_KEY wkey, WIDGET_KEYSTATE* pState, bool alsoTriggerReleased);

private:
	std::weak_ptr<WIDGET> parentWidget;
	std::vector<std::shared_ptr<WIDGET>> childWidgets;

	WzRect                  dim;
	bool					isTransparentToClicks = false;
	bool					isTransparentToMouse = false;

	WIDGET(WIDGET const &) = delete;
	WIDGET &operator =(WIDGET const &) = delete;

public:
	bool dirty; ///< Whether widget is changed and needs to be redrawn
public:
	friend bool isMouseOverScreenOverlayChild(int mx, int my);
};


struct WidgetTrigger
{
	std::shared_ptr<WIDGET> widget;
};
typedef std::vector<WidgetTrigger> WidgetTriggers;

/* The screen structure which stores all info for a widget screen */
struct W_SCREEN: public std::enable_shared_from_this<W_SCREEN>
{
protected:
	W_SCREEN(): TipFontID(font_regular) {}
	virtual ~W_SCREEN();
	void initialize(const std::shared_ptr<W_FORM>& customRootForm);

public:
	static std::shared_ptr<W_SCREEN> make(std::shared_ptr<W_FORM> customRootForm = nullptr)
	{
		class make_shared_enabler: public W_SCREEN {};
		auto screen = std::make_shared<make_shared_enabler>();
		screen->initialize(customRootForm);
		return screen;
	}

	void setFocus(const std::shared_ptr<WIDGET> &widget);  ///< Sets psFocus, notifying the old widget, if any.
	void setReturn(const std::shared_ptr<WIDGET> &psWidget);  ///< Adds psWidget to retWidgets.
	void screenSizeDidChange(unsigned int oldWidth, unsigned int oldHeight, unsigned int newWidth, unsigned int newHeight); // used to handle screen resizing

	std::shared_ptr<W_FORM> psForm; ///< The root form of the screen
	std::weak_ptr<WIDGET> psFocus;  ///< The widget that has keyboard focus
	std::weak_ptr<WIDGET> lastHighlight; ///< The last widget to be highlighted. This is used to track when the mouse moves off something.
	iV_fonts         TipFontID;     ///< ID of the IVIS font to use for tool tips.
	WidgetTriggers   retWidgets;    ///< The widgets to be returned by widgRunScreen.

	std::shared_ptr<WIDGET> getWidgetWithFocus() const
	{
		return psFocus.lock();
	}

	bool hasFocus(WIDGET const &widget) const
	{
		return psFocus.lock().get() == &widget;
	}

	bool isLastHighlight(WIDGET const &widget) const
	{
		return lastHighlight.lock().get() == &widget;
	}

private:
	W_SCREEN(W_SCREEN const &) = delete;
	W_SCREEN &operator =(W_SCREEN const &) = delete;
};

/* Context information to pass into the widget functions */
struct W_CONTEXT
{
public:
	SDWORD		xOffset, yOffset;	// Screen offset of the parent form
	SDWORD		mx, my;				// mouse position on the form

private:
	W_CONTEXT()
	: xOffset(0)
	, yOffset(0)
	, mx(0)
	, my(0)
	{ }
public:
	static W_CONTEXT ZeroContext()
	{
		return W_CONTEXT();
	}
	W_CONTEXT(SDWORD xOffset, SDWORD yOffset, SDWORD mx, SDWORD my)
	: xOffset(xOffset)
	, yOffset(yOffset)
	, mx(mx)
	, my(my)
	{ }
	W_CONTEXT(const W_CONTEXT& other) = default;
	W_CONTEXT(const W_CONTEXT* other)
	: xOffset(0)
	, yOffset(0)
	, mx(0)
	, my(0)
	{
		ASSERT_OR_RETURN(, other, "Initializing with null W_CONTEXT");
		*this = *other;
	}
	W_CONTEXT& operator=(const W_CONTEXT& other) = default;
	inline bool operator== (const W_CONTEXT &b) const
	{
		return (xOffset == b.xOffset && yOffset == b.yOffset
				&& mx == b.mx && my == b.my);
	}
public:
	inline W_CONTEXT convertToScreenContext()
	{
		W_CONTEXT screenContext(*this);
		screenContext.mx += screenContext.xOffset;
		screenContext.my += screenContext.yOffset;
		screenContext.xOffset = 0;
		screenContext.yOffset = 0;
		return screenContext;
	}
};

#endif // __INCLUDED_LIB_WIDGET_WIDGBASE_H__