Debian Codegraph @

src/libs/gui_tk/gui_tk.h

raw symbols SCIP
1 /** \mainpage gui::tk - framework-agnostic C++ GUI toolkit
2 *
3 * \section i Introduction
4 *
5 * gui::tk is a simple one-file C++ GUI toolkit for use with arbitrary
6 * memory framebuffers.
7 *
8 * \section f Features
9 *
10 * \li small source and binary code size
11 * \li reasonable performance and memory usage
12 * \li comfortable usage
13 * \li suitable for embedded usage: integer math only
14 * \li extensibility via OO
15 * \li non-intrusive: can be integrated with any event mechanism of your liking
16 * \li no dependencies apart from standards-conformant ANSI C++ (including a little STL)
17 * \li support for different encodings, single- and multibyte
18 * \li flexible font support
19 *
20 * \section o Overview
21 *
22 * The toolkit draws on a surface you provide, using any size or pixel format.
23 * Create a GUI::Screen with the buffer to draw on, then pass that object
24 * (or a GUI::Window created from it) to all other widgets' constructors.
25 *
26 * It doesn't provide an own event loop. Instead, it relies on you passing events
27 * and updating the screen regularly. This way, it can easily be integrated with
28 * any event loop available (SDL, Qt, glib, X11, Win32, selfmade, ...)
29 *
30 * Many functions and concepts were taken from other well-known toolkits, so if you
31 * know Qt, Java or wxWindows, you may encounter (intentional) similarities. However,
32 * simplicity of code has been given priority over maximum optimization and pixel-exact
33 * replication of their appearance.
34 *
35 * A note about font support and encodings: All text-related functions use templates to
36 * support any encoding. Fonts define the charset.
37 *
38 * \section g Getting Started
39 *
40 * gui::tk contains an SDL adapter, so if your program is already using SDL,
41 * things are really easy. The rough sequence to get up and running is:
42 *
43 * \code
44 * // setup a suitable video mode with SDL
45 * SDL_surface *screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
46 *
47 * // add a default font, you will most probably need it
48 * GUI::Font::addFont("default",new GUI::BitmapFont(testfont,14,10));
49 *
50 * // create the root-level screen object, the parent of all top-level windows
51 * GUI::ScreenSDL guiscreen(screen);
52 *
53 * // create any amount of toplevel windows you like
54 * GUI::ToplevelWindow *frame = new GUI::ToplevelWindow(&guiscreen, 205, 100, 380, 250, "gui::tk example");
55 *
56 * // add some GUI elements to the toplevel window
57 * GUI::Button *b = new GUI::Button(frame,8,20,"Quit");
58 *
59 * // Define and add an event handler
60 * struct quit : public GUI::ActionEventSource_Callback {
61 * void actionExecuted(GUI::ActionEventSource *b, const GUI::String &arg) {
62 * exit(0);
63 * }
64 * } ex;
65 * b->addActionHandler(&ex);
66 *
67 * // Enter an event loop, calling update() regularly.
68 * SDL_Event event;
69 * while (1) {
70 * while (SDL_PollEvent(&event)) {
71 * if (!guiscreen.event(event)) { // gui::tk didn't handle that event
72 * if (event.type == SDL_QUIT) exit(0);
73 * }
74 * }
75 *
76 * guiscreen.update(4); // 4 ticks = 40ms
77 * SDL_UpdateRect(screen, 0, 0, screen->w, screen->h);
78 *
79 * SDL_Delay(40); // wait 40ms
80 * }
81 * \endcode
82 *
83 * Look at gui_tk.h for more detailed documentation and reference of all classes.
84 *
85 * A test program that shows off the capabilities of gui::tk is available as part of gui_tk.cpp.
86 *
87 * \section l License
88 *
89 * Copyright (C) 2005-2007 Jörg Walter
90 *
91 * gui::tk is free software; you can redistribute it and/or modify
92 * it under the terms of the GNU General Public License as published by
93 * the Free Software Foundation; either version 3 of the License, or
94 * (at your option) any later version.
95 *
96 * gui::tk is distributed in the hope that it will be useful,
97 * but WITHOUT ANY WARRANTY; without even the implied warranty of
98 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
99 * GNU General Public License for more details.
100 *
101 * You should have received a copy of the GNU General Public License
102 * along with this program. If not, see <http://www.gnu.org/licenses/>
103 */
104
105 /* $Id: gui_tk.h,v 1.6 2009-05-17 15:28:05 c2woody Exp $ */
106
107 #ifndef GUI__TOOLKIT_H
108 #define GUI__TOOLKIT_H
109
110 #define imin(x,y) ((x)<(y)?(x):(y))
111 #define imax(x,y) ((x)>(y)?(x):(y))
112 #define isign(x) (((x)<0?-1:1))
113
114 /** \file
115 * \brief Header file for gui::tk.
116 *
117 * All you need to do is to include "gui_tk.h". If you want SDL support, then include \c SDL.h first.
118 */
119
120 #ifdef _MSC_VER
121 typedef signed __int8 int8_t;
122 typedef signed __int16 int16_t;
123 typedef signed __int32 int32_t;
124 typedef unsigned __int8 uint8_t;
125 typedef unsigned __int16 uint16_t;
126 typedef unsigned __int32 uint32_t;
127 #else
128 #include <stdint.h>
129 #endif
130
131 #include <list>
132 #include <map>
133 #include <vector>
134 #include <typeinfo>
135 #include <string>
136 #include <iostream>
137
138 /// This namespace contains all GUI toolkit classes, types and functions.
139 namespace GUI {
140
141 /// ARGB 24-bit color value: (a<<24)|(r<<16)|(g<<8)|(b)
142 typedef uint32_t RGB;
143
144 /// Collection of all color-related constants and functions.
145 namespace Color {
146 /// A fully transparent pixel.
147 const RGB Transparent = 0x00ffffff;
148
149 /// A fully opaque black pixel.
150 const RGB Black = 0xff000000;
151
152 /// A fully opaque white pixel.
153 const RGB White = 0xffffffff;
154
155 /// Alpha mask.
156 const RGB AlphaMask = 0xff000000;
157
158 /// Offset of alpha value.
159 const int AlphaShift = 24;
160
161 /// Red mask.
162 const RGB RedMask = 0x00ff0000;
163
164 /// Full-intensity red.
165 const RGB Red = Black|RedMask;
166
167 /// Offset of red value.
168 const int RedShift = 16;
169
170 /// Green mask.
171 const RGB GreenMask = 0x0000ff00;
172
173 /// Full-intensity green.
174 const RGB Green = Black|GreenMask;
175
176 /// Offset of green value.
177 const int GreenShift = 8;
178
179 /// Blue mask.
180 const RGB BlueMask = 0x000000ff;
181
182 /// Full-intensity blue.
183 const RGB Blue = Black|BlueMask;
184
185 /// Offset of blue value.
186 const int BlueShift = 0;
187
188 /// Full-intensity Magenta.
189 const RGB Magenta = Red|Blue;
190
191 /// Magenta mask.
192 const RGB MagentaMask = RedMask|BlueMask;
193
194 /// Full-intensity Cyan.
195 const RGB Cyan = Green|Blue;
196
197 /// Cyan mask.
198 const RGB CyanMask = GreenMask|BlueMask;
199
200 /// Full-intensity Yellow.
201 const RGB Yellow = Red|Green;
202
203 /// Yellow mask.
204 const RGB YellowMask = RedMask|GreenMask;
205
206 /// 50% grey
207 const RGB Grey50 = 0xff808080;
208
209 /// Background color for 3D effects. May be customized.
210 extern RGB Background3D;
211
212 /// Light highlight color for 3D effects. May be customized.
213 extern RGB Light3D;
214
215 /// Dark highlight color (shadow) for 3D effects. May be customized.
216 extern RGB Shadow3D;
217
218 /// Generic border color for highlights or similar. May be customized.
219 extern RGB Border;
220
221 /// Foreground color for regular content (mainly text). May be customized.
222 extern RGB Text;
223
224 /// Background color for inactive areas. May be customized.
225 extern RGB Background;
226
227 /// Background color for selected areas. May be customized.
228 extern RGB SelectionBackground;
229
230 /// Foreground color for selected areas. May be customized.
231 extern RGB SelectionForeground;
232
233 /// Background color for inputs / application area. May be customized.
234 extern RGB EditableBackground;
235
236 /// Title bar color for windows. May be customized.
237 extern RGB Titlebar;
238
239 /// Title bar text color for windows. May be customized.
240 extern RGB TitlebarText;
241
242 /// Convert separate r, g, b and a values (each 0-255) to an RGB value.
243 static inline RGB rgba(int r, int g, int b, int a=0) {
244 return (((r&255)<<RedShift)|((g&255)<<GreenShift)|((b&255)<<BlueShift)|((a&255)<<AlphaShift));
245 }
246
247 /// Get red value (0-255) from an RGB value.
248 static inline int R(RGB val) { return ((val&Color::RedMask)>>Color::RedShift); }
249 /// Get green value (0-255) from an RGB value.
250 static inline int G(RGB val) { return ((val&Color::GreenMask)>>Color::GreenShift); }
251 /// Get blue value (0-255) from an RGB value.
252 static inline int B(RGB val) { return ((val&Color::BlueMask)>>Color::BlueShift); }
253 /// Get alpha value (0-255) from an RGB value.
254 static inline int A(RGB val) { return ((val&Color::AlphaMask)>>Color::AlphaShift); }
255
256 }
257
258 /// Identifies a mouse button.
259 enum MouseButton { NoButton, Left, Right, Middle, WheelUp, WheelDown, WheelLeft, WheelRight };
260
261 /// A type which holds size values that can be very large.
262 typedef unsigned int Size;
263
264 /// A type which holds a single character. Large enough for Unicode.
265 typedef uint32_t Char;
266
267 /// A type which holds a number of timer ticks.
268 typedef unsigned int Ticks;
269
270 /// Identifies a keyboard key.
271 class Key {
272 public:
273 /// Translated character value.
274 /** No encoding is implied. The Font that is used to display this character
275 * determines the appearance. */
276 Char character;
277 /// Special keyboard keys.
278 /** It is modeled after PC keyboards. When you feed keyboard events to a GUI::Screen,
279 * try to map native keys to this set. Some special keys have a character value. Set
280 * to \c None if the key has no special meaning. */
281 enum Special {
282 None,
283 F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
284 Up, Down, Left, Right, Backspace, Tab, Backtab, Enter, Escape,
285 Home, End, PageUp, PageDown, Insert, Delete, Menu,
286 Print, Pause, Break, CapsLock, NumLock, ScrollLock,
287 Alt, Ctrl, Shift, Windows
288 } special;
289 /// Set if the Shift key is currently down.
290 bool shift;
291 /// Set if the Ctrl key is currently down.
292 bool ctrl;
293 /// Set if the Alt (PC) or Meta (classic Unix) key is currently down.
294 bool alt;
295 /// Set if the "Windows"/Meta (PC) or Super (classic Unix) key is currently down.
296 /** Do not depend too heavily on this, as many keyboards and systems do not have such a key. */
297 bool windows;
298
299 /// Constructor.
300 Key(int character, Special special, bool shift, bool ctrl, bool alt, bool windows) :
301 character(character), special(special),
302 shift(shift), ctrl(ctrl), alt(alt), windows(windows) {}
303 };
304
305 class Drawable;
306 class String;
307
308 /** \brief Converts between strings of various types and String objects.
309 *
310 * It is used to deal with string encoding. It is intended to be used with template
311 * specializations. Having such a specialization means you can feed the corresponding type to
312 * all functions that expect a string -- without any conversion. You can add specializations
313 * yourself in your program's code to deal with unsupported types.
314 *
315 * As an example, see the std::string version.
316 *
317 * Encodings, as opposed to character sets, define how bytes map to character values.
318 * ASCII, for example, has an \em encoding where each byte is one character, while the
319 * ASCII \em character \em set says that values 0-127 are valid and 65 is the upper case
320 * letter 'A'. UTF-8 has 1-6 bytes per character, and the character set is unicode.
321 *
322 * GUI::Font deals with the character set, and this class encapsulates encodings.
323 *
324 */
325 template <typename STR> class NativeString {
326 protected:
327 friend class String;
328
329 /// Converts a native string into a String object
330 static void getString(String &dest, const STR &src) { STR::_this_string_type_is_not_supported_(); }
331
332 /** \brief Converts a string object to native representation.
333 *
334 * If some characters cannot be converted, they should silently be skipped. Apart from that,
335 * \c nativeString(stringNative(String(),X)) should be value-equal to \c X.
336 */
337 static STR& getNative(const String &src) { STR::_this_string_type_is_not_supported_();return*new STR(); }
338 };
339
340 template <typename STR> class NativeString<STR*> {
341 protected:
342 friend class String;
343 static void getString(String &dest, const STR *src);
344 static STR* getNative(const String &src);
345 };
346
347 template <typename STR, Size N> class NativeString<STR[N]> : public NativeString<STR*> {};
348 template <typename STR, Size N> class NativeString<const STR[N]> : public NativeString<STR*> {};
349 template <typename STR> class NativeString<const STR*> : public NativeString<STR*> {};
350
351 /// 'less-than' comparison between pointer addresses
352 struct ltvoid { bool operator()(const void* s1, const void* s2) const { return s1 < s2; } };
353
354 /** \brief Simple STL-based string class.
355 *
356 * This is intended as internal helper class to allow gui::tk to work with any kind of
357 * string objects. While you can use this in normal application code, you should better
358 * use the string class of your application framework (like Qt). If you don't have any,
359 * use std::string.
360 *
361 * It supports arbitrary characters, no character set is implied. Conversion from/to usual
362 * string types like \c char* is automatic but not thread-safe for non-class types.
363 */
364 class String : public std::vector<Char> {
365 protected:
366 template <typename STR> friend class NativeString;
367 /// Simple pointer encapsulation class for memory management.
368 class Native { public: virtual ~Native() {}; };
369 /// Simple pointer encapsulation class for memory management.
370 template <typename STR> class NativeArray: public Native {
371 STR *data;
372 public:
373 NativeArray(STR *data) : data(data) {}
374 virtual ~NativeArray() { delete[] data; }
375 };
376 template <typename STR> class NativeObject: public Native {
377 STR *data;
378 public:
379 NativeObject(STR *data) : data(data) {}
380 virtual ~NativeObject() { delete data; }
381 };
382
383 private:
384 /// Semi-static memory management for pointer string types.
385 mutable std::map<const class std::type_info *, Native *, ltvoid> strings;
386
387 protected:
388 /// Manage a native string's memory.
389 void addNative(Native *dest) const {
390 const class std::type_info &type = typeid(dest);
391 if (strings[&type] != NULL) delete strings[&type];
392 strings[&type] = dest;
393 }
394
395 public:
396 /// Allocate a new String initialized from native string.
397 template <typename STR> String(const STR& src) { NativeString<STR>::getString(*this, src); }
398
399 /// Taken from STL.
400 template <class InputIterator> String(InputIterator a, InputIterator b) : std::vector<Char>(a,b) {}
401
402 /// Copy-constructor
403 String(const String &src) : std::vector<Char>(src), strings() {};
404
405 /// Allocate a new String.
406 String() { }
407
408 /// Deallocate a String.
409 ~String() {
410 for (std::map<const class std::type_info *, Native *, ltvoid>::iterator i = strings.begin(); i != strings.end(); ++i)
411 delete (*i).second;
412 };
413
414 /// Convert to native representation.
415 /** For pointer types like \c char*, the returned pointer is usually only valid as long as
416 * this object exists, or until it is modified and cast to the same type again. */
417 template <typename T> operator T() const { return NativeString<T>::getNative(*this); }
418
419 /// Compare with native representation.
420 template <typename T> bool operator==(const T &src) const { return *this == String(src); }
421 /// Compare with other Strings.
422 bool operator==(const String &src) const { return *(std::vector<Char>*)this == src; }
423
424 /// Compare with native representation.
425 template <typename T> bool operator!=(const T &src) const { return *this != String(src); }
426 /// Compare with other Strings.
427 bool operator!=(const String &src) const { return *(std::vector<Char>*)this != src; }
428 };
429
430 template <typename STR> void NativeString<STR*>::getString(String &dest, const STR* src) {
431 Size strlen = 0;
432 while (src[strlen]) strlen++;
433 dest.resize(strlen);
434 for (strlen = 0; src[strlen]; strlen++) dest[strlen] = (sizeof(STR)==1?(unsigned char)src[strlen]:sizeof(STR)==2?(unsigned short)src[strlen]:src[strlen]);
435 }
436
437 template <typename STR> STR* NativeString<STR*>::getNative(const String &src) {
438 Size strlen = (Size)src.size();
439 STR* dest = new STR[strlen+1];
440 dest[strlen] = 0;
441 for (; strlen > 0; strlen--) dest[strlen-1] = src[strlen-1];
442 src.addNative(new String::NativeArray<const STR>(dest));
443 return dest;
444 }
445
446 template <> class NativeString<std::string*> {
447 protected:
448 friend class String;
449 static void getString(String &dest, const std::string *src) {
450 Size strlen = (Size)src->length();
451 dest.resize(strlen);
452 for (Size i = 0; i< strlen; i++) dest[i] = (*src)[i];
453 }
454 static std::string* getNative(const String &src) {
455 Size strlen = (Size)src.size();
456 std::string* dest = new std::string();
457 for (Size i = 0; i < strlen; i++) dest->append(1,src[i]);
458 src.addNative(new String::NativeObject<std::string>(dest));
459 return dest;
460 }
461 };
462
463 template <> class NativeString<const std::string*> : public NativeString<std::string*> {};
464
465 template <> class NativeString<std::string> {
466 protected:
467 friend class String;
468 static void getString(String &dest, const std::string &src) {
469 Size strlen = (Size)src.length();
470 dest.resize(strlen);
471 for (Size i = 0; i< strlen; i++) dest[i] = src[i];
472 }
473 static std::string& getNative(const String &src) {
474 Size strlen = (Size)src.size();
475 std::string* dest = new std::string();
476 for (Size i = 0; i < strlen; i++) dest->append(1,src[i]);
477 src.addNative(new String::NativeObject<std::string>(dest));
478 return *dest;
479 }
480 };
481
482 template <> class NativeString<const std::string> : public NativeString<std::string> {};
483
484 class ToplevelWindow;
485 class Menu;
486 class TransientWindow;
487 class Screen;
488 class Window;
489
490 /// Callback for window events.
491 struct Window_Callback {
492 public:
493 /// Called whenever this window changes position.
494 virtual void windowMoved(Window *win, int x, int y) = 0;
495 virtual ~Window_Callback() {}
496 };
497
498
499 /** \brief A Window is a rectangular sub-area of another window.
500 *
501 * Windows are arranged hierarchically. A Window cannot leave its parent's
502 * area. They may contain their own buffer or share it with their parent.
503 *
504 * Usually, every GUI element is a subclass of Window. Note that this is
505 * \em not a GUI window with decorations like border and title bar. See ToplevelWindow
506 * for that.
507 */
508 class Window {
509 protected:
510 friend class ToplevelWindow;
511 friend class TransientWindow;
512 friend class Menu;
513
514 /// Width of the window.
515 int width;
516 /// Height of the window.
517 int height;
518 /// X position relative to parent.
519 int x;
520 /// Y position relative to parent.
521 int y;
522
523 /// \c true if anything changed in this window or one of it's children
524 bool dirty;
525
526 /// \c true if this window should be visible on screen.
527 bool visible;
528
529 /// Parent window.
530 Window *const parent;
531
532 /// Child window of last button-down event
533 /** It receives all drag/up/click/doubleclick events until an up event is received */
534 Window *mouseChild;
535
536 /// Child windows.
537 /** Z ordering is done in list order. The first element is the lowermost
538 * window. This window's content is below all children. */
539 std::list<Window *> children;
540
541 /// List of registered event handlers.
542 std::list<Window_Callback *> movehandlers;
543
544 /// Register child window.
545 virtual void addChild(Window *child);
546
547 /// Remove child window.
548 virtual void removeChild(Window *child);
549
550 /// Mark this window and all parents as dirty.
551 void setDirty() { if (dirty) return; dirty = true; if (parent != NULL) parent->setDirty(); };
552
553 /// Replace clipboard content.
554 virtual void setClipboard(const String &s) { parent->setClipboard(s); };
555
556 /// Get clipboard content.
557 virtual const String& getClipboard() { return parent->getClipboard(); };
558
559 /// Default constructor. Only used in class Screen. Do not use.
560 Window();
561
562 /// Called whenever the focus changes.
563 virtual void focusChanged(bool gained) {
564 if (children.size() > 0) children.back()->focusChanged(gained);
565 }
566
567 public:
568
569 /// Add an event handler.
570 void addWindowHandler(Window_Callback *handler) { movehandlers.push_back(handler); }
571
572 /// Remove an event handler.
573 void removeWindowHandler(Window_Callback *handler) { movehandlers.remove(handler); }
574
575 /// Create a subwindow of the given parent window.
576 Window(Window *parent, int x, int y, int w, int h);
577
578 /// Destructor.
579 virtual ~Window();
580
581 /// Resize this window to the given dimensions.
582 /** If that would move part of the window outside of this window's area,
583 * the outside area will silently be clipped while drawing. */
584 virtual void resize(int w, int h);
585 /// Return this window's width
586 virtual int getWidth() const { return width; }
587 /// Return this window's height
588 virtual int getHeight() const { return height; }
589
590 /// Move this window to the given position relative to the parent window's origin.
591 /** If that would move part of the window outside of this window's area,
592 * the outside area will silently be clipped while drawing. */
593 virtual void move(int x, int y);
594 /// Return this window's X position relative to the parent's top left corner
595 virtual int getX() const { return x; }
596 /// Return this window's Y position relative to the parent's top left corner
597 virtual int getY() const { return y; }
598 /// Return this window's contents' X position relative to the screen's top left corner
599 virtual int getScreenX() const { return (parent == NULL?0:parent->getScreenX()+x); }
600 /// Return this window's contents' Y position relative to the screen's top left corner
601 virtual int getScreenY() const { return (parent == NULL?0:parent->getScreenY()+y); }
602
603 /// Draw this window's content including all children.
604 virtual void paintAll(Drawable &d) const;
605
606 /// Draw this window's content.
607 virtual void paint(Drawable &d) const {};
608
609 /// Show or hide this window.
610 /** By default, most windows are shown when created. Hidden windows do not receive any events. */
611 virtual void setVisible(bool v) { visible = !!v; parent->setDirty(); }
612
613 /// Returns \c true if this window is visible.
614 virtual bool isVisible() const { return (!parent || parent->isVisible()) && visible; }
615
616 /// Return parent window.
617 /** May return NULL if this is the topmost window (the Screen). */
618 Window *getParent() const { return parent; }
619
620 /// Get the topmost window (the Screen)
621 Screen *getScreen();
622
623 /// Returns \c true if this window has currently the keyboard focus.
624 virtual bool hasFocus() const { return parent->hasFocus() && *parent->children.rbegin() == this; }
625
626 /// Mouse was moved. Returns true if event was handled.
627 virtual bool mouseMoved(int x, int y);
628 /// Mouse was moved while a button was pressed. Returns true if event was handled.
629 virtual bool mouseDragged(int x, int y, MouseButton button);
630 /// Mouse was pressed. Returns true if event was handled.
631 virtual bool mouseDown(int x, int y, MouseButton button);
632 /// Mouse was released. Returns true if event was handled.
633 virtual bool mouseUp(int x, int y, MouseButton button);
634 /// Mouse was clicked. Returns true if event was handled.
635 /** Clicking means pressing and releasing the mouse button while not moving it. */
636 virtual bool mouseClicked(int x, int y, MouseButton button);
637 /// Mouse was double-clicked. Returns true if event was handled.
638 virtual bool mouseDoubleClicked(int x, int y, MouseButton button);
639
640 /// Key was pressed. Returns true if event was handled.
641 virtual bool keyDown(const Key &key);
642 /// Key was released. Returns true if event was handled.
643 virtual bool keyUp(const Key &key);
644
645 /// Put this window on top of all it's siblings. Preserves relative order.
646 /** Returns true if the window accepts the raise request. */
647 virtual bool raise() {
648 Window *last = parent->children.back();
649 for (Window *cur = parent->children.back(); cur != this; cur = parent->children.back()) {
650 parent->children.remove(cur);
651 parent->children.push_front(cur);
652 }
653 if (last != this) {
654 focusChanged(true);
655 last->focusChanged(false);
656 }
657 parent->setDirty();
658 return true;
659 }
660
661 /// Put this window below all of it's siblings. Does not preserve relative order.
662 virtual void lower() {
663 parent->children.remove(this);
664 parent->children.push_front(this);
665 if (this != parent->children.back()) {
666 parent->children.back()->focusChanged(true);
667 focusChanged(false);
668 }
669 parent->setDirty();
670 }
671
672 /// Return the \p n th child
673 Window *getChild(int n) {
674 for (std::list<Window *>::const_iterator i = children.begin(); i != children.end(); ++i) {
675 if (n--) return *i;
676 }
677 return NULL;
678 }
679
680 };
681
682 /** \brief A Screen represents the framebuffer that is the final destination of the GUI.
683 *
684 * It's main purpose is to manage the current contents of the surface and to combine
685 * it with all GUI elements. You can't resize and move the screen. Requests to do so
686 * will be ignored.
687 *
688 * This is an abstract base class. You need to use a subclass which implements rgbToSurface
689 * and surfaceToRGB.
690 *
691 * To make things work, Screen needs events. Call the mouse and key event functions (see Window)
692 * whenever such an event occurs. Call update(void *surface, int ticks) regularly, if possible about
693 * every 40msec (25 fps). If nothing has changed, screen updates are quite fast.
694 */
695 class Screen : public Window {
696 protected:
697 /// Screen buffer.
698 Drawable *const buffer;
699
700 /// Clipboard.
701 String clipboard;
702
703 /// Currently pressed mouse button.
704 MouseButton button;
705
706 /// Store a single RGB triple (8 bit each) as a native pixel value and advance pointer.
707 virtual void rgbToSurface(RGB color, void **pixel) = 0;
708
709 /// Map a single framebuffer pixel to an RGB value.
710 virtual RGB surfaceToRGB(void *pixel) = 0;
711
712 /// Create a new screen with the given characteristics.
713 Screen(Size width, Size height);
714
715 /// Create a new screen from the given GUI::Drawable.
716 Screen(Drawable *d);
717
718 public:
719 /// Destructor.
720 virtual ~Screen();
721
722 /// Set clipboard content.
723 template <typename STR> void setClipboard(const STR s) { this->setClipboard(String(s)); }
724
725 /// Set clipboard content.
726 virtual void setClipboard(const String &s) { clipboard = s; }
727
728 /// Get clipboard content.
729 virtual const String& getClipboard() { return clipboard; }
730
731 /// Do nothing.
732 virtual void resize(int w, int h);
733
734 /// Do nothing.
735 virtual void move(int x, int y);
736
737 /// Screen has always focus.
738 virtual bool hasFocus() const { return true; }
739
740 /// Update the given surface with this screen's content, fully honouring the alpha channel.
741 /** \p ticks can be set to a different value depending on how much time has passed. Timing
742 * doesn't need to be perfect, but try to call this at least every 40 msec. Each tick
743 * amounts to about 10 msec. Returns the number of ticks until the next event is scheduled, or
744 * 0 if none. */
745 Ticks update(void *surface, Ticks ticks = 1);
746
747 /// Default: clear screen.
748 virtual void paint(Drawable &d) const;
749 };
750
751 class Timer;
752
753 /// Timer callback type
754 struct Timer_Callback {
755 public:
756 /// The timer has expired.
757 /** Callbacks for timers take one parameter, the number of ticks since
758 * application start. Note that this value may wrap after a little less
759 * than 500 days. If you want callbacks to be called again, return the
760 * delay in ticks relative to the scheduled time of this
761 * callback (which may be earlier than now() ). Otherwise return 0. */
762 virtual Ticks timerExpired(Ticks time) = 0;
763 virtual ~Timer_Callback() {}
764 };
765
766 /** \brief Timing service.
767 * Time is measured in ticks. A tick is about 10 msec.
768 *
769 * Note that this is not suitable as a high-accuracy timing service. Timer
770 * events can be off by many ticks, and a tick may be slightly more or
771 * slightly less than 10 msec. Because of that, Timers are only intended for
772 * simple animation effects, input timeouts and similar things.
773 *
774 */
775 class Timer {
776 protected:
777 /// Number of ticks since application start.
778 static Ticks ticks;
779
780 /// Compare two integers for 'less-than'.
781 struct ltuint { bool operator()(Ticks i1, Ticks i2) const {
782 return (i1 < i2);
783 } };
784
785 /// Active timers.
786 static std::multimap<Ticks,Timer_Callback*,ltuint> timers;
787
788 public:
789 /// Advance time and check for expired timers.
790 static void check(Ticks ticks);
791
792 /// Add a timed callback. \p ticks is a value relative to now().
793 /** \p cb is not copied. */
794 static void add(Timer_Callback *cb, const Ticks ticks) { timers.insert(std::pair<const Ticks,Timer_Callback *>(ticks+Timer::ticks,cb)); }
795
796 static void remove(const Timer_Callback *const cb);
797
798 /// Return current time (ticks since application start)
799 static Ticks now() { return ticks; }
800
801 /// Return number of ticks until next scheduled timer or 0 if no timers
802 static Ticks next();
803 };
804
805
806 /** \brief A 24 bit per pixel RGB framebuffer aligned to 32 bit per pixel.
807 *
808 * Warning: This framebuffer type varies with CPU endiannes. It is meant as
809 * a testing/debugging tool.
810 */
811 class ScreenRGB32le : public Screen {
812 protected:
813 /// Map a single RGB triple (8 bit each) to a native pixel value.
814 virtual void rgbToSurface(RGB color, void **pixel) { RGB **p = (RGB **)pixel; **p = color; (*p)++; };
815
816 /// Map a single surface pixel to an RGB value.
817 virtual RGB surfaceToRGB(void *pixel) { return *(RGB*)pixel; };
818 public:
819 ScreenRGB32le(Size width, Size height) : Screen(width,height) {};
820
821 virtual void paint(Drawable &d) const;
822 };
823
824
825 #ifdef SDL_MAJOR_VERSION
826 /** \brief An SDL surface adapter.
827 *
828 * This screen type will draw on an SDL surface (honouring transparency if the
829 * surface is already filled) and react on SDL events. It does not provide an
830 * application event loop, you have to call update() and event() regularly until
831 * you decide to quit the application.
832 *
833 * The implementation of this class could as well have been integrated into
834 * GUI::Screen. That might have been a little more efficient, but this way
835 * this class serves as an example for custom screen classes.
836 *
837 * Note that you have to include \c SDL.h \em before \c gui_tk.h for this class
838 * to become available.
839 */
840 class ScreenSDL : public Screen {
841 protected:
842 /// not used.
843 virtual void rgbToSurface(RGB color, void **pixel) {};
844
845 /// not used.
846 virtual RGB surfaceToRGB(void *pixel) { return 0; };
847
848 /// The SDL surface being drawn to.
849 SDL_Surface *surface;
850
851 /// Position of last mouse down.
852 int downx, downy;
853
854 /// time of last click for double-click detection.
855 Ticks lastclick;
856
857 public:
858
859 /** Initialize SDL screen with a surface
860 *
861 * The dimensions of this surface will define the screen dimensions. Changing the surface
862 * later on will not change the available area.
863 */
864 ScreenSDL(SDL_Surface *surface);
865
866 /** Change current surface
867 *
868 * The new surface may have different dimensions than the current one, but
869 * the screen size will not change. This means that either the screen will
870 * not be displayed fully, or there will be borders around the screen.
871 */
872 void setSurface(SDL_Surface *surface) { this->surface = surface; }
873
874 /// Retrieve current surface.
875 SDL_Surface *getSurface() { return surface; }
876
877 /// Overridden: makes background transparent by default.
878 virtual void paint(Drawable &d) const;
879
880 /// Use this to update the SDL surface. The screen must not be locked.
881 Ticks update(Ticks ticks);
882
883 /// Process an SDL event. Returns \c true if event was handled.
884 bool event(const SDL_Event *ev) { return event(*ev); }
885
886
887 /// Process an SDL event. Returns \c true if event was handled.
888 bool event(const SDL_Event& ev);
889 };
890 #endif
891
892 class Font;
893
894 /** \brief A drawable represents a rectangular off-screen drawing area.
895 *
896 * It is an off-screen buffer which can be copied to other drawables or
897 * to a Screen's framebuffer. The drawable's origin is at the top left. All
898 * operations are silently clipped to the available area. The alpha channel
899 * is honoured while copying one drawable to another, but not during other
900 * drawing operations.
901 *
902 * Drawables have a current font, color and (x,y) position. Drawing takes place
903 * at the given point using the given font and color. The current position is
904 * then moved to the final point of the drawing primitive unless otherwise
905 * noted. Pixel width of all lines is selectable, but be aware that visual
906 * appearance of lines with width > 1 is not as sophisticated as in well-known
907 * toolkits like Java or Qt.
908 *
909 * Some drawing primitives are overloaded to take full coordinates. These ignore
910 * the current position, but update it just like their regular brethren.
911 */
912 class Drawable {
913 protected:
914 friend Ticks Screen::update(void *, Ticks);
915 /// The actual pixel buffer.
916 RGB *const buffer;
917 /// Total width of buffer.
918 const int width;
919 /// Total height of buffer.
920 const int height;
921 /// \c true if \a buffer must be freed by this instance.
922 const bool owner;
923
924 /// Current color.
925 RGB color;
926 /// Current font.
927 const Font *font;
928 /// Current line width.
929 int lineWidth;
930
931 /// X translation.
932 const int tx;
933 /// Y translation.
934 const int ty;
935 /// clip x.
936 const int cx;
937 /// clip y.
938 const int cy;
939 /// clip width.
940 const int cw;
941 /// clip height.
942 const int ch;
943
944 /// Current position x coordinate.
945 int x;
946 /// Current position y coordinate.
947 int y;
948
949 public:
950 /// Create an empty drawable object with given dimensions.
951 /** Optionally, the area is cleared with a given color (default: fully transparent). */
952 Drawable(int w, int h, RGB clear = Color::Transparent);
953
954 /// Deep-copying copy constructor.
955 /** It honours clip and translate so that the resulting drawable, if drawn
956 * to the source drawable at (0,0), yields the same result as drawing
957 * directly to the source surface. If \p fill is not explicitly set, will
958 * copy the original surface's contents */
959 Drawable(Drawable &src, RGB clear = 0);
960
961 /// Shallow-copying copy constructor with clip & translate. See setClipTranslate(int x, int y, int w, int h).
962 Drawable(Drawable &src, int x, int y, int w, int h);
963
964 /// Destructor.
965 virtual ~Drawable();
966
967 /// Clears the surface.
968 void clear(RGB clear = Color::Transparent);
969
970 /// Change current drawing color.
971 /** The alpha part is honoured in all drawing primitives like this:
972 All drawing operations in this window will unconditionally overwrite
973 earlier content of this window. Only when combining this window with
974 it's parent, the alpha channel is fully honoured. */
975 void setColor(RGB c) { color = c; };
976 /// Return the currently selected drawing color.
977 RGB getColor() { return color; };
978
979 /// Change current drawing font.
980 void setFont(const Font *f) { font = f; };
981 /// Return the currently selected drawing font.
982 const Font *getFont() { return font; };
983
984 /// Change current line width.
985 void setLineWidth(int w) { lineWidth = w; };
986 /// Return the current line width.
987 int getLineWidth() { return lineWidth; };
988
989 /// Move the current position to the given coordinates.
990 void gotoXY(int x, int y) { this->x = x; this->y = y; };
991 /// Return current position X.
992 int getX() { return x; }
993 /// Return current position Y.
994 int getY() { return y; }
995
996 /// Return clip width
997 int getClipX() { return cx; }
998 /// Return clip height
999 int getClipY() { return cy; }
1000 /// Return clip width
1001 int getClipWidth() { return cw; }
1002 /// Return clip height
1003 int getClipHeight() { return ch; }
1004
1005 /// Paint a single pixel at the current position.
1006 void drawPixel() { if (x >= cx && x < cw && y >= cy && y < ch) buffer[x+tx+(y+ty)*width] = color; };
1007 /// Paint a single pixel at the given coordinates.
1008 void drawPixel(int x, int y) { gotoXY(x,y); drawPixel(); };
1009
1010 /// Return the pixel color at the current position.
1011 RGB getPixel() { if (x >= cx && x < cw && y >= cy && y < ch) return buffer[x+tx+(y+ty)*width]; return Color::Transparent; };
1012 /// Return the pixel color at the given coordinates.
1013 RGB getPixel(int x, int y) { gotoXY(x,y); return getPixel(); };
1014
1015 /// Draw a straight line from the current position to the given coordinates.
1016 void drawLine(int x2, int y2);
1017 /// Draw a straight line from (\p x1,\p y1) to (\p x2,\p y2).
1018 void drawLine(int x1, int y1, int x2, int y2) { gotoXY(x1,y1); drawLine(x2,y2); };
1019
1020 /// Draw a circle centered at the current position with diameter \p d.
1021 /** The current position is not changed. */
1022 void drawCircle(int d);
1023 /// Draw a circle centered at the given coordinates with diameter \p d.
1024 /** The current position is set to the center. */
1025 void drawCircle(int x, int y, int d) { gotoXY(x, y); drawCircle(d); };
1026
1027 /// Draw a rectangle with top left at the current position and size \p w, \p h.
1028 /** The current position is not changed. */
1029 void drawRect(int w, int h);
1030 /// Draw a rectangle with top left at the given coordinates and size \p w, \p h.
1031 /** The current position is set to the top left corner. */
1032 void drawRect(int x, int y, int w, int h) { gotoXY(x, y); drawRect(w, h); };
1033
1034 /// Flood-fill an area at the current position.
1035 /** A continuous area with the same RGB value as the selected pixel is
1036 changed to the current color. The current position is not changed. */
1037 void fill();
1038 /// Flood-fill an area at a given position.
1039 /** see fill(), but moves current position to the given coordinates */
1040 void fill(int x, int y) { gotoXY(x,y); fill(); };
1041
1042 /// Draw a filled circle centered at the current position with diameter \p d.
1043 /** The current position is not changed. */
1044 void fillCircle(int d);
1045 /// Draw a filled circle centered at the given coordinates with diameter \p d.
1046 /** The current position is set to the center. */
1047 void fillCircle(int x, int y, int d) { gotoXY(x, y); fillCircle(d); };
1048
1049 /// Draw a filled rectangle with top left at the current position and size \p w, \p h.
1050 /** The current position is not changed. */
1051 void fillRect(int w, int h);
1052 /// Draw a filled rectangle with top left at the given coordinates and size \p w, \p h.
1053 /** The current position is set to the top left corner. */
1054 void fillRect(int x, int y, int w, int h) { gotoXY(x, y); fillRect(w, h); };
1055
1056 /// Draw a text string.
1057 /** Current position is the leftmost pixel on the baseline of the character.
1058 The current position is moved to the next character. Background is not
1059 cleared. If \p interpret is \c true, some ASCII control characters like
1060 backspace, line-feed, tab and ANSI colors are interpreted, and text is word-wrapped at
1061 the window borders. You can optionally pass start and length of a substring
1062 to print */
1063 void drawText(const String& text, bool interpret = true, Size start = 0, Size len = (Size)-1);
1064
1065 /// Draw a text string at a fixed position.
1066 /** see drawText(const String& text, bool interpret, Size start, Size len) */
1067 template <typename STR> void drawText(int x, int y, const STR text, bool interpret, Size start, Size len = (Size)-1) { gotoXY(x,y); drawText(String(text), interpret, start, len); };
1068 /// Draw a single character.
1069 /** see drawText(const STR text, bool interpret), except wrapping is
1070 performed on this character only */
1071 void drawText(const Char c, bool interpret = false);
1072 /// Draw a single character at a fixed position.
1073 /** see drawText(const Char c, bool interpret). */
1074 void drawText(int x, int y, const Char c, bool interpret = false) { gotoXY(x,y); drawText(c, interpret); };
1075
1076 /// Copy the contents of another Drawable to this one.
1077 /** The top left corner of the source Drawable is put at the current
1078 position. The alpha channel is fully honoured. Additionally, an extra
1079 \p alpha value may be given which is multiplied with the source
1080 alpha channel. The current position remains unchanged. */
1081 void drawDrawable(Drawable &d, unsigned char alpha = 1);
1082 /// Copy the contents of another Drawable to this one at a given position.
1083 /** see drawDrawable(Drawable &d, unsigned char alpha). The current position
1084 is moved to the given coordinates. */
1085 void drawDrawable(int x, int y, Drawable &d, unsigned char alpha = 1) { gotoXY(x,y); drawDrawable(d, alpha); };
1086
1087 };
1088
1089 /** \brief A variable- or fixed-width fixed-size Font.
1090 *
1091 * These Fonts can't be scaled once instantiated, but it is possible
1092 * to subclass this abstract font class to encapsulate scalable
1093 * fonts. Fonts can be anti-aliasing and multi-coloured, depending on
1094 * subclass. There is no encoding enforced. The font object implicitly
1095 * knows about it's encoding. Because of that, there is a utility
1096 * function for string examination as well.
1097 *
1098 * You can't instantiate objects of this class directly, use one of the
1099 * subclasses like BitmapFont.
1100 *
1101 * This class provides a font registry which allows you to register
1102 * and retrieve font objects using a name of your choice. It is recommended
1103 * to use a naming scheme like "FontName-variant-pixelsize-encoding" where
1104 * variant is "normal", "bold", "italic" or "bolditalic". No one enforces
1105 * this, however.
1106 *
1107 * The GUI uses some special font names. You must add them before creating
1108 * the relevant GUI item.
1109 * \li \c default - used if a requested font was not found
1110 * \li \c title - GUI::ToplevelWindow title
1111 * \li \c input - GUI::Input
1112 *
1113 */
1114 class Font {
1115 protected:
1116 friend void Drawable::drawText(const Char c, bool interpret);
1117 friend void Drawable::drawText(const String& s, bool interpret, Size start, Size len);
1118
1119 /// Compare two strings for 'less-than'.
1120 struct ltstr { bool operator()(const char* s1, const char* s2) const {
1121 return strcmp(s1, s2) < 0;
1122 } };
1123 /// Font registry. Contains all known font objects indexed by name.
1124 static std::map<const char *,Font *,ltstr> registry;
1125
1126 /// Default constructor.
1127 Font() {};
1128
1129 /// Draw character to a drawable at the current position.
1130 /** \p d's current position is advanced to the position of the next character.
1131 * The y coordinate is located at the baseline before and after the call. */
1132 virtual void drawChar(Drawable *d, const Char c) const = 0;
1133
1134 /// Draw \p len characters to a drawable at the current position, starting at string position \p start.
1135 /** This can be used to provide kerning. */
1136 virtual void drawString(Drawable *d, const String &s, Size start, Size len) const {
1137 if (len > s.size()-start) len = (Size)(s.size()-start);
1138 len += start;
1139 while (start < len) drawChar(d,s[start++]);
1140 }
1141
1142 public:
1143 /// Return a font with the given name (case-sensitive).
1144 /** If no font was registered with that name, returns NULL. */
1145 static const Font *getFont(const char *name) {
1146 std::map<const char *,Font *,ltstr>::iterator i = registry.find(name);
1147 if (i == registry.end()) return(strcmp(name,"default")?getFont("default"):NULL);
1148 return (*i).second;
1149 }
1150
1151 /// Add a font with a given name.
1152 /** Don't delete this font once added. This class will do that for you.
1153 * If a font with that name already exists, it will be replaced. */
1154 static void addFont(const char *name, Font *font) {
1155 std::map<const char *,Font *,ltstr>::iterator i = registry.find(name);
1156 if (i != registry.end()) delete (*i).second;
1157 registry[name] = font;
1158 }
1159
1160 virtual ~Font() {};
1161
1162 /// Retrieve total height of font in pixels.
1163 virtual int getHeight() const = 0;
1164
1165 /// Retrieve the ascent, i.e. the number of pixels above the base line.
1166 virtual int getAscent() const = 0;
1167
1168 /// Return width of a string.
1169 template <typename STR> int getWidth(const STR s, Size start = 0, Size len = (Size)-1) const {
1170 return this->getWidth(String(s), start, len);
1171 }
1172
1173 /// Retrieve width of a character.
1174 virtual int getWidth(Char c = 'M') const = 0;
1175
1176 /// Retrieve width of a string of characters.
1177 /** Can be used to provide kerning. */
1178 virtual int getWidth(const String &s, Size start = 0, Size len = (Size)-1) const {
1179 int width = 0;
1180 if (start+len > s.size()) len = (Size)(s.size()-start);
1181 while (len--) width += getWidth(s[start++]);
1182 return width;
1183 }
1184
1185 /// Characters with special appearance or meaning.
1186 enum SpecialChar { CR = '\r', LF = '\n', BS = '\b', Tab = '\t', Space = ' ', ESC = 27 };
1187
1188 /// Convert a character to an equivalent SpecialChar. May return values not in SpecialChar.
1189 virtual SpecialChar toSpecial(Char c) const { return (SpecialChar)(c<255?c:255); }
1190
1191 /// Convert a SpecialChar to an equivalent character.
1192 virtual Char fromSpecial(SpecialChar c) const { return c; }
1193 };
1194
1195 /** \brief A bitmap font.
1196 * This is a font which is defined by a binary bit map. Each bit in the bitmap
1197 * defines one pixel. Bits may be arranged in various common patterns.
1198 *
1199 * Encoding free, character size depends on number of characters in the font.
1200 */
1201 class BitmapFont : public Font {
1202 protected:
1203 /// The actual font data.
1204 const unsigned char *const bitmap;
1205
1206 /// Width of a character cell.
1207 const int width;
1208
1209 /// Height of all characters.
1210 const int height;
1211
1212 /// Ascent of all characters.
1213 const int ascent;
1214
1215 /// Array of character widths. If font is fixed-width, this is NULL and \a width is used.
1216 const int *const widths;
1217
1218 /// Array of character ascents. If this is NULL, \a ascent is used for all characters.
1219 /** This allows character data to be flush to the top or bottom of it's bitmap area. */
1220 const int *const ascents;
1221
1222 /// True if set bits are background, false otherwise.
1223 const bool background_set;
1224
1225 /// Number of bits added to get from a column to the next column.
1226 const int col_step;
1227
1228 /// Distance between 2 rows of a character, or 0 for variable-width rows.
1229 const int row_step;
1230
1231 /// Distance of two characters in the bitmap in bits.
1232 /** This is calculated as abs(row_step*height) unless explicitly specified. */
1233 const int character_step;
1234
1235 /// Array of pointers to font data. If set, neither \a bitmap nor \a character_step are used.
1236 const unsigned char *const*const char_position;
1237
1238 /// Array of SpecialChar equivalents.
1239 /** If unset, encoding is assumed ASCII-like for the first 32 characters */
1240 const SpecialChar *const special;
1241
1242 /// If \c true, then all arrays are freed on destruction.
1243 const bool owner;
1244
1245 /// Last defined character. Characters above this will be ignored.
1246 const Char last;
1247
1248 /// Draw character to a drawable at the current position.
1249 /** \p d's current position is advanced to the position of the next character.
1250 * The y coordinate is located at the baseline before and after the call. */
1251 virtual void drawChar(Drawable *d, const Char c) const;
1252
1253 public:
1254 /// Constructor.
1255 /** The default values provide an 8 bit wide fixed-width pixel layout with each byte a row,
1256 * arranged top-to-bottom just like a PC's VGA font. See the individual member documentation
1257 * for details on the parameters. */
1258 BitmapFont(const unsigned char *data, int height, int ascent, bool owner = false,
1259 int width = 8, bool background_set = false,
1260 int col_step = -1, int row_step = 8, int character_step = 0, Char last = 256,
1261 const int *widths = NULL, const int *ascents = NULL,
1262 const unsigned char *const* char_position = NULL,
1263 const SpecialChar *special = NULL);
1264
1265 virtual ~BitmapFont();
1266
1267 /// Retrieve total height of font in pixels.
1268 virtual int getHeight() const { return height; };
1269
1270 /// Retrieve the ascent, i.e. the number of pixels above the base line.
1271 virtual int getAscent() const { return ascent; };
1272
1273 /// Retrieve width of a character.
1274 virtual int getWidth(Char c = 'M') const { return (widths != NULL?widths[c]:width); };
1275
1276 /// Convert a character to an equivalent SpecialChar. See Font::toSpecial(Char c)
1277 virtual SpecialChar toSpecial(Char c) const { return (special != NULL?special[c]:Font::toSpecial(c)); }
1278
1279 /// Convert a character to an equivalent character. See Font::fromSpecial(SpecialChar c).
1280 virtual Char fromSpecial(SpecialChar c) const { if (special == NULL) return Font::fromSpecial(c); Char i = 0; while(special[i] != c) i++; return i; }
1281
1282 };
1283
1284 class ActionEventSource;
1285 /// Callback for action events.
1286 struct ActionEventSource_Callback {
1287 public:
1288 /// Handler with optional String argument.
1289 /** If the event source doesn't provide an additional argument, the name will be used. */
1290 virtual void actionExecuted(ActionEventSource *source, const String &arg) = 0;
1291 virtual ~ActionEventSource_Callback() {}
1292 };
1293
1294 /// Event class for action events.
1295 /** Action events are events generated by GUI elements like Buttons, Menus and by pressing Enter in
1296 * an Input. All of these are handled similarly: The source of such an event has a name, and the
1297 * Event may also be connected with a String describing what was executed, like the name of the
1298 * Menu entry or the contents of the Input.
1299 */
1300 class ActionEventSource {
1301 protected:
1302 /// List of registered action handlers.
1303 std::list<ActionEventSource_Callback *> actionHandlers;
1304
1305 /// This event source's name.
1306 /** The name is primarily meant for your own purposes, for example identification of the activated
1307 * element. One exception are Menubars, which display the name of their Menus. */
1308 String name;
1309
1310 public:
1311 /// Create a named event source.
1312 template <typename STR> ActionEventSource(const STR name) : name(String(name)) { }
1313
1314 /// Dummy destructor.
1315 virtual ~ActionEventSource() {}
1316
1317 /// Add a button press event handler.
1318 void addActionHandler(ActionEventSource_Callback *handler) { actionHandlers.push_back(handler); }
1319
1320 /// Remove a button press event handler.
1321 void removeActionHandler(ActionEventSource_Callback *handler) { actionHandlers.remove(handler); }
1322
1323 /// Set the name of this event source.
1324 template <typename STR> void setName(const STR name) { this->name = String(name); }
1325
1326 /// Get the name of this event source.
1327 const String &getName() const { return name; }
1328
1329 /// Execute handlers.
1330 void executeAction(const String &arg) {
1331 std::list<ActionEventSource_Callback*>::iterator i = actionHandlers.begin();
1332 bool end = (i == actionHandlers.end());
1333 while (!end) {
1334 ActionEventSource_Callback *c = *i;
1335 ++i;
1336 end = (i == actionHandlers.end());
1337 c->actionExecuted(this,arg);
1338 }
1339 }
1340
1341 /// Execute handlers.
1342 void executeAction() { executeAction(name); }
1343 };
1344
1345 /// Internal class for windows whose child content should not span the entire area.
1346 class BorderedWindow : public Window {
1347 protected:
1348 /// Borders.
1349 int border_left, border_top, border_right, border_bottom;
1350
1351 /// Create a bordered window.
1352 BorderedWindow(Window *parent, int x, int y, int w, int h, int bl, int bt, int br, int bb) :
1353 Window(parent,x,y,w,h), border_left(bl), border_top(bt), border_right(br), border_bottom(bb) {}
1354
1355 public:
1356 virtual void paintAll(Drawable &d) const;
1357 virtual bool mouseMoved(int x, int y);
1358 virtual bool mouseDown(int x, int y, MouseButton button);
1359 virtual bool mouseDragged(int x, int y, MouseButton button);
1360 virtual int getScreenX() const { return Window::getScreenX()+border_left; }
1361 virtual int getScreenY() const { return Window::getScreenY()+border_top; }
1362 };
1363
1364 /// A text label
1365 /** Text labels are positioned relative to the top left corner of their bounding box.
1366 * They size themselves automatically and display their text in non-interpreted mode.
1367 */
1368
1369 class Label : public Window {
1370 /// The Font used
1371 const Font *font;
1372
1373 /// Text color
1374 RGB color;
1375
1376 /// Text
1377 String text;
1378
1379 /// multiline text?
1380 bool interpret;
1381
1382 public:
1383 /// Create a text label with given position, \p text, \p font and \p color.
1384 /** If \p width is given, the resulting label is a word-wrapped multiline label */
1385 template <typename STR> Label(Window *parent, int x, int y, const STR text, int width = 0, const Font *font = Font::getFont("default"), RGB color = Color::Text) :
1386 Window(parent, x, y, (width?width:1), 1), font(font), color(color), text(text), interpret(width != 0)
1387 { resize(); }
1388
1389 /// Set a new text. Size of the label is adjusted accordingly.
1390 template <typename STR> void setText(const STR text) { this->text = text; resize(); }
1391 /// Retrieve current text
1392 const String& getText() { return text; }
1393
1394 /// Set a new font. Size of the label is adjusted accordingly.
1395 void setFont(const Font *font) { this->font = font; resize(); }
1396 /// Retrieve current font
1397 const Font *getFont() { return font; }
1398
1399 /// Set a new text color.
1400 void setColor(const RGB color) { this->color = color; resize(); }
1401 /// Retrieve current color
1402 RGB getColor() { return color; }
1403
1404 /// Calculate label size. Parameters are ignored.
1405 virtual void resize(int w = -1, int h = -1) {
1406 if (w == -1) w = (interpret?getWidth():0);
1407 else interpret = (w != 0);
1408 Drawable d((w?w:1), 1);
1409 d.setFont(font);
1410 d.drawText(0, font->getAscent(), text, interpret, 0);
1411 if (interpret) Window::resize(w, d.getY()-font->getAscent()+font->getHeight());
1412 else Window::resize(d.getX(), font->getHeight());
1413 }
1414
1415 /// Paint label
1416 virtual void paint(Drawable &d) const { d.setColor(color); d.drawText(0, font->getAscent(), text, interpret, 0); }
1417
1418 virtual bool raise() { return false; }
1419 };
1420
1421
1422 /// A single-line text input
1423 /** It uses Font::getFont("input") to display content.
1424 * It supports selection, the clipboard and all well-known key bindings (except undo).
1425 */
1426 class Input : public Window, public Timer_Callback, public ActionEventSource {
1427 protected:
1428 /// The text entered.
1429 String text;
1430
1431 /// Current position in \a text.
1432 Size pos;
1433
1434 /// Last updated position in \a text.
1435 Size lastpos;
1436
1437 /// Coordinates according to pos.
1438 int posx, posy;
1439
1440 /// Selection in \a text.
1441 Size start_sel, end_sel;
1442
1443 /// Is cursor visible at the moment?
1444 bool blink;
1445
1446 /// Insert mode?
1447 bool insert;
1448
1449 /// Multiline?
1450 bool multi;
1451
1452 /// Horizontal scrolling offset.
1453 int offset;
1454
1455 /// Ensure that pos is visible.
1456 void checkOffset() {
1457 if (lastpos == pos) return;
1458 const Font *f = Font::getFont("input");
1459 if (multi) {
1460 Drawable d(width-6,1);
1461 d.setFont(f);
1462 d.drawText(0, 0, text, multi, 0, pos);
1463 posy = d.getY();
1464 posx = d.getX();
1465 if (posy-offset > height-8-f->getHeight()) offset = posy-height+8+f->getHeight();
1466 if (posy-offset < 0) offset = posy;
1467 } else {
1468 posy = 0;
1469 posx = f->getWidth(text,0,pos);
1470 if (f->getWidth(text,0,pos+1)-offset > width-10) offset = f->getWidth(text,0,pos+1)-width+10;
1471 if (f->getWidth(text,0,(pos>0?pos-1:0))-offset < 0) offset = f->getWidth(text,0,(pos>0?pos-1:0));
1472 }
1473 lastpos = pos;
1474 setDirty();
1475 }
1476
1477 public:
1478 /// Create an input with given position and width. If not set, height is calculated from the font and input is single-line.
1479 Input(Window *parent, int x, int y, int w, int h = 0) :
1480 Window(parent,x,y,w,(h?h:Font::getFont("input")->getHeight()+10)), ActionEventSource("GUI::Input"),
1481 text(""), pos(0), lastpos(0), posx(0), posy(0), start_sel(0), end_sel(0), blink(true), insert(true), multi(h != 0), offset(0)
1482 { Timer::add(this,30); }
1483
1484 ~Input() {
1485 Timer::remove(this);
1486 }
1487
1488 /// Paint input.
1489 virtual void paint(Drawable &d) const;
1490
1491 /// Clear selected area.
1492 void clearSelection() {
1493 text.erase(text.begin()+(pos = imin(start_sel,end_sel)),text.begin()+imax(start_sel,end_sel));
1494 start_sel = end_sel = pos;
1495 }
1496
1497 /// Copy selection to clipboard.
1498 void copySelection() {
1499 setClipboard(String(text.begin()+imin(start_sel,end_sel),text.begin()+imax(start_sel,end_sel)));
1500 }
1501
1502 /// Cut selection to clipboard.
1503 void cutSelection() {
1504 setClipboard(String(text.begin()+imin(start_sel,end_sel),text.begin()+imax(start_sel,end_sel)));
1505 clearSelection();
1506 }
1507
1508 /// Paste from clipboard.
1509 void pasteSelection() {
1510 String c = getClipboard();
1511 clearSelection();
1512 text.insert(text.begin()+pos,c.begin(),c.end());
1513 start_sel = end_sel = pos += (Size)c.size();
1514 }
1515
1516 /// get character position corresponding to coordinates
1517 Size findPos(int x, int y);
1518
1519 /// Set text to be edited.
1520 template <typename STR> void setText(const STR text) { this->text = text; setDirty(); };
1521 /// Get the entered text. If you need it longer, copy it immediately.
1522 const String& getText() { return text; };
1523
1524 /// Handle text input.
1525 virtual bool keyDown(const Key &key);
1526
1527 /// Handle mouse input.
1528 virtual bool mouseDown(int x, int y, MouseButton button);
1529
1530 /// Handle mouse input.
1531 virtual bool mouseDragged(int x, int y, MouseButton button);
1532
1533 /// Timer callback function
1534 virtual Ticks timerExpired(Ticks time)
1535 { blink = !blink; setDirty(); return 30; }
1536
1537 };
1538
1539 class ToplevelWindow;
1540 /// Callbacks for window events.
1541 struct ToplevelWindow_Callback {
1542 public:
1543 /// The window has been asked to be closed.
1544 /** Return \c false in order to block the requested action. Do not do any
1545 * deallocation here, as other callbacks may abort the close process.
1546 */
1547 virtual bool windowClosing(ToplevelWindow *win) = 0;
1548
1549 /// The window will been closed.
1550 /** Now it is safe to deallocate all external resources that applications
1551 * may have associated with this window, like registering this window
1552 * with external callbacks.
1553 */
1554 virtual void windowClosed(ToplevelWindow *win) = 0;
1555 virtual ~ToplevelWindow_Callback() {}
1556 };
1557
1558 /// An actual decorated window.
1559 class ToplevelWindow : public BorderedWindow, public ActionEventSource_Callback {
1560 protected:
1561 /// Title text
1562 String title;
1563
1564 /// Drag base
1565 int dragx, dragy;
1566
1567 /// List of registered event handlers.
1568 std::list<ToplevelWindow_Callback *> closehandlers;
1569
1570 /// System menu (top left)
1571 Menu *systemMenu;
1572
1573 public:
1574 /// Create a new GUI Frame with title bar, border and close button
1575 template <typename STR> ToplevelWindow(Screen *parent, int x, int y, int w, int h, const STR title);
1576
1577 /// Call cleanup handlers
1578 ~ToplevelWindow() {
1579 std::list<ToplevelWindow_Callback*>::iterator i = closehandlers.begin();
1580 bool end = (i == closehandlers.end());
1581 while (!end) {
1582 ToplevelWindow_Callback *c = *i;
1583 ++i;
1584 end = (i == closehandlers.end());
1585 c->windowClosed(this);
1586 }
1587 }
1588
1589 /// Menu callback function
1590 virtual void actionExecuted(ActionEventSource *src, const String &item) {
1591 if (item == String("Close")) close();
1592 }
1593
1594 /// Add a window event handler.
1595 void addCloseHandler(ToplevelWindow_Callback *handler) { closehandlers.push_back(handler); }
1596
1597 /// Remove a window event handler.
1598 void removeCloseHandler(ToplevelWindow_Callback *handler) { closehandlers.remove(handler); }
1599
1600 virtual void paint(Drawable &d) const;
1601 virtual bool mouseDown(int x, int y, MouseButton button);
1602 virtual bool mouseDoubleClicked(int x, int y, MouseButton button) {
1603 if (button == Left && x < 32 && x > 6 && y > 4 && y < 31) {
1604 close();
1605 return true;
1606 }
1607 BorderedWindow::mouseClicked(x,y,button);
1608 return true;
1609 }
1610 virtual bool mouseUp(int x, int y, MouseButton button) {
1611 if (button == Left && dragx >= 0 && dragy >= 0) {
1612 dragx = dragy = -1;
1613 return true;
1614 }
1615 BorderedWindow::mouseUp(x,y,button);
1616 return true;
1617 }
1618 virtual bool mouseDragged(int x, int y, MouseButton button) {
1619 if (button == Left && dragx >= 0 && dragy >= 0) {
1620 move(x-dragx+this->x,y-dragy+this->y);
1621 return true;
1622 }
1623 BorderedWindow::mouseDragged(x,y,button);
1624 return true;
1625 }
1626 virtual bool mouseMoved(int x, int y) {
1627 BorderedWindow::mouseMoved(x,y);
1628 return true;
1629 }
1630
1631 /// Put window on top of all other windows without changing their relative order
1632 virtual bool raise() {
1633 Window *last = parent->children.back();
1634 parent->children.remove(this);
1635 parent->children.push_back(this);
1636 if (last != this) {
1637 focusChanged(true);
1638 last->focusChanged(false);
1639 }
1640 return true;
1641 }
1642
1643 /// Set a new title.
1644 template <typename STR> void setTitle(const STR title) { this->title = title; setDirty(); }
1645 /// Retrieve current title.
1646 const String& getTitle() { return title; }
1647
1648 /// Close window.
1649 void close() {
1650 bool doit = true;
1651 std::list<ToplevelWindow_Callback*>::iterator i = closehandlers.begin();
1652 bool end = (i == closehandlers.end());
1653 while (!end) {
1654 ToplevelWindow_Callback *c = *i;
1655 ++i;
1656 end = (i == closehandlers.end());
1657 doit = doit && c->windowClosing(this);
1658 }
1659 if (doit) delete this;
1660 }
1661 };
1662
1663 /// A floating temporary window that is not restricted by it's parent's area.
1664 /** They have a parent which displays them,
1665 * but that parent is not their real parent in the window hierarchy: They are always top-level elements, thus
1666 * they are not clipped to their logical parent's area, they can freely overlay any part of the screen.
1667 * As another consequence, they are not automatically deleted when their logical parent is deleted.
1668 *
1669 * You should observe the following points:
1670 * \li TransientWindows behave mostly as if their logical parent was their true parent, but are not
1671 * restricted to it's area
1672 * \li TransientWindows are deleted automatically when the ToplevelWindow is deleted in which their logical
1673 * parent resides; do NOT delete them in your destructor or bad things will happen
1674 * \li only the logical parent object can show/hide a TransientWindow at will
1675 * \li it will close automatically upon clicking other GUI elements, \em except for the
1676 * logical parent and it's children
1677 */
1678 class TransientWindow : public Window, Window_Callback, ToplevelWindow_Callback {
1679 protected:
1680 /// The true parent window.
1681 Window *realparent;
1682
1683 /// User selected position relative to logical parent.
1684 int relx, rely;
1685
1686 public:
1687 /// Handle automatic hiding
1688 virtual void focusChanged(bool gained) {
1689 Window::focusChanged(gained);
1690 if (isVisible() && !gained) {
1691 if (realparent->hasFocus()) raise();
1692 else setVisible(false);
1693 }
1694 }
1695
1696 /// Handle automatic delete
1697 void windowClosed(ToplevelWindow *win) {
1698 delete this;
1699 }
1700
1701 /// No-op
1702 bool windowClosing(ToplevelWindow *win) { return true; }
1703
1704 /// Create a transient window with given position and size
1705 /** \a parent is the logical parent. The true parent object is
1706 * always the screen the logical parent resides on. */
1707 TransientWindow(Window *parent, int x, int y, int w, int h) :
1708 Window(parent->getScreen(),x+parent->getScreenX(),y+parent->getScreenY(),w,h),
1709 realparent(parent), relx(x), rely(y) {
1710 Window *p = realparent, *last = NULL, *last2 = NULL;
1711 while (p != NULL) {
1712 p->addWindowHandler(this);
1713 last2 = last;
1714 last = p;
1715 p = p->getParent();
1716 }
1717 dynamic_cast<ToplevelWindow *>(last2)->addCloseHandler(this);
1718 }
1719
1720 ~TransientWindow() {
1721 Window *p = realparent, *last = NULL, *last2 = NULL;
1722 while (p != NULL) {
1723 p->removeWindowHandler(this);
1724 last2 = last;
1725 last = p;
1726 p = p->getParent();
1727 }
1728 dynamic_cast<ToplevelWindow *>(last2)->removeCloseHandler(this);
1729 }
1730
1731 virtual void move(int x, int y) { relx = x; rely = y;
1732 Window::move(x+realparent->getScreenX(),y+realparent->getScreenY()); }
1733 virtual int getX() const { return x-realparent->getScreenX(); }
1734 virtual int getY() const { return y-realparent->getScreenY(); }
1735 virtual void setVisible(bool v) { if (v) raise(); Window::setVisible(v); }
1736 virtual void windowMoved(Window *src, int x, int y) { move(relx,rely); }
1737
1738 /// Put window on top of all other windows without changing their relative order
1739 virtual bool raise() {
1740 Window *last = parent->children.back();
1741 parent->children.remove(this);
1742 parent->children.push_back(this);
1743 if (last != this) {
1744 focusChanged(true);
1745 last->focusChanged(false);
1746 }
1747 return true;
1748 }
1749
1750 };
1751
1752 /// A popup menu.
1753 /** Popup menus are used as context menus or as part of a menu bar. Menus are not visible when created.
1754 * Menus have a name which can be used in event handlers to identify it, and it is used in Menubars as well.
1755 *
1756 * Currently, menu entries are not interpreted in any way. This may change in the future. To ensure upwards
1757 * compatibility, avoid the \c '&' character in menu entries, since it may have a special meaning in future
1758 * versions. Menus use the Font named "menu".
1759 *
1760 * Please note the general remarks in GUI::TransientWindow
1761 */
1762 class Menu : public TransientWindow, public ActionEventSource {
1763 protected:
1764 /// List of menu items (displayed text)
1765 std::vector<String> items;
1766
1767 /// Currently selected menu item.
1768 /** Can be -1 if no item is currently active. */
1769 int selected;
1770
1771 /// Flag to skip the first mouseUp-event
1772 bool firstMouseUp;
1773
1774 /// Where we grabbed the mouse from.
1775 Window *mouseTakenFrom;
1776
1777 /// Selects menu item at position (x,y).
1778 /** \a selected is set to -1 if there is no active item at that location. */
1779 virtual void selectItem(int x, int y) {
1780 y -= 2;
1781 selected = -1;
1782 const int height = Font::getFont("menu")->getHeight()+2;
1783 std::vector<String>::iterator i;
1784 for (i = items.begin(); i != items.end() && y > 0; ++i) {
1785 selected++;
1786 if ((*i).size() > 0) y -= height;
1787 else y -= 12;
1788 }
1789 if (y > 0 || (selected >= 0 && items[selected].size() == 0)) selected = -1;
1790 }
1791
1792 virtual Size getPreferredWidth() {
1793 Size width = 0;
1794 const Font *f = Font::getFont("menu");
1795 std::vector<String>::iterator i;
1796 for (i = items.begin(); i != items.end() && y > 0; ++i) {
1797 Size newwidth = f->getWidth(*i);
1798 if (newwidth > width) width = newwidth;
1799 }
1800 return width+39;
1801 }
1802
1803 virtual Size getPreferredHeight() {
1804 Size height = 0;
1805 const Size h = Font::getFont("menu")->getHeight()+2;
1806 std::vector<String>::iterator i;
1807 for (i = items.begin(); i != items.end() && y > 0; ++i) {
1808 height += ((*i).size() > 0?h:12);
1809 }
1810 return height+6;
1811 }
1812
1813 public:
1814 /// Create a menu with given position
1815 /** Size is determined dynamically. \a parent is the logical parent. The true parent object is
1816 * always the screen the logical parent resides on. */
1817 template <typename STR> Menu(Window *parent, int x, int y, const STR name) :
1818 TransientWindow(parent,x,y,4,4), ActionEventSource(name), selected(-1)
1819 { setVisible(false); }
1820
1821 ~Menu() {
1822 setVisible(false);
1823 }
1824
1825 /// Paint button.
1826 virtual void paint(Drawable &d) const;
1827
1828 /// Highlight current item.
1829 virtual bool mouseMoved(int x, int y) {
1830 selectItem(x,y);
1831 return true;
1832 }
1833
1834 /// Highlight current item.
1835 virtual bool mouseDragged(int x, int y, MouseButton b) {
1836 selectItem(x,y);
1837 return true;
1838 }
1839
1840 virtual bool mouseDown(int x, int y, MouseButton button) { return true; }
1841
1842 /// Possibly select item.
1843 virtual bool mouseUp(int x, int y, MouseButton button) {
1844 selectItem(x,y);
1845 if (firstMouseUp) firstMouseUp = false;
1846 else setVisible(false);
1847 execute();
1848 return true;
1849 }
1850
1851 /// Handle keyboard input.
1852 virtual bool keyDown(const Key &key) {
1853 if (key.special == Key::Up) selected--;
1854 else if (key.special == Key::Down) selected++;
1855 else if (key.special == Key::Enter) { execute(); return true; }
1856 else if (key.special == Key::Escape) { setVisible(false); return true; }
1857 else return true;
1858 if (items[selected].size() == 0 && items.size() > 1) return keyDown(key);
1859 if (selected < 0) selected = (int)(items.size()-1);
1860 if (selected >= (int)items.size()) selected = 0;
1861 return true;
1862 }
1863
1864
1865 /// Add a menu item at end. An empty string denotes a separator.
1866 template <typename T> void addItem(const T item) {
1867 items.push_back(String(item));
1868 resize(getPreferredWidth(),getPreferredHeight());
1869 }
1870
1871 /// Remove an existing menu item.
1872 template <typename T> void removeItem(const T item) {
1873 const String s(item);
1874 std::vector<String>::iterator i = items.begin();
1875 while (i != items.end() && s != (*i)) ++i;
1876 if (i != items.end()) items.erase(i);
1877 resize(getPreferredWidth(),getPreferredHeight());
1878 }
1879
1880 virtual void setVisible(bool v) {
1881 TransientWindow::setVisible(v);
1882 if (v) {
1883 parent->mouseChild = this;
1884 raise();
1885 firstMouseUp = true;
1886 }
1887 }
1888
1889 /// Execute menu item.
1890 void execute() {
1891 if (selected >= 0) {
1892 setVisible(false);
1893 executeAction(items[selected]);
1894 }
1895 }
1896 };
1897
1898 /// A push button
1899 /** Buttons have 3D appearance and can have any child widget as content.
1900 * There are convenience constructors for common forms of buttons.
1901 */
1902 class Button : public BorderedWindow, public ActionEventSource {
1903 protected:
1904 /// \c true, if button is currently pressed down.
1905 bool pressed;
1906
1907 public:
1908 /// Create a button with given position and size
1909 Button(Window *parent, int x, int y, int w, int h) : BorderedWindow(parent,x,y,w,h,6,5,6,5), ActionEventSource("GUI::Button"), pressed(0) {}
1910
1911 /// Create a text button.
1912 /** If a size is specified, text is centered. Otherwise, button size is adjusted for the text. */
1913 template <typename T> Button(Window *parent, int x, int y, const T text, int w = -1, int h = -1);
1914
1915 /// Paint button.
1916 virtual void paint(Drawable &d) const;
1917
1918 /// Press button.
1919 virtual bool mouseDown(int x, int y, MouseButton button) {
1920 border_left = 7; border_right = 5; border_top = 7; border_bottom = 3;
1921 pressed = true;
1922 return true;
1923 }
1924
1925 /// Release button.
1926 virtual bool mouseUp(int x, int y, MouseButton button) {
1927 border_left = 6; border_right = 6; border_top = 5; border_bottom = 5;
1928 pressed = false;
1929 return true;
1930 }
1931
1932 /// Handle mouse activation.
1933 virtual bool mouseClicked(int x, int y, MouseButton button) {
1934 if (button == Left) {
1935 executeAction();
1936 return true;
1937 }
1938 return false;
1939 }
1940
1941 /// Handle keyboard input.
1942 virtual bool keyDown(const Key &key);
1943
1944 /// Handle keyboard input.
1945 virtual bool keyUp(const Key &key);
1946
1947 };
1948
1949 /// A menu bar at the top of a ToplevelWindow
1950 /** Menu bars aggregate several Menus. They have a simple border at the bottom. If your application
1951 * has a work area with 3D sunken look, place it so that it overlaps the menu by one row.
1952 *
1953 * As with Menus, avoid the character \c '&' in Menu names as it may
1954 * have a special meaning in future versions. Menubars use the Font named "menu".
1955 */
1956 class Menubar : public Window, public ActionEventSource, ActionEventSource_Callback {
1957 protected:
1958 /// Currently activated menu index.
1959 int selected;
1960
1961 /// Horizontal position of next menu.
1962 int lastx;
1963
1964 /// List of Menus.
1965 std::vector<Menu*> menus;
1966
1967 public:
1968 /// Create a menubar with given position and size
1969 /** Height is autocalculated from font size */
1970 Menubar(Window *parent, int x, int y, int w) : Window(parent,x,y,w,Font::getFont("menu")->getHeight()+5), ActionEventSource("GUI::Menubar"), selected(-1), lastx(0) {}
1971
1972 /// Add a Menu.
1973 template <typename STR> void addMenu(const STR name) {
1974 const String n(name);
1975 menus.push_back(new Menu(this,lastx,height-2,n));
1976 menus.back()->addActionHandler(this);
1977 lastx += Font::getFont("menu")->getWidth(n)+14;
1978 }
1979
1980 /// Add a Menuitem.
1981 template <typename STR> void addItem(int index, const STR name) { menus[index]->addItem(name); }
1982
1983 /// Remove a Menuitem.
1984 template <typename STR> void removeItem(int index, const STR name) { menus[index]->removeItem(name); }
1985
1986 /// Paint menubar.
1987 virtual void paint(Drawable &d) const;
1988
1989 /// Open menu.
1990 virtual bool mouseDown(int x, int y, MouseButton button) {
1991 int oldselected = selected;
1992 if (selected >= 0 && !menus[selected]->isVisible()) oldselected = -1;
1993 if (selected >= 0) menus[selected]->setVisible(false);
1994 if (x < 0 || x >= lastx) return true;
1995 for (selected = (int)(menus.size()-1); menus[selected]->getX() > x; selected--) {};
1996 if (oldselected == selected) selected = -1;
1997 else menus[selected]->setVisible(true);
1998 return true;
1999 }
2000
2001 /// Handle keyboard input.
2002 virtual bool keyDown(const Key &key) { return true; };
2003
2004 /// Handle keyboard input.
2005 virtual bool keyUp(const Key &key) { return true; };
2006
2007 virtual void actionExecuted(ActionEventSource *src, const String &arg) {
2008 std::list<ActionEventSource_Callback*>::iterator i = actionHandlers.begin();
2009 bool end = (i == actionHandlers.end());
2010 while (!end) {
2011 ActionEventSource_Callback *c = *i;
2012 ++i;
2013 end = (i == actionHandlers.end());
2014 c->actionExecuted(src,arg);
2015 }
2016 }
2017 };
2018
2019 /// A checkbox
2020 /** Checkboxes can have any child widget as content.
2021 * There are convenience constructors for common forms of checkboxes.
2022 */
2023 class Checkbox : public BorderedWindow, public ActionEventSource {
2024 protected:
2025 /// \c true, if checkbox is currently selected.
2026 bool checked;
2027
2028 public:
2029 /// Create a checkbox with given position and size
2030 Checkbox(Window *parent, int x, int y, int w, int h) : BorderedWindow(parent,x,y,w,h,16,0,0,0), ActionEventSource("GUI::Checkbox"), checked(0) {}
2031
2032 /// Create a checkbox with text label.
2033 /** If a size is specified, text is centered. Otherwise, checkbox size is adjusted for the text. */
2034 template <typename T> Checkbox(Window *parent, int x, int y, const T text, int w = -1, int h = -1);
2035
2036 /// Paint checkbox.
2037 virtual void paint(Drawable &d) const;
2038
2039 /// Change checkbox state.
2040 virtual void setChecked(bool checked) { this->checked = checked; }
2041
2042 /// Get checkbox state.
2043 virtual bool isChecked() { return checked; }
2044
2045 /// Press checkbox.
2046 virtual bool mouseDown(int x, int y, MouseButton button) {
2047 checked = !checked;
2048 return true;
2049 }
2050
2051 /// Release checkbox.
2052 virtual bool mouseUp(int x, int y, MouseButton button) {
2053 execute();
2054 return true;
2055 }
2056
2057 /// Handle keyboard input.
2058 virtual bool keyDown(const Key &key);
2059
2060 /// Handle keyboard input.
2061 virtual bool keyUp(const Key &key);
2062
2063 /// Execute handlers.
2064 virtual void execute() {
2065 String arg(name);
2066 if (!checked) arg.insert(arg.begin(),'!');
2067 executeAction(arg);
2068 }
2069 };
2070
2071 class Frame;
2072
2073 /// A radio box.
2074 /** Radio boxes can have any child widget as content.
2075 * There are convenience constructors for common forms of radio boxes.
2076 */
2077 class Radiobox : public BorderedWindow, public ActionEventSource {
2078 protected:
2079 /// \c true, if radio box is currently selected.
2080 bool checked;
2081
2082 public:
2083 /// Create a radio box with given position and size
2084 Radiobox(Frame *parent, int x, int y, int w, int h);
2085
2086 /// Create a radio box with text label.
2087 /** If a size is specified, text is centered. Otherwise, checkbox size is adjusted for the text. */
2088 template <typename T> Radiobox(Frame *parent, int x, int y, const T text, int w = -1, int h = -1);
2089
2090 /// Paint radio box.
2091 virtual void paint(Drawable &d) const;
2092
2093 /// Change radio box state.
2094 virtual void setChecked(bool checked) { this->checked = checked; }
2095
2096 /// Get radio box state.
2097 virtual bool isChecked() { return checked; }
2098
2099 /// Press radio box.
2100 virtual bool mouseDown(int x, int y, MouseButton button) {
2101 checked = true;
2102 return true;
2103 }
2104
2105 /// Release checkbox.
2106 virtual bool mouseUp(int x, int y, MouseButton button) {
2107 executeAction();
2108 return true;
2109 }
2110
2111 /// Handle keyboard input.
2112 virtual bool keyDown(const Key &key);
2113
2114 /// Handle keyboard input.
2115 virtual bool keyUp(const Key &key);
2116 };
2117
2118 /// A rectangular 3D sunken frame
2119 /** These can be used as generic grouping elements and also serve as aggregators for RadioBoxes.
2120 */
2121 class Frame : public BorderedWindow, public ActionEventSource, protected ActionEventSource_Callback {
2122 protected:
2123 friend class Radiobox;
2124
2125 /// Currently selected radio box.
2126 int selected;
2127
2128 /// Label of frame.
2129 String label;
2130
2131 /// Execute handlers.
2132 virtual void actionExecuted(ActionEventSource *src, const String &arg) {
2133 for (std::list<Window *>::iterator i = children.begin(); i != children.end(); ++i) {
2134 Radiobox *r = dynamic_cast<Radiobox*>(*i);
2135 if (r != NULL && src != dynamic_cast<ActionEventSource*>(r)) r->setChecked(false);
2136 }
2137 executeAction(src->getName());
2138 }
2139
2140 public:
2141 /// Create a non-labeled frame with given position and size
2142 Frame(Window *parent, int x, int y, int w, int h) : BorderedWindow(parent,x,y,w,h,5,5,5,5), ActionEventSource("GUI::Frame"), selected(0) {}
2143
2144 /// Create a frame with text label.
2145 template <typename T> Frame(Window *parent, int x, int y, int w, int h, const T text) :
2146 BorderedWindow(parent,x,y,w,h,5,Font::getFont("default")->getHeight()+2,5,5),
2147 ActionEventSource(text), selected(0), label(text) { }
2148
2149 /// Paint frame.
2150 virtual void paint(Drawable &d) const;
2151
2152 };
2153
2154 /// A message box with a single "Close" button.
2155 class MessageBox : public GUI::ToplevelWindow {
2156 protected:
2157 Label *message;
2158 Button *close;
2159 public:
2160 /// Create a new message box
2161 template <typename STR> MessageBox(Screen *parent, int x, int y, int width, const STR title, const STR text) :
2162 ToplevelWindow(parent, x, y, width, 1, title) {
2163 message = new Label(this, 5, 5, text, width-10);
2164 close = new GUI::Button(this, width/2-40, 10, "Close", 70);
2165 close->addActionHandler(this);
2166 setText(text);
2167 }
2168
2169 /// Set a new text. Size of the box is adjusted accordingly.
2170 template <typename STR> void setText(const STR text) {
2171 message->setText(text);
2172 close->move(width/2-40, 20+message->getHeight());
2173 resize(width, message->getHeight()+100);
2174 }
2175 };
2176
2177 template <typename STR> ToplevelWindow::ToplevelWindow(Screen *parent, int x, int y, int w, int h, const STR title) :
2178 BorderedWindow(parent, x, y, w, h, 6, 33, 6, 3), title(title),
2179 dragx(-1), dragy(-1), closehandlers(), systemMenu(new Menu(this,-1,-2,"System Menu")) {
2180 systemMenu->addItem("Move");
2181 systemMenu->addItem("Resize");
2182 systemMenu->addItem("");
2183 systemMenu->addItem("Minimize");
2184 systemMenu->addItem("Maximize");
2185 systemMenu->addItem("Restore");
2186 systemMenu->addItem("");
2187 systemMenu->addItem("Close");
2188 systemMenu->addActionHandler(this);
2189 }
2190
2191 template <typename STR> Button::Button(Window *parent, int x, int y, const STR text, int w, int h) :
2192 BorderedWindow(parent,x,y,w,h,6,5,6,5), ActionEventSource(text), pressed(0)
2193 {
2194
2195 Label *l = new Label(this,0,0,text);
2196 if (width < 0) resize(l->getWidth()+border_left+border_right+10,height);
2197 if (height < 0) resize(width,l->getHeight()+border_top+border_bottom+6);
2198 l->move((width-border_left-border_right-l->getWidth())/2,
2199 (height-border_top-border_bottom-l->getHeight())/2);
2200 }
2201
2202 template <typename STR> Checkbox::Checkbox(Window *parent, int x, int y, const STR text, int w, int h) :
2203 BorderedWindow(parent,x,y,w,h,16,0,0,0), ActionEventSource(text), checked(0)
2204 {
2205 Label *l = new Label(this,0,0,text);
2206 if (width < 0) resize(l->getWidth()+border_left+border_right+4,height);
2207 if (height < 0) resize(width,l->getHeight()+border_top+border_bottom+4);
2208 l->move((width-border_left-border_right-l->getWidth())/2,
2209 (height-border_top-border_bottom-l->getHeight())/2);
2210 }
2211
2212 template <typename STR> Radiobox::Radiobox(Frame *parent, int x, int y, const STR text, int w, int h) :
2213 BorderedWindow(parent,x,y,w,h,16,0,0,0), ActionEventSource(text), checked(0)
2214 {
2215 Label *l = new Label(this,0,0,text);
2216 if (width < 0) resize(l->getWidth()+border_left+border_right+4,height);
2217 if (height < 0) resize(width,l->getHeight()+border_top+border_bottom+4);
2218 l->move((width-border_left-border_right-l->getWidth())/2,
2219 (height-border_top-border_bottom-l->getHeight())/2);
2220 addActionHandler(parent);
2221 }
2222
2223 };
2224
2225 #endif