/*********************************************************************** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT MODIFY DEVELOPER: Zihan Chen(vczh) ***********************************************************************/ #include "VlppGlrParser.h" #include "VlppWorkflowLibrary.h" #include "VlppReflection.h" #include "VlppOS.h" #include "Vlpp.h" #include "VlppRegex.h" #include "VlppParser.h" /*********************************************************************** .\GUITYPES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Common Types Classes: ***********************************************************************/ #ifndef VCZH_PRESENTATION_GUITYPES #define VCZH_PRESENTATION_GUITYPES namespace vl { namespace presentation { using namespace reflection; /*********************************************************************** Enumerations ***********************************************************************/ /// /// Defines an alignment direction. /// enum class Alignment { /// Aligned to the left side. Left=0, /// Aligned to the top side. Top=0, /// Aligned to the center. Center=1, /// Aligned to the right side. Right=2, /// Aligned to the bottom side. Bottom=2, }; /// Axis direction. enum class AxisDirection { /// X:left, Y:down. LeftDown, /// X:right, Y:down. RightDown, /// X:left, Y:up. LeftUp, /// X:right, Y:up. RightUp, /// X:down, Y:left. DownLeft, /// X:down, Y:right. DownRight, /// X:up, Y:left. UpLeft, /// X:up, Y:right. UpRight, }; #define GUI_DEFINE_COMPARE_OPERATORS(TYPE)\ inline bool operator==(const TYPE& right)const { return Compare(right) == 0; } \ inline bool operator!=(const TYPE& right)const { return Compare(right) != 0; } \ inline bool operator< (const TYPE& right)const { return Compare(right) < 0; } \ inline bool operator<=(const TYPE& right)const { return Compare(right) <= 0; } \ inline bool operator> (const TYPE& right)const { return Compare(right) > 0; } \ inline bool operator>=(const TYPE& right)const { return Compare(right) >= 0; } \ /*********************************************************************** TextPos ***********************************************************************/ /// /// Represents the position in multiple lines of text. /// struct TextPos { /// /// Row number. /// vint row; /// /// Column number. If a line has 4 characters, there are 5 available column numbers(from 0 to 4) in this line. /// vint column; TextPos() :row(0) ,column(0) { } TextPos(vint _row, vint _column) :row(_row) ,column(_column) { } inline vint Compare(const TextPos& value)const { vint result; if ((result = row - value.row) != 0) return result; if ((result = column - value.column) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(TextPos) }; /*********************************************************************** GridPos ***********************************************************************/ /// /// Represents the cell position in a grid. /// struct GridPos { /// /// Row number. /// vint row; /// /// Column number. If a line has 4 characters, there are 5 available column numbers(from 0 to 4) in this line. /// vint column; GridPos() :row(0) ,column(0) { } GridPos(vint _row, vint _column) :row(_row) ,column(_column) { } inline vint Compare(const GridPos& value)const { vint result; if ((result = row - value.row) != 0) return result; if ((result = column - value.column) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(GridPos) }; /*********************************************************************** Coordinate ***********************************************************************/ /// /// Represents a position in the local window coordinate space, which is DPI awared. /// using GuiCoordinate = vint; /// /// Represents a position in the global screen coordinate space. /// struct NativeCoordinate { vint value; NativeCoordinate() :value(0) {} NativeCoordinate(vint _value) :value(_value) {} NativeCoordinate(const NativeCoordinate& _value) = default; NativeCoordinate(NativeCoordinate&& _value) = default; NativeCoordinate& operator=(const NativeCoordinate& _value) = default; NativeCoordinate& operator=(NativeCoordinate&& _value) = default; inline vint Compare(NativeCoordinate c) const { return value - c.value; } GUI_DEFINE_COMPARE_OPERATORS(NativeCoordinate) inline NativeCoordinate operator+(NativeCoordinate c)const { return value + c.value; }; inline NativeCoordinate operator-(NativeCoordinate c)const { return value - c.value; }; inline NativeCoordinate operator*(NativeCoordinate c)const { return value * c.value; }; inline NativeCoordinate operator/(NativeCoordinate c)const { return value / c.value; }; inline NativeCoordinate& operator+=(NativeCoordinate c) { value += c.value; return *this; }; inline NativeCoordinate& operator-=(NativeCoordinate c) { value -= c.value; return *this; }; inline NativeCoordinate& operator*=(NativeCoordinate c) { value *= c.value; return *this; }; inline NativeCoordinate& operator/=(NativeCoordinate c) { value /= c.value; return *this; }; }; inline vint CompareCoordinate(vint a, vint b) { return a - b; } inline vint CompareCoordinate(NativeCoordinate a, NativeCoordinate b) { return a.value - b.value; } /*********************************************************************** Point ***********************************************************************/ /// /// Represents a position in a two dimensions space. /// /// Type of the coordinate. template struct Point_ { /// /// Position in x dimension. /// T x; /// /// Position in y dimension. /// T y; Point_() :x(0), y(0) { } Point_(T _x, T _y) :x(_x), y(_y) { } inline vint Compare(const Point_& value)const { vint result; if ((result = CompareCoordinate(x, value.x)) != 0) return result; if ((result = CompareCoordinate(y, value.y)) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(Point_) }; using Point = Point_; using NativePoint = Point_; /*********************************************************************** Size ***********************************************************************/ /// /// Represents a size in a two dimensions space. /// /// Type of the coordinate. template struct Size_ { /// /// Size in x dimension. /// T x; /// /// Size in y dimension. /// T y; Size_() :x(0), y(0) { } Size_(T _x, T _y) :x(_x), y(_y) { } inline vint Compare(const Size_& value)const { vint result; if ((result = CompareCoordinate(x, value.x)) != 0) return result; if ((result = CompareCoordinate(y, value.y)) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(Size_) }; using Size = Size_; using NativeSize = Size_; /*********************************************************************** Rectangle ***********************************************************************/ /// /// Represents a bounds in a two dimensions space. /// /// Type of the coordinate. template struct Rect_ { /// /// Left. /// T x1; /// /// Top. /// T y1; /// /// Left + Width. /// T x2; /// /// Top + Height. /// T y2; Rect_() :x1(0), y1(0), x2(0), y2(0) { } Rect_(T _x1, T _y1, T _x2, T _y2) :x1(_x1), y1(_y1), x2(_x2), y2(_y2) { } Rect_(Point_ p, Size_ s) :x1(p.x), y1(p.y), x2(p.x + s.x), y2(p.y + s.y) { } inline vint Compare(const Rect_& value)const { vint result; if ((result = CompareCoordinate(x1, value.x1)) != 0) return result; if ((result = CompareCoordinate(y1, value.y1)) != 0) return result; if ((result = CompareCoordinate(x2, value.x2)) != 0) return result; if ((result = CompareCoordinate(y2, value.y2)) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(Rect_) Point_ LeftTop()const { return Point_(x1, y1); } Point_ RightBottom()const { return Point_(x2, y2); } Size_ GetSize()const { return Size_(x2 - x1, y2 - y1); } T Left()const { return x1; } T Right()const { return x2; } T Width()const { return x2 - x1; } T Top()const { return y1; } T Bottom()const { return y2; } T Height()const { return y2 - y1; } void Expand(T x, T y) { x1 -= x; y1 -= y; x2 += x; y2 += y; } void Expand(Size_ s) { x1 -= s.x; y1 -= s.y; x2 += s.x; y2 += s.y; } void Move(T x, T y) { x1 += x; y1 += y; x2 += x; y2 += y; } void Move(Size_ s) { x1 += s.x; y1 += s.y; x2 += s.x; y2 += s.y; } bool Contains(Point_ p) { return x1 <= p.x && p.x < x2 && y1 <= p.y && p.y < y2; } }; using Rect = Rect_; using NativeRect = Rect_; /*********************************************************************** 2D operations ***********************************************************************/ template inline Point_ operator+(Point_ p, Size_ s) { return Point_(p.x + s.x, p.y + s.y); } template inline Point_ operator+(Size_ s, Point_ p) { return Point_(p.x + s.x, p.y + s.y); } template inline Point_ operator-(Point_ p, Size_ s) { return Point_(p.x - s.x, p.y - s.y); } template inline Size_ operator-(Point_ p1, Point_ p2) { return Size_(p1.x - p2.x, p1.y - p2.y); } template inline Size_ operator+(Size_ s1, Size_ s2) { return Size_(s1.x + s2.x, s1.y + s2.y); } template inline Size_ operator-(Size_ s1, Size_ s2) { return Size_(s1.x - s2.x, s1.y - s2.y); } template inline Size_ operator*(Size_ s, vint i) { return Size_(s.x*i, s.y*i); } template inline Size_ operator/(Size_ s, vint i) { return Size_(s.x / i, s.y / i); } template inline Point_ operator+=(Point_& s1, Size_ s2) { s1.x += s2.x; s1.y += s2.y; return s1; } template inline Point_ operator-=(Point_& s1, Size_ s2) { s1.x -= s2.x; s1.y -= s2.y; return s1; } template inline Size_ operator+=(Size_& s1, Size_ s2) { s1.x += s2.x; s1.y += s2.y; return s1; } template inline Size_ operator-=(Size_& s1, Size_ s2) { s1.x -= s2.x; s1.y -= s2.y; return s1; } /*********************************************************************** Color ***********************************************************************/ /// Represents a 32bit RGBA color. Values of separate components can be accessed using fields "r", "g", "b" and "a". struct Color { union { struct { unsigned char r; unsigned char g; unsigned char b; unsigned char a; }; vuint32_t value; }; Color() :r(0), g(0), b(0), a(255) { } Color(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a=255) :r(_r), g(_g), b(_b), a(_a) { } vint64_t Compare(Color color)const { return (vint64_t)value - (vint64_t)color.value; } GUI_DEFINE_COMPARE_OPERATORS(Color) static Color Parse(const WString& value) { const wchar_t* code=L"0123456789ABCDEF"; if((value.Length()==7 || value.Length()==9) && value[0]==L'#') { vint index[8]={15, 15, 15, 15, 15, 15, 15, 15}; for(vint i=0;i15) { return Color(); } } Color c; c.r=(unsigned char)(index[0]*16+index[1]); c.g=(unsigned char)(index[2]*16+index[3]); c.b=(unsigned char)(index[4]*16+index[5]); c.a=(unsigned char)(index[6]*16+index[7]); return c; } return Color(); } WString ToString()const { const wchar_t* code=L"0123456789ABCDEF"; wchar_t result[10]=L"#00000000"; result[1]=code[r/16]; result[2]=code[r%16]; result[3]=code[g/16]; result[4]=code[g%16]; result[5]=code[b/16]; result[6]=code[b%16]; if(a==255) { result[7]=L'\0'; } else { result[7]=code[a/16]; result[8]=code[a%16]; } return result; } }; /*********************************************************************** Margin ***********************************************************************/ /// /// Represents a margin in a two dimensions space. /// /// Type of the coordinate. template struct Margin_ { /// /// The left margin. /// T left; /// /// The top margin. /// T top; /// /// The right margin. /// T right; /// /// The bottom margin. /// T bottom; Margin_() :left(0), top(0), right(0), bottom(0) { } Margin_(T _left, T _top, T _right, T _bottom) :left(_left), top(_top), right(_right), bottom(_bottom) { } inline vint Compare(const Margin_& value)const { vint result; if ((result = CompareCoordinate(left, value.left)) != 0) return result; if ((result = CompareCoordinate(top, value.top)) != 0) return result; if ((result = CompareCoordinate(right, value.right)) != 0) return result; if ((result = CompareCoordinate(bottom, value.bottom)) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(Margin_) }; using Margin = Margin_; using NativeMargin = Margin_; /*********************************************************************** Resources ***********************************************************************/ /// /// Represents a font configuration. /// struct FontProperties { /// /// Font family (or font name, usually). /// WString fontFamily; /// /// Font size in pixel. /// vint size; /// /// True if the font is bold. /// bool bold; /// /// True if the font is italic. /// bool italic; /// /// True if the font has a underline. /// bool underline; /// /// True if the font has a strikeline. /// bool strikeline; /// /// True if the font has anti alias rendering. /// bool antialias; /// /// True if the font has anti alias rendering in vertical direction. /// bool verticalAntialias; FontProperties() :size(0) ,bold(false) ,italic(false) ,underline(false) ,strikeline(false) ,antialias(true) ,verticalAntialias(false) { } vint64_t Compare(const FontProperties& value)const { vint64_t result = 0; result = WString::Compare(fontFamily, value.fontFamily); if (result != 0) return result; result = (vint64_t)size - (vint64_t)value.size; if (result != 0) return result; result = (vint64_t)bold - (vint64_t)value.bold; if (result != 0) return result; result = (vint64_t)italic - (vint64_t)value.italic; if (result != 0) return result; result = (vint64_t)underline - (vint64_t)value.underline; if (result != 0) return result; result = (vint64_t)strikeline - (vint64_t)value.strikeline; if (result != 0) return result; result = (vint64_t)antialias - (vint64_t)value.antialias; if (result != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(FontProperties) }; /*********************************************************************** Keys ***********************************************************************/ #define GUI_DEFINE_KEYBOARD_CODE(ITEM) \ /* \ * Virtual Keys, Standard Set \ */ \ ITEM(LBUTTON, 0x01) \ ITEM(RBUTTON, 0x02) \ ITEM(CANCEL, 0x03) \ ITEM(MBUTTON, 0x04) /* NOT contiguous with L & RBUTTON */ \ ITEM(XBUTTON1, 0x05) /* NOT contiguous with L & RBUTTON */ \ ITEM(XBUTTON2, 0x06) /* NOT contiguous with L & RBUTTON */ \ ITEM(BACK, 0x08) \ ITEM(TAB, 0x09) \ ITEM(CLEAR, 0x0C) \ ITEM(RETURN, 0x0D) \ ITEM(SHIFT, 0x10) \ ITEM(CONTROL, 0x11) \ ITEM(MENU, 0x12) \ ITEM(PAUSE, 0x13) \ ITEM(CAPITAL, 0x14) \ ITEM(KANA_HANGUL, 0x15) \ ITEM(JUNJA, 0x17) \ ITEM(FINAL, 0x18) \ ITEM(HANJA, 0x19) \ ITEM(KANJI, 0x19) \ ITEM(ESCAPE, 0x1B) \ ITEM(CONVERT, 0x1C) \ ITEM(NONCONVERT, 0x1D) \ ITEM(ACCEPT, 0x1E) \ ITEM(MODECHANGE, 0x1F) \ ITEM(SPACE, 0x20) \ ITEM(PRIOR, 0x21) \ ITEM(NEXT, 0x22) \ ITEM(END, 0x23) \ ITEM(HOME, 0x24) \ ITEM(LEFT, 0x25) \ ITEM(UP, 0x26) \ ITEM(RIGHT, 0x27) \ ITEM(DOWN, 0x28) \ ITEM(SELECT, 0x29) \ ITEM(PRINT, 0x2A) \ ITEM(EXECUTE, 0x2B) \ ITEM(SNAPSHOT, 0x2C) \ ITEM(INSERT, 0x2D) \ ITEM(DELETE, 0x2E) \ ITEM(HELP, 0x2F) \ /* \ * VKEY_0 - VKEY_9 are the same as ASCII '0' - '9' (0x30 - 0x39) \ * VKEY_A - VKEY_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) \ */ \ ITEM(0, 0x30) \ ITEM(1, 0x31) \ ITEM(2, 0x32) \ ITEM(3, 0x33) \ ITEM(4, 0x34) \ ITEM(5, 0x35) \ ITEM(6, 0x36) \ ITEM(7, 0x37) \ ITEM(8, 0x38) \ ITEM(9, 0x39) \ ITEM(A, 0x41) \ ITEM(B, 0x42) \ ITEM(C, 0x43) \ ITEM(D, 0x44) \ ITEM(E, 0x45) \ ITEM(F, 0x46) \ ITEM(G, 0x47) \ ITEM(H, 0x48) \ ITEM(I, 0x49) \ ITEM(J, 0x4A) \ ITEM(K, 0x4B) \ ITEM(L, 0x4C) \ ITEM(M, 0x4D) \ ITEM(N, 0x4E) \ ITEM(O, 0x4F) \ ITEM(P, 0x50) \ ITEM(Q, 0x51) \ ITEM(R, 0x52) \ ITEM(S, 0x53) \ ITEM(T, 0x54) \ ITEM(U, 0x55) \ ITEM(V, 0x56) \ ITEM(W, 0x57) \ ITEM(X, 0x58) \ ITEM(Y, 0x59) \ ITEM(Z, 0x5A) \ ITEM(LWIN, 0x5B) \ ITEM(RWIN, 0x5C) \ ITEM(APPS, 0x5D) \ ITEM(SLEEP, 0x5F) \ ITEM(NUMPAD0, 0x60) \ ITEM(NUMPAD1, 0x61) \ ITEM(NUMPAD2, 0x62) \ ITEM(NUMPAD3, 0x63) \ ITEM(NUMPAD4, 0x64) \ ITEM(NUMPAD5, 0x65) \ ITEM(NUMPAD6, 0x66) \ ITEM(NUMPAD7, 0x67) \ ITEM(NUMPAD8, 0x68) \ ITEM(NUMPAD9, 0x69) \ ITEM(MULTIPLY, 0x6A) \ ITEM(ADD, 0x6B) \ ITEM(SEPARATOR, 0x6C) \ ITEM(SUBTRACT, 0x6D) \ ITEM(DECIMAL, 0x6E) \ ITEM(DIVIDE, 0x6F) \ ITEM(F1, 0x70) \ ITEM(F2, 0x71) \ ITEM(F3, 0x72) \ ITEM(F4, 0x73) \ ITEM(F5, 0x74) \ ITEM(F6, 0x75) \ ITEM(F7, 0x76) \ ITEM(F8, 0x77) \ ITEM(F9, 0x78) \ ITEM(F10, 0x79) \ ITEM(F11, 0x7A) \ ITEM(F12, 0x7B) \ ITEM(F13, 0x7C) \ ITEM(F14, 0x7D) \ ITEM(F15, 0x7E) \ ITEM(F16, 0x7F) \ ITEM(F17, 0x80) \ ITEM(F18, 0x81) \ ITEM(F19, 0x82) \ ITEM(F20, 0x83) \ ITEM(F21, 0x84) \ ITEM(F22, 0x85) \ ITEM(F23, 0x86) \ ITEM(F24, 0x87) \ ITEM(NUMLOCK, 0x90) \ ITEM(SCROLL, 0x91) \ /* \ * NEC PC-9800 kbd definitions \ */ \ ITEM(OEM_NEC_EQUAL, 0x92) /* '=' key on numpad */ \ /* \ * Fujitsu/OASYS kbd definitions \ */ \ ITEM(OEM_FJ_JISHO, 0x92) /* 'Dictionary' key */ \ ITEM(OEM_FJ_MASSHOU, 0x93) /* 'Unregister word' key */ \ ITEM(OEM_FJ_TOUROKU, 0x94) /* 'Register word' key */ \ ITEM(OEM_FJ_LOYA, 0x95) /* 'Left OYAYUBI' key */ \ ITEM(OEM_FJ_ROYA, 0x96) /* 'Right OYAYUBI' key */ \ /* \ * VKEY_L* & VKEY_R* - left and right Alt, Ctrl and Shift virtual keys. \ * Used only as parameters to GetAsyncKeyState() and GetKeyState(). \ * No other API or message will distinguish left and right keys in this way. \ */ \ ITEM(LSHIFT, 0xA0) \ ITEM(RSHIFT, 0xA1) \ ITEM(LCONTROL, 0xA2) \ ITEM(RCONTROL, 0xA3) \ ITEM(LMENU, 0xA4) \ ITEM(RMENU, 0xA5) \ ITEM(BROWSER_BACK, 0xA6) \ ITEM(BROWSER_FORWARD, 0xA7) \ ITEM(BROWSER_REFRESH, 0xA8) \ ITEM(BROWSER_STOP, 0xA9) \ ITEM(BROWSER_SEARCH, 0xAA) \ ITEM(BROWSER_FAVORITES, 0xAB) \ ITEM(BROWSER_HOME, 0xAC) \ ITEM(VOLUME_MUTE, 0xAD) \ ITEM(VOLUME_DOWN, 0xAE) \ ITEM(VOLUME_UP, 0xAF) \ ITEM(MEDIA_NEXT_TRACK, 0xB0) \ ITEM(MEDIA_PREV_TRACK, 0xB1) \ ITEM(MEDIA_STOP, 0xB2) \ ITEM(MEDIA_PLAY_PAUSE, 0xB3) \ ITEM(LAUNCH_MAIL, 0xB4) \ ITEM(LAUNCH_MEDIA_SELECT, 0xB5) \ ITEM(LAUNCH_APP1, 0xB6) \ ITEM(LAUNCH_APP2, 0xB7) \ ITEM(OEM_1, 0xBA) /* ';:' for US */ \ ITEM(OEM_PLUS, 0xBB) /* '+' any country */ \ ITEM(OEM_COMMA, 0xBC) /* ',' any country */ \ ITEM(OEM_MINUS, 0xBD) /* '-' any country */ \ ITEM(OEM_PERIOD, 0xBE) /* '.' any country */ \ ITEM(OEM_2, 0xBF) /* '/?' for US */ \ ITEM(OEM_3, 0xC0) /* '`~' for US */ \ ITEM(OEM_4, 0xDB) /* '[{' for US */ \ ITEM(OEM_5, 0xDC) /* '\|' for US */ \ ITEM(OEM_6, 0xDD) /* ']}' for US */ \ ITEM(OEM_7, 0xDE) /* ''"' for US */ \ ITEM(OEM_8, 0xDF) \ /* \ * Various extended or enhanced keyboards \ */ \ ITEM(OEM_AX, 0xE1) /* 'AX' key on Japanese AX kbd */ \ ITEM(OEM_102, 0xE2) /* "<>" or "\|" on RT 102-key kbd */ \ ITEM(ICO_HELP, 0xE3) /* Help key on ICO */ \ ITEM(ICO_00, 0xE4) /* 00 key on ICO */ \ ITEM(PROCESSKEY, 0xE5) \ ITEM(ICO_CLEAR, 0xE6) \ ITEM(PACKET, 0xE7) \ /* \ * Nokia/Ericsson definitions \ */ \ ITEM(OEM_RESET, 0xE9) \ ITEM(OEM_JUMP, 0xEA) \ ITEM(OEM_PA1, 0xEB) \ ITEM(OEM_PA2, 0xEC) \ ITEM(OEM_PA3, 0xED) \ ITEM(OEM_WSCTRL, 0xEE) \ ITEM(OEM_CUSEL, 0xEF) \ ITEM(OEM_ATTN, 0xF0) \ ITEM(OEM_FINISH, 0xF1) \ ITEM(OEM_COPY, 0xF2) \ ITEM(OEM_AUTO, 0xF3) \ ITEM(OEM_ENLW, 0xF4) \ ITEM(OEM_BACKTAB, 0xF5) \ ITEM(ATTN, 0xF6) \ ITEM(CRSEL, 0xF7) \ ITEM(EXSEL, 0xF8) \ ITEM(EREOF, 0xF9) \ ITEM(PLAY, 0xFA) \ ITEM(ZOOM, 0xFB) \ ITEM(NONAME, 0xFC) \ ITEM(PA1, 0xFD) \ ITEM(OEM_CLEAR, 0xFE) \ /* \ * Friendly names for common keys (US) \ */ \ ITEM(SEMICOLON, 0xBA) /* OEM_1 */ \ ITEM(SLASH, 0xBF) /* OEM_2 */ \ ITEM(GRAVE_ACCENT, 0xC0) /* OEM_3 */ \ ITEM(RIGHT_BRACKET, 0xDB) /* OEM_4 */ \ ITEM(BACKSLASH, 0xDC) /* OEM_5 */ \ ITEM(LEFT_BRACKET, 0xDD) /* OEM_6 */ \ ITEM(APOSTROPHE, 0xDE) /* OEM_7 */ \ #define GUI_DEFINE_KEYBOARD_CODE_ENUM_ITEM(NAME, CODE) KEY_##NAME = CODE, enum class VKEY { KEY_UNKNOWN = -1, GUI_DEFINE_KEYBOARD_CODE(GUI_DEFINE_KEYBOARD_CODE_ENUM_ITEM) }; #undef GUI_DEFINE_KEYBOARD_CODE_ENUM_ITEM static bool operator == (VKEY a, VKEY b) { return (vint)a == (vint)b; } static bool operator != (VKEY a, VKEY b) { return (vint)a != (vint)b; } static bool operator < (VKEY a, VKEY b) { return (vint)a < (vint)b; } static bool operator <= (VKEY a, VKEY b) { return (vint)a <= (vint)b; } static bool operator > (VKEY a, VKEY b) { return (vint)a > (vint)b; } static bool operator >= (VKEY a, VKEY b) { return (vint)a >= (vint)b; } static VKEY operator & (VKEY a, VKEY b) { return (VKEY)((vint)a & (vint)b); } static VKEY operator | (VKEY a, VKEY b) { return (VKEY)((vint)a | (vint)b); } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSAXIS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSAXIS #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSAXIS namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Axis Interface ***********************************************************************/ /// Represents the four directions that is accessable by keyboard. enum class KeyDirection { /// The up direction. Up, /// The down direction. Down, /// The left direction. Left, /// The right direction. Right, /// The home direction. Home, /// The end direction. End, /// The page up direction. PageUp, /// The page down direction. PageDown, /// The page left direction. PageLeft, /// The page right direction. PageRight, }; /// Item coordinate transformer for a . In all functions in this interface, real coordinate is in the list control's container space, virtual coordinate is in a space that the transformer created. class IGuiAxis : public virtual IDescriptable, public Description { public: /// Translate real size to virtual size. /// The virtual size. /// The real size. virtual Size RealSizeToVirtualSize(Size size)=0; /// Translate virtual size to real size. /// The real size. /// The virtual size. virtual Size VirtualSizeToRealSize(Size size)=0; /// Translate real point to virtual point. /// The virtual point. /// The real full size. /// The real point. virtual Point RealPointToVirtualPoint(Size realFullSize, Point point)=0; /// Translate virtual point to real point. /// The real point. /// The real full size. /// The virtual point. virtual Point VirtualPointToRealPoint(Size realFullSize, Point point)=0; /// Translate real bounds to virtual bounds. /// The virtual bounds. /// The real full size. /// The real bounds. virtual Rect RealRectToVirtualRect(Size realFullSize, Rect rect)=0; /// Translate virtual bounds to real bounds. /// The real bounds. /// The real full size. /// The virtual bounds. virtual Rect VirtualRectToRealRect(Size realFullSize, Rect rect)=0; /// Translate real margin to margin size. /// The virtual margin. /// The real margin. virtual Margin RealMarginToVirtualMargin(Margin margin)=0; /// Translate virtual margin to margin size. /// The real margin. /// The virtual margin. virtual Margin VirtualMarginToRealMargin(Margin margin)=0; /// Translate real key direction to virtual key direction. /// The virtual key direction. /// The real key direction. virtual KeyDirection RealKeyDirectionToVirtualKeyDirection(KeyDirection key)=0; }; /*********************************************************************** Axis Implementation ***********************************************************************/ /// Default item coordinate transformer. This transformer doesn't transform any coordinate. class GuiDefaultAxis : public Object, virtual public IGuiAxis, public Description { public: /// Create the transformer. GuiDefaultAxis(); ~GuiDefaultAxis(); Size RealSizeToVirtualSize(Size size)override; Size VirtualSizeToRealSize(Size size)override; Point RealPointToVirtualPoint(Size realFullSize, Point point)override; Point VirtualPointToRealPoint(Size realFullSize, Point point)override; Rect RealRectToVirtualRect(Size realFullSize, Rect rect)override; Rect VirtualRectToRealRect(Size realFullSize, Rect rect)override; Margin RealMarginToVirtualMargin(Margin margin)override; Margin VirtualMarginToRealMargin(Margin margin)override; KeyDirection RealKeyDirectionToVirtualKeyDirection(KeyDirection key)override; }; /// Axis aligned item coordinate transformer. This transformer transforms coordinates by changing the axis direction. class GuiAxis : public Object, virtual public IGuiAxis, public Description { protected: AxisDirection axisDirection; public: /// Create the transformer with a specified axis direction. /// The specified axis direction. GuiAxis(AxisDirection _axisDirection); ~GuiAxis(); /// Get the specified axis direction. /// The specified axis direction. AxisDirection GetDirection(); Size RealSizeToVirtualSize(Size size)override; Size VirtualSizeToRealSize(Size size)override; Point RealPointToVirtualPoint(Size realFullSize, Point point)override; Point VirtualPointToRealPoint(Size realFullSize, Point point)override; Rect RealRectToVirtualRect(Size realFullSize, Rect rect)override; Rect VirtualRectToRealRect(Size realFullSize, Rect rect)override; Margin RealMarginToVirtualMargin(Margin margin)override; Margin VirtualMarginToRealMargin(Margin margin)override; KeyDirection RealKeyDirectionToVirtualKeyDirection(KeyDirection key)override; }; } } } #endif /*********************************************************************** .\GRAPHICSELEMENT\GUIGRAPHICSELEMENTINTERFACES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Element System and Infrastructure Interfaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSELEMENTINTERFACES #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSELEMENTINTERFACES namespace vl { namespace presentation { namespace compositions { class GuiGraphicsComposition; extern void InvokeOnCompositionStateChanged(compositions::GuiGraphicsComposition* composition); } namespace elements { class IGuiGraphicsElement; class IGuiGraphicsRenderer; class IGuiGraphicsRendererFactory; class IGuiGraphicsRenderTarget; /*********************************************************************** Basic Construction ***********************************************************************/ /// /// This is the interface for graphics elements. /// Graphics elements usually contains some information and helper functions for visible things. /// An graphics elements should be created using ElementType::Create. /// class IGuiGraphicsElement : public virtual IDescriptable, public Description { friend class compositions::GuiGraphicsComposition; protected: virtual void SetOwnerComposition(compositions::GuiGraphicsComposition* composition) = 0; public: /// /// Access the associated for this graphics element. /// /// Returns the related renderer. virtual IGuiGraphicsRenderer* GetRenderer() = 0; /// /// Get the owner composition. /// /// The owner composition. virtual compositions::GuiGraphicsComposition* GetOwnerComposition() = 0; }; /// /// This is the interface for graphics renderers. /// class IGuiGraphicsRenderer : public Interface { public: /// /// Access the graphics that is used to create this graphics renderer. /// /// Returns the related factory. virtual IGuiGraphicsRendererFactory* GetFactory()=0; /// /// Initialize the grpahics renderer by binding a to it. /// /// The graphics element to bind. virtual void Initialize(IGuiGraphicsElement* element)=0; /// /// Release all resources that used by this renderer. /// virtual void Finalize()=0; /// /// Set a to this element. /// /// The graphics render target. It can be NULL. virtual void SetRenderTarget(IGuiGraphicsRenderTarget* renderTarget)=0; /// /// Render the graphics element using a specified bounds. /// /// Bounds to decide the size and position of the binded graphics element. virtual void Render(Rect bounds)=0; /// /// Notify that the state in the binded graphics element is changed. This function is usually called by the element itself. /// virtual void OnElementStateChanged()=0; /// /// Calculate the minimum size using the binded graphics element and its state. /// /// The minimum size. virtual Size GetMinSize()=0; }; /// /// This is the interface for graphics renderer factories. /// Graphics renderers should be registered using [M:vl.presentation.elements.GuiGraphicsResourceManager.RegisterRendererFactory]. /// class IGuiGraphicsRendererFactory : public Interface { public: /// /// Create a . /// /// Returns the created graphics renderer. virtual IGuiGraphicsRenderer* Create()=0; }; enum RenderTargetFailure { None, ResizeWhileRendering, LostDevice, }; /// /// This is the interface for graphics renderer targets. /// class IGuiGraphicsRenderTarget : public Interface { public: /// /// Notify the target to prepare for rendering. /// virtual void StartRendering()=0; /// /// Notify the target to stop rendering. /// /// Returns false to recreate render target. virtual RenderTargetFailure StopRendering()=0; /// /// Apply a clipper to the render target. /// The result clipper is combined by all clippers in the clipper stack maintained by the render target. /// /// The clipper to push. virtual void PushClipper(Rect clipper)=0; /// /// Remove the last pushed clipper from the clipper stack. /// virtual void PopClipper()=0; /// /// Get the combined clipper /// /// The combined clipper virtual Rect GetClipper()=0; /// /// Test is the combined clipper is as large as the render target. /// /// Return true if the combined clipper is as large as the render target. virtual bool IsClipperCoverWholeTarget()=0; }; } } } #endif /*********************************************************************** .\GRAPHICSELEMENT\GUIGRAPHICSDOCUMENTINTERFACES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Element System and Infrastructure Interfaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSDOCUMENTINTERFACES #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSDOCUMENTINTERFACES namespace vl { namespace presentation { namespace elements { /*********************************************************************** Layout Engine ***********************************************************************/ class IGuiGraphicsParagraph; class IGuiGraphicsLayoutProvider; /// Represents a paragraph of a layouted rich text content. class IGuiGraphicsParagraph : public IDescriptable, public Description { public: static const vint NullInteractionId = -1; /// Text style. Items in this enumeration type can be combined. enum TextStyle { /// Bold. Bold=1, /// Italic. Italic=2, /// Underline. Underline=4, /// Strikeline. Strikeline=8, }; /// Inline object break condition. enum BreakCondition { /// Stay together with the previous run if possible. StickToPreviousRun, /// Stay together with the next run if possible. StickToNextRun, /// Treat as a single run. Alone, }; /// Caret relative position. enum CaretRelativePosition { /// The first caret position. CaretFirst, /// The last caret position. CaretLast, /// The first caret position of the current line. CaretLineFirst, /// The last caret position of the current line. CaretLineLast, /// The relative left caret position. CaretMoveLeft, /// The relative right caret position. CaretMoveRight, /// The relative up caret position. CaretMoveUp, /// The relative down caret position. CaretMoveDown, }; /// Inline object properties. struct InlineObjectProperties { /// The size of the inline object. Size size; /// The baseline of the inline object.If the baseline is at the bottom, then set the baseline to -1. vint baseline = -1; /// The break condition of the inline object. BreakCondition breakCondition; /// The background image, nullable. Ptr backgroundImage; /// The id for callback. If the value is -1, then no callback will be received . vint callbackId = -1; InlineObjectProperties() :baseline(-1) { } }; /// Get the object that created this paragraph. /// The layout provider object. virtual IGuiGraphicsLayoutProvider* GetProvider()=0; /// Get the associated to this paragraph. /// The associated render target. virtual IGuiGraphicsRenderTarget* GetRenderTarget()=0; /// Get if line auto-wrapping is enabled for this paragraph. /// Return true if line auto-wrapping is enabled for this paragraph. virtual bool GetWrapLine()=0; /// Set if line auto-wrapping is enabled for this paragraph. /// True if line auto-wrapping is enabled for this paragraph. virtual void SetWrapLine(bool value)=0; /// Get the max width for this paragraph. If there is no max width limitation, it returns -1. /// The max width for this paragraph. virtual vint GetMaxWidth()=0; /// Set the max width for this paragraph. If the max width is set to -1, the max width limitation will be removed. /// The max width. virtual void SetMaxWidth(vint value)=0; /// Get the horizontal alignment for this paragraph. /// The alignment. virtual Alignment GetParagraphAlignment()=0; /// Set the horizontal alignment for this paragraph. /// The alignment. virtual void SetParagraphAlignment(Alignment value)=0; /// Replace the font within the specified range. /// The position of the first character of the specified range. /// The length of the specified range by character. /// The font. /// Returns true if this operation succeeded. virtual bool SetFont(vint start, vint length, const WString& value)=0; /// Replace the size within the specified range. /// The position of the first character of the specified range. /// The length of the specified range by character. /// The size. /// Returns true if this operation succeeded. virtual bool SetSize(vint start, vint length, vint value)=0; /// Replace the text style within the specified range. /// The position of the first character of the specified range. /// The length of the specified range by character. /// The text style. /// Returns true if this operation succeeded. virtual bool SetStyle(vint start, vint length, TextStyle value)=0; /// Replace the color within the specified range. /// The position of the first character of the specified range. /// The length of the specified range by character. /// The color. /// Returns true if this operation succeeded. virtual bool SetColor(vint start, vint length, Color value)=0; /// Replace the background color within the specified range. /// The position of the first character of the specified range. /// The length of the specified range by character. /// The background color. /// Returns true if this operation succeeded. virtual bool SetBackgroundColor(vint start, vint length, Color value)=0; /// Bind an to a range of text. /// The position of the first character of the specified range. /// The length of the specified range by character. /// The properties for the inline object. /// Returns true if this operation succeeded. virtual bool SetInlineObject(vint start, vint length, const InlineObjectProperties& properties)=0; /// Unbind all inline objects to a range of text. /// The position of the first character of the specified range. /// The length of the specified range by character. /// Returns true if this operation succeeded. virtual bool ResetInlineObject(vint start, vint length)=0; /// Get the layouted height of the text. The result depends on rich styled text and the two important properties that can be set using and . /// The layouted height. virtual vint GetHeight()=0; /// Make the caret visible so that it will be rendered in the paragraph. /// Returns true if this operation succeeded. /// The caret. /// The color of the caret. /// Set to true to display the caret for the character before it. virtual bool OpenCaret(vint caret, Color color, bool frontSide)=0; /// Make the caret invisible. /// Returns true if this operation succeeded. virtual bool CloseCaret()=0; /// Render the graphics element using a specified bounds. /// Bounds to decide the size and position of the binded graphics element. virtual void Render(Rect bounds)=0; /// Get a new caret from the old caret with a relative position. /// The new caret. Returns -1 if failed. /// The caret to compare. If the position is CaretFirst or CaretLast, this argument is ignored. /// The relative position. /// Only for CaretMoveUp and CaretMoveDown. Set to true to make the caret prefer to get closer to the character before it. After this function is called, this argument stored the suggested side for displaying the new caret. virtual vint GetCaret(vint comparingCaret, CaretRelativePosition position, bool& preferFrontSide)=0; /// Get the bounds of the caret. /// The bounds whose width is 0. Returns an empty Rect value if failed. /// The caret. /// Set to true to get the bounds of the front side, otherwise the back side. If only one side is valid, this argument is ignored. virtual Rect GetCaretBounds(vint caret, bool frontSide)=0; /// Get the caret from a specified position. /// The caret. Returns -1 if failed. /// The point. virtual vint GetCaretFromPoint(Point point)=0; /// Get the inline object from a specified position. /// The inline object. Returns null if failed. /// The point. /// Get the start position of this element. /// Get the length of this element. virtual Nullable GetInlineObjectFromPoint(Point point, vint& start, vint& length)=0; /// Get the nearest caret from a text position. /// The caret. Returns -1 if failed. If the text position is a caret, then the result will be the text position itself without considering the frontSide argument. /// The caret to compare. If the position is CaretFirst or CaretLast, this argument is ignored. /// Set to true to search in front of the text position, otherwise the opposite position. virtual vint GetNearestCaretFromTextPos(vint textPos, bool frontSide)=0; /// Test is the caret valid. /// Returns true if the caret is valid. /// The caret to test. virtual bool IsValidCaret(vint caret)=0; /// Test is the text position valid. /// Returns true if the text position is valid. /// The text position to test. virtual bool IsValidTextPos(vint textPos)=0; }; /// Paragraph callback class IGuiGraphicsParagraphCallback : public IDescriptable, public Description { public: /// Called when an inline object with a valid callback id is being rendered. /// Returns the new size of the rendered inline object. /// The callback id of the inline object /// The location of the inline object, relative to the left-top corner of this paragraph. virtual Size OnRenderInlineObject(vint callbackId, Rect location) = 0; }; /// Renderer awared rich text document layout engine provider interface. class IGuiGraphicsLayoutProvider : public IDescriptable, public Description { public: /// Create a paragraph with internal renderer device dependent objects initialized. /// The text used to fill the paragraph. /// The render target that the created paragraph will render to. /// A callback to receive necessary information when the paragraph is being rendered. /// The created paragraph object. virtual Ptr CreateParagraph(const WString& text, IGuiGraphicsRenderTarget* renderTarget, IGuiGraphicsParagraphCallback* callback)=0; }; } } } #endif /*********************************************************************** .\NATIVEWINDOW\GUINATIVEWINDOW.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Native Window Interfaces: INativeController : Interface for Operating System abstraction Renderers: GUI_GRAPHICS_RENDERER_GDI GUI_GRAPHICS_RENDERER_DIRECT2D ***********************************************************************/ #ifndef VCZH_PRESENTATION_GUINATIVEWINDOW #define VCZH_PRESENTATION_GUINATIVEWINDOW namespace vl { namespace presentation { class GuiImageData; class DocumentModel; class INativeWindow; class INativeWindowListener; class INativeController; class INativeControllerListener; /*********************************************************************** System Object ***********************************************************************/ /// /// Represents a screen. /// class INativeScreen : public virtual IDescriptable, public Description { public: /// /// Get the bounds of the screen. /// /// The bounds of the screen. virtual NativeRect GetBounds()=0; /// /// Get the bounds of the screen client area. /// /// The bounds of the screen client area. virtual NativeRect GetClientBounds()=0; /// /// Get the name of the screen. /// /// The name of the screen. virtual WString GetName()=0; /// /// Test is the screen is a primary screen. /// /// Returns true if the screen is a primary screen. virtual bool IsPrimary()=0; /// /// Get the scaling for the screen's horizontal edge. /// /// The scaling. For example, in Windows when you have a 96 DPI, this function returns 1.0. virtual double GetScalingX() = 0; /// /// Get the scaling for the screen's vertical edge. /// /// The scaling. For example, in Windows when you have a 96 DPI, this function returns 1.0. virtual double GetScalingY() = 0; }; /// /// Represents a cursor. /// class INativeCursor : public virtual IDescriptable, public Description { public: /// /// Represents a predefined cursor type. /// enum SystemCursorType { /// /// Small waiting cursor. /// SmallWaiting, /// /// large waiting cursor. /// LargeWaiting, /// /// Arrow cursor. /// Arrow, /// /// Cross cursor. /// Cross, /// /// Hand cursor. /// Hand, /// /// Help cursor. /// Help, /// /// I beam cursor. /// IBeam, /// /// Sizing in all direction cursor. /// SizeAll, /// /// Sizing NE-SW cursor. /// SizeNESW, /// /// Sizing N-S cursor. /// SizeNS, /// /// Sizing NW-SE cursor. /// SizeNWSE, /// /// Sizing W-E cursor. /// SizeWE, /// /// Number of available cursors, this is not an available cursor by itself. /// LastSystemCursor=SizeWE, }; static const vint SystemCursorCount=LastSystemCursor+1; public: /// /// Test is the cursor a system provided cursor. /// /// Returns true if the cursor a system provided cursor. virtual bool IsSystemCursor()=0; /// /// Get the cursor type if the cursor a system provided cursor. /// /// The cursor type. virtual SystemCursorType GetSystemCursorType()=0; }; /*********************************************************************** Image Object ***********************************************************************/ class INativeImageService; class INativeImage; class INativeImageFrame; /// /// Represents a customized cache object for an image frame. /// class INativeImageFrameCache : public Interface { public: /// /// Called when this cache object is attached to an image frame. /// /// The image frame that attached to. virtual void OnAttach(INativeImageFrame* frame)=0; /// /// Called when this cache object is detached to an image frame. /// /// The image frame that detached from. virtual void OnDetach(INativeImageFrame* frame)=0; }; /// /// Represents an image frame. /// class INativeImageFrame : public virtual IDescriptable, public Description { public: /// /// Get the image that owns this frame. /// /// The image that owns this frame. virtual INativeImage* GetImage()=0; /// /// Get the size of this frame. /// /// The size of this frame. virtual Size GetSize()=0; /// /// Attach a customized cache object to this image frame and bind to a key. /// /// Returns true if this operation succeeded. /// The key binded with the customized cache object. /// The customized cache object. virtual bool SetCache(void* key, Ptr cache)=0; /// /// Get the attached customized cache object that is already binded to a key. /// /// The attached customized cache object. /// The key binded with the customized cache object. virtual Ptr GetCache(void* key)=0; /// /// Get the attached customized cache object that is already binded to a key, and then detach it. /// /// The detached customized cache object. /// The key binded with the customized cache object. virtual Ptr RemoveCache(void* key)=0; }; /// /// Represents an image. /// class INativeImage : public virtual IDescriptable, public Description { public: /// /// Represents an image format. /// enum FormatType { /// /// Bitmap format. /// Bmp, /// /// GIF format. /// Gif, /// /// Icon format. /// Icon, /// /// JPEG format. /// Jpeg, /// /// PNG format. /// Png, /// /// TIFF format. /// Tiff, /// /// WMP format. /// Wmp, /// /// Unknown format. /// Unknown, }; /// /// Get the image service that creates this image. /// /// The image service that creates this image. virtual INativeImageService* GetImageService()=0; /// /// Get the image format. /// /// The image format. virtual FormatType GetFormat()=0; /// /// Get the number of frames in this image. /// /// The number of frames in this image. virtual vint GetFrameCount()=0; /// /// Get the frame in this image by a specified frame index. /// /// The frame in this image by a specified frame index. /// The specified frame index. virtual INativeImageFrame* GetFrame(vint index)=0; /// /// Save the image to a stream. /// /// The stream. /// The format of the image. virtual void SaveToStream(stream::IStream& imageStream, FormatType formatType = FormatType::Unknown) = 0; }; /// /// Image service. To access this service, use [M:vl.presentation.INativeController.ImageService]. /// class INativeImageService : public virtual IDescriptable, public Description { public: /// /// Create an image from file. /// /// The created image. /// The file path. virtual Ptr CreateImageFromFile(const WString& path)=0; /// /// Create an image from memory. /// /// The created image. /// The memory pointer. /// The memory length. virtual Ptr CreateImageFromMemory(void* buffer, vint length)=0; /// /// Create an image from stream. /// /// The created image. /// The stream. virtual Ptr CreateImageFromStream(stream::IStream& imageStream)=0; }; /*********************************************************************** Native Window ***********************************************************************/ /// /// Represents a window. /// class INativeWindow : public Interface, public Description { public: /// /// Convert point from native coordinate to GUI coordinate. /// /// The converted result. /// The coordinate to convert. virtual Point Convert(NativePoint value) = 0; /// /// Convert point from GUI coordinate to native coordinate. /// /// The converted result. /// The coordinate to convert. virtual NativePoint Convert(Point value) = 0; /// /// Convert size from native coordinate to GUI coordinate. /// /// The converted result. /// The coordinate to convert. virtual Size Convert(NativeSize value) = 0; /// /// Convert size from GUI coordinate to native coordinate. /// /// The converted result. /// The coordinate to convert. virtual NativeSize Convert(Size value) = 0; /// /// Convert margin from native coordinate to GUI coordinate. /// /// The converted result. /// The coordinate to convert. virtual Margin Convert(NativeMargin value) = 0; /// /// Convert margin from GUI coordinate to native coordinate. /// /// The converted result. /// The coordinate to convert. virtual NativeMargin Convert(Margin value) = 0; /// /// Get the bounds of the window. /// /// The bounds of the window. virtual NativeRect GetBounds()=0; /// /// Set the bounds of the window. /// /// The bounds of the window. virtual void SetBounds(const NativeRect& bounds)=0; /// /// Get the client size of the window. /// /// The client size of the window. virtual NativeSize GetClientSize()=0; /// /// Set the client size of the window. /// /// The client size of the window. virtual void SetClientSize(NativeSize size)=0; /// /// Get the client bounds in screen space. /// /// The client bounds in screen space. virtual NativeRect GetClientBoundsInScreen()=0; /// /// Get the title of the window. A title will be displayed as a name of this window. /// /// The title of the window. virtual WString GetTitle()=0; /// /// Set the title of the window. A title will be displayed as a name of this window. /// /// The title of the window. virtual void SetTitle(WString title)=0; /// /// Get the mouse cursor of the window. When the mouse is on the window, the mouse cursor will be rendered. /// /// The mouse cursor of the window. virtual INativeCursor* GetWindowCursor()=0; /// /// Set the mouse cursor of the window. When the mouse is on the window, the mouse cursor will be rendered. /// /// The mouse cursor of the window. virtual void SetWindowCursor(INativeCursor* cursor)=0; /// /// Get the caret point of the window. When an input method editor is opened, the input text box will be located to the caret point. /// /// The caret point of the window. virtual NativePoint GetCaretPoint()=0; /// /// Set the caret point of the window. When an input method editor is opened, the input text box will be located to the caret point. /// /// The caret point of the window. virtual void SetCaretPoint(NativePoint point)=0; /// /// Get the parent window. /// A parent window doesn't contain a child window. It always displayed below the child windows. When a parent window is minimized or restored, so as its child windows. /// /// The parent window. virtual INativeWindow* GetParent()=0; /// /// Set the parent window. A parent window doesn't contain a child window. It always displayed below the child windows. When a parent window is minimized or restored, so as its child windows. /// /// The parent window. virtual void SetParent(INativeWindow* parent)=0; /// /// Window mode /// enum WindowMode { /// /// A normal window. /// Normal, /// /// A tooltip window. /// Such window is expected to be disabled activation, [M:vl.presentation.INativeWindow.DisableActivate] must be called manually. /// Such window is expected to have a parent window, [M:vl.presentation.INativeWindow.SetParent] must be called before [M:vl.presentation.INativeWindow.ShowDeactivated]. /// This window is automatically closed when the top level window is deactivated or clicked. /// Tooltip, /// /// A popup window. /// Such window is expected to be disabled activation, [M:vl.presentation.INativeWindow.DisableActivate] must be called manually. /// Such window is expected to have a parent window, [M:vl.presentation.INativeWindow.SetParent] must be called before [M:vl.presentation.INativeWindow.ShowDeactivated]. /// This window is automatically closed when the top level window is deactivated or clicked. /// Popup, /// /// A menu window. /// Such window is expected to be disabled activation, [M:vl.presentation.INativeWindow.DisableActivate] must be called manually. /// Such window is expected to have a parent window, [M:vl.presentation.INativeWindow.SetParent] must be called before [M:vl.presentation.INativeWindow.ShowDeactivated]. /// This window is automatically closed when the top level window is deactivated or clicked. /// Menu, }; /// /// Get the window mode. /// /// The window mode. virtual WindowMode GetWindowMode() = 0; /// /// Enable the window customized frame mode. /// virtual void EnableCustomFrameMode()=0; /// /// Disable the window customized frame mode. /// virtual void DisableCustomFrameMode()=0; /// /// Test is the window customized frame mode enabled. /// /// Returns true if the window customized frame mode is enabled. virtual bool IsCustomFrameModeEnabled()=0; /// /// Get the amount of the border. The window template may need this value to calculate where to put the client area. /// /// Returns the amount of the border. virtual NativeMargin GetCustomFramePadding() = 0; /// Window size state. enum WindowSizeState { /// Minimized. Minimized, /// Restored. Restored, /// Maximized. Maximized, }; /// /// Get the icon. /// /// Returns the icon. virtual Ptr GetIcon()=0; /// /// Set the icon. /// /// The icon. Set to null to use the default icon. virtual void SetIcon(Ptr icon)=0; /// /// Get the window size state. /// /// Returns the window size state. virtual WindowSizeState GetSizeState()=0; /// /// Show the window. /// If the window disabled activation, this function enables it again. /// virtual void Show()=0; /// /// Show the window without activation. /// virtual void ShowDeactivated()=0; /// /// Restore the window. /// virtual void ShowRestored()=0; /// /// Maximize the window. /// virtual void ShowMaximized()=0; /// /// Minimize the window. /// virtual void ShowMinimized()=0; /// /// Hide the window. /// /// Set to true to really close the window. Or the window will just be hidden. This parameter only affect the main window. virtual void Hide(bool closeWindow)=0; /// /// Test is the window visible. /// /// Returns true if the window is visible. virtual bool IsVisible()=0; /// /// Enable the window. /// virtual void Enable()=0; /// /// Disable the window. /// virtual void Disable()=0; /// /// Test is the window enabled. /// /// Returns true if the window is enabled. virtual bool IsEnabled()=0; /// /// Set focus to the window. /// A window with activation disabled cannot receive focus. /// virtual void SetFocus()=0; /// /// Test is the window focused. /// /// Returns true if the window is focused. virtual bool IsFocused()=0; /// /// Activate to the window. /// If the window disabled activation, this function enables it again. /// virtual void SetActivate()=0; /// /// Test is the window activated. /// /// Returns true if the window is activated. virtual bool IsActivated()=0; /// /// Show the icon in the task bar. /// virtual void ShowInTaskBar()=0; /// /// Hide the icon in the task bar. /// virtual void HideInTaskBar()=0; /// /// Test is the window icon appeared in the task bar. /// /// Returns true if the window icon appears in the task bar. virtual bool IsAppearedInTaskBar()=0; /// /// Enable activation to the window. /// virtual void EnableActivate()=0; /// /// Disable activation to the window. /// Clicking a window with activation disabled doesn't bring activation and focus. /// Activation will be automatically enabled by calling or . /// virtual void DisableActivate()=0; /// /// Test is the window allowed to be activated. /// /// Returns true if the window is allowed to be activated. virtual bool IsEnabledActivate()=0; /// /// Require mouse message capturing to this window. If the capture is required, all mouse message will be send to this window. /// When the window becomes invisible after calling this function, the window will still receive mouse messages, if the OS supports this feature. /// Otherwise, the capturing must be released when the window becomes invisible. /// /// Returns true if this operation succeeded. virtual bool RequireCapture()=0; /// /// Release mouse message capturing to this window. If the capture is required, all mouse message will be send to this window. /// /// Returns true if this operation succeeded. virtual bool ReleaseCapture()=0; /// /// Test if the window is capturing mouse messages. /// /// Returns true if the window is capturing mouse messages. virtual bool IsCapturing()=0; /// /// Test is the maximize box visible. /// /// Returns true if the maximize box is visible. virtual bool GetMaximizedBox()=0; /// /// Make the maximize box visible or invisible. /// /// True to make the maximize box visible. virtual void SetMaximizedBox(bool visible)=0; /// /// Test is the minimize box visible. /// /// Returns true if the minimize box is visible. virtual bool GetMinimizedBox()=0; /// /// Make the minimize box visible or invisible. /// /// True to make the minimize box visible. virtual void SetMinimizedBox(bool visible)=0; /// /// Test is the border visible. /// /// Returns true if the border is visible. virtual bool GetBorder()=0; /// /// Make the border visible or invisible. /// /// True to make the border visible. virtual void SetBorder(bool visible)=0; /// /// Test is the size box visible. /// /// Returns true if the size box is visible. virtual bool GetSizeBox()=0; /// /// Make the size box visible or invisible. /// /// True to make the size box visible. virtual void SetSizeBox(bool visible)=0; /// /// Test is the icon visible. /// /// Returns true if the icon is visible. virtual bool GetIconVisible()=0; /// /// Make the icon visible or invisible. /// /// True to make the icon visible. virtual void SetIconVisible(bool visible)=0; /// /// Test is the title bar visible. /// /// Returns true if the title bar is visible. virtual bool GetTitleBar()=0; /// /// Make the title bar visible or invisible. /// /// True to make the title bar visible. virtual void SetTitleBar(bool visible)=0; /// /// Test is the window always on top of the desktop. /// /// Returns true if the window is always on top of the desktop. virtual bool GetTopMost()=0; /// /// Make the window always or never on top of the desktop. /// /// True to make the window always on top of the desktop. virtual void SetTopMost(bool topmost)=0; /// /// Supress the system's Alt+X hot key /// virtual void SupressAlt() = 0; /// /// Install an message listener. /// /// Returns true if this operation succeeded. /// The listener to install. virtual bool InstallListener(INativeWindowListener* listener)=0; /// /// Uninstall an message listener. /// /// Returns true if this operation succeeded. /// The listener to uninstall. virtual bool UninstallListener(INativeWindowListener* listener)=0; /// /// Redraw the content of the window. /// virtual void RedrawContent()=0; }; /// /// Mouse message information. /// /// Type of the coordinate. template struct WindowMouseInfo_ { /// True if the control button is pressed. bool ctrl; /// True if the shift button is pressed. bool shift; /// True if the left mouse button is pressed. bool left; /// True if the middle mouse button is pressed. bool middle; /// True if the right mouse button is pressed. bool right; /// The mouse position of x dimension. T x; /// The mouse position of y dimension. T y; /// The delta of the wheel. vint wheel; /// True if the mouse is in the non-client area. bool nonClient; }; using WindowMouseInfo = WindowMouseInfo_; using NativeWindowMouseInfo = WindowMouseInfo_; /// /// Key message information. /// struct NativeWindowKeyInfo { /// Key code of the key that sends this message. VKEY code; /// True if the control button is pressed. bool ctrl; /// True if the shift button is pressed. bool shift; /// True if the alt button is pressed. bool alt; /// True if the capslock button is pressed. bool capslock; /// True if this repeated event is generated because a key is holding down. bool autoRepeatKeyDown; }; using WindowKeyInfo = NativeWindowKeyInfo; /// /// Character message information. /// struct NativeWindowCharInfo { /// Character that sends this message. wchar_t code; /// True if the control button is pressed. bool ctrl; /// True if the shift button is pressed. bool shift; /// True if the alt button is pressed. bool alt; /// True if the capslock button is pressed. bool capslock; }; using WindowCharInfo = NativeWindowCharInfo; /// /// Represents a message listener to an . /// class INativeWindowListener : public Interface { public: /// Hit test result for a native window. enum HitTestResult { /// Border that doesn't contain sizing functionalitiy. BorderNoSizing, /// Left border. BorderLeft, /// Right border. BorderRight, /// Top border. BorderTop, /// Bottom border. BorderBottom, /// Left top border. BorderLeftTop, /// Right top border. BorderRightTop, /// Left bottom border. BorderLeftBottom, /// Right bottom border. BorderRightBottom, /// Title Title, /// Minimum button. ButtonMinimum, /// Maximum button. ButtonMaximum, /// Close button. ButtonClose, /// Client button. Client, /// Icon. Icon, /// Let the OS window layer decide. NoDecision, }; /// /// Perform a hit test. /// /// Returns the hit test result. If "NoDecision" is returned, the native window provider should call the OS window layer to do the hit test. /// The location to do the hit test. This location is in the window space (not the client space). virtual HitTestResult HitTest(NativePoint location); /// /// Called when the window is moving. /// /// The bounds. Message handler can change the bounds. /// True if the message raise only want the message handler to change the size, and keep the position unchanged. /// True if the message raise because the user is dragging the border to change the size. virtual void Moving(NativeRect& bounds, bool fixSizeOnly, bool draggingBorder); /// /// Called when the window is moved. /// virtual void Moved(); /// /// Called when the dpi associated with this window is changed. /// virtual void DpiChanged(); /// /// Called when the window is enabled. /// virtual void Enabled(); /// /// Called when the window is disabled. /// virtual void Disabled(); /// /// Called when the window got the focus. /// virtual void GotFocus(); /// /// Called when the window lost the focus. /// virtual void LostFocus(); /// /// Called when the window is activated. /// virtual void Activated(); /// /// Called when the window is deactivated. /// virtual void Deactivated(); /// /// Called when the window is opened. /// virtual void Opened(); /// /// Called when the window is closing. /// /// Change the value to true to prevent the windows from being closed. virtual void Closing(bool& cancel); /// /// Called when the window is closed. /// virtual void Closed(); /// /// Called when the window is painting. /// virtual void Paint(); /// /// Called when the window is destroying. /// virtual void Destroying(); /// /// Called when the window is destroyed. /// virtual void Destroyed(); /// /// Called when the left mouse button is pressed. /// /// Detailed information to this message. virtual void LeftButtonDown(const NativeWindowMouseInfo& info); /// /// Called when the left mouse button is released. /// /// Detailed information to this message. virtual void LeftButtonUp(const NativeWindowMouseInfo& info); /// /// Called when the left mouse button performed a double click. /// /// Detailed information to this message. virtual void LeftButtonDoubleClick(const NativeWindowMouseInfo& info); /// /// Called when the right mouse button is pressed. /// /// Detailed information to this message. virtual void RightButtonDown(const NativeWindowMouseInfo& info); /// /// Called when the right mouse button is released. /// /// Detailed information to this message. virtual void RightButtonUp(const NativeWindowMouseInfo& info); /// /// Called when the right mouse button performed a double click. /// /// Detailed information to this message. virtual void RightButtonDoubleClick(const NativeWindowMouseInfo& info); /// /// Called when the middle mouse button is pressed. /// /// Detailed information to this message. virtual void MiddleButtonDown(const NativeWindowMouseInfo& info); /// /// Called when the middle mouse button is released. /// /// Detailed information to this message. virtual void MiddleButtonUp(const NativeWindowMouseInfo& info); /// /// Called when the middle mouse button performed a double click. /// /// Detailed information to this message. virtual void MiddleButtonDoubleClick(const NativeWindowMouseInfo& info); /// /// Called when the horizontal mouse wheel scrolls. /// /// Detailed information to this message. virtual void HorizontalWheel(const NativeWindowMouseInfo& info); /// /// Called when the horizontal vertical wheel scrolls. /// /// Detailed information to this message. virtual void VerticalWheel(const NativeWindowMouseInfo& info); /// /// Called when the mouse is moving on the window. /// /// Detailed information to this message. virtual void MouseMoving(const NativeWindowMouseInfo& info); /// /// Called when the mouse entered the window. /// virtual void MouseEntered(); /// /// Called when the mouse leaved the window. /// virtual void MouseLeaved(); /// /// Called a key is pressed. /// /// Detailed information to this message. virtual void KeyDown(const NativeWindowKeyInfo& info); /// /// Called a key is released. /// /// Detailed information to this message. virtual void KeyUp(const NativeWindowKeyInfo& info); /// /// Called a system key is pressed. /// /// Detailed information to this message. virtual void SysKeyDown(const NativeWindowKeyInfo& info); /// /// Called a system key is released. /// /// Detailed information to this message. virtual void SysKeyUp(const NativeWindowKeyInfo& info); /// /// Called an input character is generated. /// /// Detailed information to this message. virtual void Char(const NativeWindowCharInfo& info); }; /*********************************************************************** Native Window Services ***********************************************************************/ /// /// System resource service. To access this service, use [M:vl.presentation.INativeController.ResourceService]. /// class INativeResourceService : public virtual IDescriptable, public Description { public: /// /// Get a cached cursor object using a predefined system cursor type; /// /// The cached cursor object. /// The predefined system cursor type. virtual INativeCursor* GetSystemCursor(INativeCursor::SystemCursorType type)=0; /// /// Get a cached cursor object using a default system cursor type; /// /// The cached cursor object. virtual INativeCursor* GetDefaultSystemCursor()=0; /// /// Get the default font configuration of the system. /// /// The default font configuration of the system. virtual FontProperties GetDefaultFont()=0; /// /// Override the default font configuration for the current process, only available GacUI library. /// /// The font configuration to override. virtual void SetDefaultFont(const FontProperties& value)=0; }; /// /// Delay execution controller. /// class INativeDelay : public virtual IDescriptable, public Description { public: /// Delay execution controller status. enum ExecuteStatus { /// Pending. Pending, /// Executing. Executing, /// Executed. Executed, /// Canceled. Canceled, }; /// Get the current status. /// The current status. virtual ExecuteStatus GetStatus()=0; /// If the current task is pending, execute the task after a specified period. /// Returns true if this operation succeeded. /// A specified period. virtual bool Delay(vint milliseconds)=0; /// If the current task is pending, cancel the task. /// Returns true if this operation succeeded. virtual bool Cancel()=0; }; /// /// Asynchronized operation service. GacUI is not a thread safe library except for this service. To access this service, use [M:vl.presentation.INativeController.AsyncService]. /// class INativeAsyncService : public virtual IDescriptable, public Description { public: /// /// Test is the current thread the main thread. /// /// Returns true if the current thread is the main thread. /// A window to access the corressponding main thread. virtual bool IsInMainThread(INativeWindow* window)=0; /// /// Invoke a specified function with an specified argument asynchronisly. /// /// The specified function. virtual void InvokeAsync(const Func& proc)=0; /// /// Invoke a specified function with an specified argument in the main thread. /// /// A window to access the corressponding main thread. /// The specified function. virtual void InvokeInMainThread(INativeWindow* window, const Func& proc)=0; /// /// Invoke a specified function with an specified argument in the main thread and wait for the function to complete or timeout. /// /// Return true if the function complete. Return false if the function has not completed during a specified period of time. /// A window to access the corressponding main thread. /// The specified function. /// The specified period of time to wait. Set to -1 (default value) to wait forever until the function completed. virtual bool InvokeInMainThreadAndWait(INativeWindow* window, const Func& proc, vint milliseconds=-1)=0; /// /// Delay execute a specified function with an specified argument asynchronisly. /// /// The Delay execution controller for this task. /// The specified function. /// Time to delay. virtual Ptr DelayExecute(const Func& proc, vint milliseconds)=0; /// /// Delay execute a specified function with an specified argument in the main thread. /// /// The Delay execution controller for this task. /// The specified function. /// Time to delay. virtual Ptr DelayExecuteInMainThread(const Func& proc, vint milliseconds)=0; }; /// /// Clipboard reader. /// class INativeClipboardReader : public virtual IDescriptable, public Description { public: /// Test is there a text in the clipboard. /// Returns true if there is a text in the clipboard. virtual bool ContainsText() = 0; /// Get the text from the clipboard. /// The text. virtual WString GetText() = 0; /// Test is there a document in the clipboard. /// Returns true if there is a document in the clipboard. virtual bool ContainsDocument() = 0; /// Get the document from the clipboard. /// The document. virtual Ptr GetDocument() = 0; /// Test is there an image in the clipboard. /// Returns true if there is an image in the clipboard. virtual bool ContainsImage() = 0; /// Get the image from the clipboard. /// The image. virtual Ptr GetImage() = 0; }; /// /// Clipboard writer. /// class INativeClipboardWriter : public virtual IDescriptable, public Description { public: /// Prepare a text for the clipboard. /// The text. virtual void SetText(const WString& value) = 0; /// Prepare a document for the clipboard. /// The document. virtual void SetDocument(Ptr value) = 0; /// Prepare an image for the clipboard. /// The image. virtual void SetImage(Ptr value) = 0; /// Send all data to the clipboard. /// Returns true if this operation succeeded. virtual bool Submit() = 0; }; /// /// Clipboard service. To access this service, use [M:vl.presentation.INativeController.ClipboardService]. /// class INativeClipboardService : public virtual IDescriptable, public Description { public: /// Read clipboard. /// The clipboard reader. virtual Ptr ReadClipboard() = 0; /// Write clipboard. /// The clipboard writer. virtual Ptr WriteClipboard() = 0; }; /// /// Screen information service. To access this service, use [M:vl.presentation.INativeController.ScreenService]. /// class INativeScreenService : public virtual IDescriptable, public Description { public: /// /// Get the number of all available screens. /// /// The number of all available screens. virtual vint GetScreenCount()=0; /// /// Get the screen object by a specified screen index. /// /// The screen object. /// The specified screen index. virtual INativeScreen* GetScreen(vint index)=0; /// /// Get the screen object where the main part of the specified window is inside. /// /// The screen object. /// The specified window. virtual INativeScreen* GetScreen(INativeWindow* window)=0; }; /// /// Window service. To access this service, use [M:vl.presentation.INativeController.WindowService]. /// class INativeWindowService : public virtual Interface { public: /// /// Create a window. /// /// The created window. /// The window mode. virtual INativeWindow* CreateNativeWindow(INativeWindow::WindowMode windowMode) = 0; /// /// Destroy a window. /// /// The window to destroy. virtual void DestroyNativeWindow(INativeWindow* window) = 0; /// /// Get the main window. /// /// The main window. virtual INativeWindow* GetMainWindow() = 0; /// /// Get the window that under a specified position in screen space. /// /// The window that under a specified position in screen space. /// The specified position in screen space. virtual INativeWindow* GetWindow(NativePoint location) = 0; /// /// Make the specified window a main window, show that window, and wait until the windows is closed. /// /// The specified window. virtual void Run(INativeWindow* window) = 0; }; /// /// User input service. To access this service, use [M:vl.presentation.INativeController.InputService]. /// class INativeInputService : public virtual IDescriptable, public Description { public: /// /// Start to reveive global timer message. /// virtual void StartTimer()=0; /// /// Stop to receive global timer message. /// virtual void StopTimer()=0; /// /// Test is the global timer message receiving enabled. /// /// Returns true if the global timer message receiving is enabled. virtual bool IsTimerEnabled()=0; /// /// Test is the specified key pressing. /// /// Returns true if the specified key is pressing. /// The key code to test. virtual bool IsKeyPressing(VKEY code)=0; /// /// Test is the specified key toggled. /// /// Returns true if the specified key is toggled. /// The key code to test. virtual bool IsKeyToggled(VKEY code)=0; /// /// Get the name of a key. /// /// The name of a key. /// The key code. virtual WString GetKeyName(VKEY code)=0; /// /// Get the key from a name. /// /// The key, returns -1 if the key name doesn't exist. /// Key name virtual VKEY GetKey(const WString& name)=0; }; /// /// Callback service. To access this service, use [M:vl.presentation.INativeController.CallbackService]. /// class INativeCallbackService : public virtual Interface { public: /// /// Install a global message listener. /// /// Returns true if this operation succeeded. /// The global message listener to install. virtual bool InstallListener(INativeControllerListener* listener)=0; /// /// Uninstall a global message listener. /// /// Returns true if this operation succeeded. /// The global message listener to uninstall. virtual bool UninstallListener(INativeControllerListener* listener)=0; }; /// /// Dialog service. To access this service, use [M:vl.presentation.INativeController.DialogService]. /// class INativeDialogService : public virtual Interface { public: /// /// Message box button combination for displaying a message box. /// enum MessageBoxButtonsInput { /// Display OK. DisplayOK, /// Display OK, Cancel. DisplayOKCancel, /// Display Yes, No. DisplayYesNo, /// Display Yes, No, Cancel. DisplayYesNoCancel, /// Display Retry, Cancel. DisplayRetryCancel, /// Display Abort, Retry, Ignore. DisplayAbortRetryIgnore, /// Display Cancel, TryAgain, Continue. DisplayCancelTryAgainContinue, }; /// /// Message box button to indicate what the user selected. /// enum MessageBoxButtonsOutput { /// Select OK. SelectOK, /// Select Cancel. SelectCancel, /// Select Yes. SelectYes, /// Select No. SelectNo, /// Select Retry. SelectRetry, /// Select Abort. SelectAbort, /// Select Ignore. SelectIgnore, /// Select TryAgain. SelectTryAgain, /// Select Continue. SelectContinue, }; /// /// Message box default button. /// enum MessageBoxDefaultButton { /// First. DefaultFirst, /// Second. DefaultSecond, /// Third. DefaultThird, }; /// /// Message box icons. /// enum MessageBoxIcons { /// No icon. IconNone, /// Error icon. IconError, /// Question icon. IconQuestion, /// Warning icon. IconWarning, /// Information icon. IconInformation, }; /// /// Message box model options. /// enum MessageBoxModalOptions { /// Disable the current window. ModalWindow, /// Disable all windows in the application. ModalTask, /// Top most message box in the whole system. ModalSystem, }; /// Show a message box. /// Returns the user selected button. /// The current window. This argument can be null. /// The content of the message box. /// The title of the message box. /// The display button combination of the message box. /// The default button of the message box. /// The icon of the message box. /// The modal option of the message box. virtual MessageBoxButtonsOutput ShowMessageBox(INativeWindow* window, const WString& text, const WString& title=L"", MessageBoxButtonsInput buttons=DisplayOK, MessageBoxDefaultButton defaultButton=DefaultFirst, MessageBoxIcons icon=IconNone, MessageBoxModalOptions modal=ModalWindow)=0; /// /// Color dialog custom color options /// enum ColorDialogCustomColorOptions { /// Disable the custom color panel. CustomColorDisabled, /// Enable the custom color panel. CustomColorEnabled, /// Open the custom color panel at the beginning. CustomColorOpened, }; /// Show a color dialog. /// Returns true if the user selected the OK button. /// The current window. /// The color that the user selected. /// Make the color dialog selected the color specified in the "selection" parameter at the beginning. /// Custom color panel options. /// The initial 16 colors in custom color boxes. This argument can be null. virtual bool ShowColorDialog(INativeWindow* window, Color& selection, bool selected=false, ColorDialogCustomColorOptions customColorOptions=CustomColorEnabled, Color* customColors=0)=0; /// Show a font dialog. /// Returns true if the user selected the OK button. /// The current window. /// The font that the user selected. /// The color that the user selected. /// Make the font dialog selected the font specified in the "selectionFont" and "selectionColor" parameters at the beginning. /// Enable the user to edit some extended font properties. /// Force the user to select existing font. virtual bool ShowFontDialog(INativeWindow* window, FontProperties& selectionFont, Color& selectionColor, bool selected=false, bool showEffect=true, bool forceFontExist=true)=0; /// /// File dialog type. /// enum FileDialogTypes { /// Open file dialog. FileDialogOpen, /// Open file dialog with preview. FileDialogOpenPreview, /// Save file dialog. FileDialogSave, /// Save file dialog with preview. FileDialogSavePreview, }; /// /// File dialog options. /// enum FileDialogOptions { /// Allow multiple selection. FileDialogAllowMultipleSelection = 1, /// Prevent the user to select unexisting files. FileDialogFileMustExist = 2, /// Show the "Read Only" check box. FileDialogShowReadOnlyCheckBox = 4, /// Dereference link files. FileDialogDereferenceLinks = 8, /// Show the "Network" button. FileDialogShowNetworkButton = 16, /// Prompt if a new file is going to be created. FileDialogPromptCreateFile = 32, /// Promt if a existing file is going to be overwritten. FileDialogPromptOverwriteFile = 64, /// Prevent the user to select an unexisting directory. FileDialogDirectoryMustExist = 128, /// Add user selected files to "Recent" directory. FileDialogAddToRecent = 256, }; /// Show a file dialog. /// Returns true if the user selected the OK button. /// The current window. /// The file names that the user selected. /// The filter that the user selected. /// The type of the file dialog. /// The title of the file dialog. /// The initial file name. /// The initial directory. /// The default file extension. /// The file name filter like L"Text Files|*.txt|All Files|*.*". /// File dialog options. Multiple options can be combined using the "|" operator. virtual bool ShowFileDialog(INativeWindow* window, collections::List& selectionFileNames, vint& selectionFilterIndex, FileDialogTypes dialogType, const WString& title, const WString& initialFileName, const WString& initialDirectory, const WString& defaultExtension, const WString& filter, FileDialogOptions options)=0; }; inline INativeDialogService::FileDialogOptions operator|(INativeDialogService::FileDialogOptions a, INativeDialogService::FileDialogOptions b) { return static_cast(static_cast(a) | static_cast(b)); } inline INativeDialogService::FileDialogOptions operator&(INativeDialogService::FileDialogOptions a, INativeDialogService::FileDialogOptions b) { return static_cast(static_cast(a) & static_cast(b)); } /*********************************************************************** Native Window Controller ***********************************************************************/ /// /// Global native system service controller. Use [M:vl.presentation.GetCurrentController] to access this controller. /// class INativeController : public virtual IDescriptable, public Description { public: /// /// Get the callback service. /// /// The callback service virtual INativeCallbackService* CallbackService()=0; /// /// Get the system resource service. /// /// The system resource service virtual INativeResourceService* ResourceService()=0; /// /// Get the asynchronized operation service. /// /// The asynchronized operation service virtual INativeAsyncService* AsyncService()=0; /// /// Get the clipboard service. /// /// The clipboard service virtual INativeClipboardService* ClipboardService()=0; /// /// Get the image service. /// /// The image service virtual INativeImageService* ImageService()=0; /// /// Get the screen information service. /// /// The screen information service virtual INativeScreenService* ScreenService()=0; /// /// Get the window service. /// /// The window service virtual INativeWindowService* WindowService()=0; /// /// Get the user input service. /// /// The user input service virtual INativeInputService* InputService()=0; /// /// Get the dialog service. /// /// The user dialog service virtual INativeDialogService* DialogService()=0; /// /// Get the file path of the current executable. /// /// The file path of the current executable. virtual WString GetExecutablePath()=0; }; /// /// Represents a global message listener to an . /// class INativeControllerListener : public Interface { public: /// /// Called when the global timer message raised. To receive or not receive this message, use or /// virtual void GlobalTimer(); /// /// Called when the content of the clipboard is updated. /// virtual void ClipboardUpdated(); /// /// Called when a window is created. /// /// The created window. virtual void NativeWindowCreated(INativeWindow* window); /// /// Called when a window is destroying. /// /// The destroying window. virtual void NativeWindowDestroying(INativeWindow* window); }; /// /// Get the global native system service controller. /// /// The global native system service controller. extern INativeController* GetCurrentController(); /// /// Set the global native system service controller. /// /// The global native system service controller. extern void SetCurrentController(INativeController* controller); } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSEVENTRECEIVER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Event Model Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSEVENTRECEIVER #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSEVENTRECEIVER namespace vl { namespace presentation { namespace controls { namespace tree { class INodeProvider; } } } } namespace vl { namespace presentation { namespace compositions { class GuiGraphicsComposition; /*********************************************************************** Event ***********************************************************************/ class IGuiGraphicsEventHandler : public virtual IDescriptable, public Description { public: class Container { public: Ptr handler; }; virtual bool IsAttached() = 0; }; template class GuiGraphicsEvent : public Object, public Description> { public: typedef void(RawFunctionType)(GuiGraphicsComposition*, T&); typedef Func FunctionType; typedef T ArgumentType; class FunctionHandler : public Object, public IGuiGraphicsEventHandler { public: bool isAttached = true; FunctionType handler; FunctionHandler(const FunctionType& _handler) :handler(_handler) { } bool IsAttached()override { return isAttached; } void Execute(GuiGraphicsComposition* sender, T& argument) { handler(sender, argument); } }; protected: struct HandlerNode { Ptr handler; Ptr next; }; GuiGraphicsComposition* sender; Ptr handlers; bool Attach(Ptr handler) { Ptr* currentHandler = &handlers; while (*currentHandler) { if ((*currentHandler)->handler == handler) { return false; } else { currentHandler = &(*currentHandler)->next; } } (*currentHandler) = new HandlerNode; (*currentHandler)->handler = handler; return true; } public: GuiGraphicsEvent(GuiGraphicsComposition* _sender=0) :sender(_sender) { } ~GuiGraphicsEvent() { } GuiGraphicsComposition* GetAssociatedComposition() { return sender; } void SetAssociatedComposition(GuiGraphicsComposition* _sender) { sender=_sender; } template Ptr AttachMethod(TClass* receiver, TMethod TClass::* method) { auto handler=MakePtr(FunctionType(receiver, method)); Attach(handler); return handler; } Ptr AttachFunction(RawFunctionType* function) { auto handler = MakePtr(FunctionType(function)); Attach(handler); return handler; } Ptr AttachFunction(const FunctionType& function) { auto handler = MakePtr(function); Attach(handler); return handler; } template Ptr AttachLambda(const TLambda& lambda) { auto handler = MakePtr(FunctionType(lambda)); Attach(handler); return handler; } bool Detach(Ptr handler) { auto typedHandler = handler.Cast(); if (!typedHandler) { return false; } auto currentHandler=&handlers; while(*currentHandler) { if((*currentHandler)->handler == typedHandler) { (*currentHandler)->handler->isAttached = false; auto next=(*currentHandler)->next; (*currentHandler)=next; return true; } else { currentHandler=&(*currentHandler)->next; } } return false; } void ExecuteWithNewSender(T& argument, GuiGraphicsComposition* newSender) { auto currentHandler=&handlers; while(*currentHandler) { (*currentHandler)->handler->Execute(newSender?newSender:sender, argument); currentHandler=&(*currentHandler)->next; } } void Execute(T& argument) { ExecuteWithNewSender(argument, 0); } void Execute(const T& argument) { auto t = argument; ExecuteWithNewSender(t, 0); } }; /*********************************************************************** Predefined Events ***********************************************************************/ /// Notify event arguments. struct GuiEventArgs : public Object, public AggregatableDescription { /// The event raiser composition. GuiGraphicsComposition* compositionSource; /// The nearest parent of the event raiser composition that contains an event receiver. If the event raiser composition contains an event receiver, it will be the event raiser composition. GuiGraphicsComposition* eventSource; /// Set this field to true will stop the event routing. This is a signal that the event is properly handeled, and the event handler want to override the default behavior. bool handled; /// Create an event arguments with and set to null. GuiEventArgs() :compositionSource(0) ,eventSource(0) ,handled(false) { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiEventArgs(GuiGraphicsComposition* composition) :compositionSource(composition) ,eventSource(composition) ,handled(false) { } ~GuiEventArgs() { FinalizeAggregation(); } }; /// Request event arguments. struct GuiRequestEventArgs : public GuiEventArgs, public Description { /// Set this field to false in event handlers will stop the corresponding action. bool cancel; /// Create an event arguments with and set to null. GuiRequestEventArgs() :cancel(false) { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiRequestEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,cancel(false) { } }; /// Keyboard event arguments. struct GuiKeyEventArgs : public GuiEventArgs, public WindowKeyInfo, public Description { /// Create an event arguments with and set to null. GuiKeyEventArgs() { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiKeyEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; /// Char input event arguments. struct GuiCharEventArgs : public GuiEventArgs, public WindowCharInfo, public Description { /// Create an event arguments with and set to null. GuiCharEventArgs() { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiCharEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; /// Mouse event arguments. struct GuiMouseEventArgs : public GuiEventArgs, public WindowMouseInfo, public Description { /// Create an event arguments with and set to null. GuiMouseEventArgs() { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiMouseEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; /// Control signal. enum class ControlSignal { /// Render target changed. RenderTargetChanged, /// Render target changed. ParentLineChanged, /// Service added changed. ServiceAdded, }; /// Control signal event arguments. struct GuiControlSignalEventArgs : public GuiEventArgs, public Description { /// The event raiser composition. ControlSignal controlSignal = ControlSignal::ParentLineChanged; /// Create an event arguments with and set to null. GuiControlSignalEventArgs() { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiControlSignalEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; typedef GuiGraphicsEvent GuiNotifyEvent; typedef GuiGraphicsEvent GuiRequestEvent; typedef GuiGraphicsEvent GuiKeyEvent; typedef GuiGraphicsEvent GuiCharEvent; typedef GuiGraphicsEvent GuiMouseEvent; typedef GuiGraphicsEvent GuiControlSignalEvent; /*********************************************************************** Predefined Item Events ***********************************************************************/ /// Item event arguments. struct GuiItemEventArgs : public GuiEventArgs, public Description { /// Item index. vint itemIndex; GuiItemEventArgs() :itemIndex(-1) { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiItemEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,itemIndex(-1) { } }; /// Item mouse event arguments. struct GuiItemMouseEventArgs : public GuiMouseEventArgs, public Description { /// Item index. vint itemIndex; GuiItemMouseEventArgs() :itemIndex(-1) { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiItemMouseEventArgs(GuiGraphicsComposition* composition) :GuiMouseEventArgs(composition) ,itemIndex(-1) { } }; typedef GuiGraphicsEvent GuiItemNotifyEvent; typedef GuiGraphicsEvent GuiItemMouseEvent; /*********************************************************************** Predefined Node Events ***********************************************************************/ /// Node event arguments. struct GuiNodeEventArgs : public GuiEventArgs, public Description { /// Tree node. controls::tree::INodeProvider* node; GuiNodeEventArgs() :node(0) { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiNodeEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,node(0) { } }; /// Node mouse event arguments. struct GuiNodeMouseEventArgs : public GuiMouseEventArgs, public Description { /// Tree node. controls::tree::INodeProvider* node; GuiNodeMouseEventArgs() :node(0) { } /// Create an event arguments with and set to a specified value. /// The speciied value to set and . GuiNodeMouseEventArgs(GuiGraphicsComposition* composition) :GuiMouseEventArgs(composition) ,node(0) { } }; typedef GuiGraphicsEvent GuiNodeNotifyEvent; typedef GuiGraphicsEvent GuiNodeMouseEvent; /*********************************************************************** Event Receiver ***********************************************************************/ /// /// Contains all available user input events for a . Almost all events are routed events. Routed events means, not only the activated composition receives the event, all it direct or indirect parents receives the event. The argument(all derives from ) for the event will store the original event raiser composition. /// class GuiGraphicsEventReceiver : public Object { protected: GuiGraphicsComposition* sender; public: GuiGraphicsEventReceiver(GuiGraphicsComposition* _sender); ~GuiGraphicsEventReceiver(); GuiGraphicsComposition* GetAssociatedComposition(); /// Left mouse button down event. GuiMouseEvent leftButtonDown; /// Left mouse button up event. GuiMouseEvent leftButtonUp; /// Left mouse button double click event. GuiMouseEvent leftButtonDoubleClick; /// Middle mouse button down event. GuiMouseEvent middleButtonDown; /// Middle mouse button up event. GuiMouseEvent middleButtonUp; /// Middle mouse button double click event. GuiMouseEvent middleButtonDoubleClick; /// Right mouse button down event. GuiMouseEvent rightButtonDown; /// Right mouse button up event. GuiMouseEvent rightButtonUp; /// Right mouse button double click event. GuiMouseEvent rightButtonDoubleClick; /// Horizontal wheel scrolling event. GuiMouseEvent horizontalWheel; /// Vertical wheel scrolling event. GuiMouseEvent verticalWheel; /// Mouse move event. GuiMouseEvent mouseMove; /// Mouse enter event. GuiNotifyEvent mouseEnter; /// Mouse leave event. GuiNotifyEvent mouseLeave; /// Preview key event. GuiKeyEvent previewKey; /// Key down event. GuiKeyEvent keyDown; /// Key up event. GuiKeyEvent keyUp; /// System key down event. GuiKeyEvent systemKeyDown; /// System key up event. GuiKeyEvent systemKeyUp; /// Preview char input event. GuiCharEvent previewCharInput; /// Char input event. GuiCharEvent charInput; /// Got focus event. GuiNotifyEvent gotFocus; /// Lost focus event. GuiNotifyEvent lostFocus; /// Caret notify event. This event is raised when a caret graph need to change the visibility state. GuiNotifyEvent caretNotify; /// Clipboard notify event. This event is raised when the content in the system clipboard is changed. GuiNotifyEvent clipboardNotify; /// Render target changed event. This event is raised when the render target of this composition is changed. GuiNotifyEvent renderTargetChanged; }; } } /*********************************************************************** Workflow to C++ Codegen Helpers ***********************************************************************/ namespace __vwsn { template struct EventHelper> { using Event = presentation::compositions::GuiGraphicsEvent; using Sender = presentation::compositions::GuiGraphicsComposition; using IGuiGraphicsEventHandler = presentation::compositions::IGuiGraphicsEventHandler; using Handler = Func; class EventHandlerImpl : public Object, public reflection::description::IEventHandler { public: Ptr handler; EventHandlerImpl(Ptr _handler) :handler(_handler) { } bool IsAttached()override { return handler->IsAttached(); } }; static Ptr Attach(Event& e, Handler handler) { return MakePtr(e.AttachLambda([=](Sender* sender, T& args) { handler(sender, &args); })); } static bool Detach(Event& e, Ptr handler) { auto impl = handler.Cast(); if (!impl) return false; return e.Detach(impl->handler); } static auto Invoke(Event& e) { return [&](Sender* sender, T* args) { e.ExecuteWithNewSender(*args, sender); }; } }; } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSCOMPOSITIONBASE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSCOMPOSITIONBASE #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSCOMPOSITIONBASE namespace vl { namespace presentation { template using ItemProperty = Func; template using WritableItemProperty = Func; template using TemplateProperty = Func; namespace templates { class GuiTemplate; } namespace controls { class GuiControl; class GuiControlHost; } namespace compositions { class GuiGraphicsHost; /*********************************************************************** Basic Construction ***********************************************************************/ /// /// Represents a composition for . A composition is a way to define the size and the position using the information from graphics elements and sub compositions. /// When a graphics composition is destroyed, all sub composition will be destroyed. The life cycle of the contained graphics element is partially controlled by the smart pointer to the graphics element inside the composition. /// class GuiGraphicsComposition : public Object, public Description { typedef collections::List CompositionList; friend class controls::GuiControl; friend class GuiGraphicsHost; friend void InvokeOnCompositionStateChanged(compositions::GuiGraphicsComposition* composition); public: /// /// Minimum size limitation. /// enum MinSizeLimitation { /// No limitation for the minimum size. NoLimit, /// Minimum size of this composition is the minimum size of the contained graphics element. LimitToElement, /// Minimum size of this composition is combiniation of sub compositions and the minimum size of the contained graphics element. LimitToElementAndChildren, }; protected: struct GraphicsHostRecord { GuiGraphicsHost* host = nullptr; elements::IGuiGraphicsRenderTarget* renderTarget = nullptr; INativeWindow* nativeWindow = nullptr; }; protected: CompositionList children; GuiGraphicsComposition* parent = nullptr; Ptr ownedElement; bool visible = true; bool transparentToMouse = false; MinSizeLimitation minSizeLimitation = MinSizeLimitation::NoLimit; Ptr eventReceiver; GraphicsHostRecord* relatedHostRecord = nullptr; controls::GuiControl* associatedControl = nullptr; INativeCursor* associatedCursor = nullptr; INativeWindowListener::HitTestResult associatedHitTestResult = INativeWindowListener::NoDecision; Margin margin; Margin internalMargin; Size preferredMinSize; bool isRendering = false; virtual void OnControlParentChanged(controls::GuiControl* control); virtual void OnChildInserted(GuiGraphicsComposition* child); virtual void OnChildRemoved(GuiGraphicsComposition* child); virtual void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent); virtual void OnParentLineChanged(); virtual void OnRenderContextChanged(); void UpdateRelatedHostRecord(GraphicsHostRecord* record); void SetAssociatedControl(controls::GuiControl* control); void InvokeOnCompositionStateChanged(); static bool SharedPtrDestructorProc(DescriptableObject* obj, bool forceDisposing); public: GuiGraphicsComposition(); ~GuiGraphicsComposition(); bool IsRendering(); /// Get the parent composition. /// The parent composition. GuiGraphicsComposition* GetParent(); /// Get all child compositions ordered by z-order from low to high. /// Child compositions. const CompositionList& Children(); /// Add a composition as a child. /// Returns true if this operation succeeded. /// The child composition to add. bool AddChild(GuiGraphicsComposition* child); /// Add a composition as a child with a specified z-order. /// Returns true if this operation succeeded. /// The z-order. 0 means the lowest position. /// The child composition to add. bool InsertChild(vint index, GuiGraphicsComposition* child); /// Remove a child composition. /// Returns true if this operation succeeded. /// The child composition to remove. bool RemoveChild(GuiGraphicsComposition* child); /// Move a child composition to a new z-order. /// Returns true if this operation succeeded. /// The child composition to move. /// The new z-order. 0 means the lowest position. bool MoveChild(GuiGraphicsComposition* child, vint newIndex); /// Get the contained graphics element. /// The contained graphics element. Ptr GetOwnedElement(); /// Set the contained graphics element. /// The new graphics element to set. void SetOwnedElement(Ptr element); /// Get the visibility of the composition. /// Returns true if the composition is visible. bool GetVisible(); /// Set the visibility of the composition. /// Set to true to make the composition visible. void SetVisible(bool value); /// Get the minimum size limitation of the composition. /// The minimum size limitation of the composition. MinSizeLimitation GetMinSizeLimitation(); /// Set the minimum size limitation of the composition. /// The minimum size limitation of the composition. void SetMinSizeLimitation(MinSizeLimitation value); /// Get the binded render target. /// The binded render target. elements::IGuiGraphicsRenderTarget* GetRenderTarget(); /// Render the composition using an offset. /// The offset. void Render(Size offset); /// Get the event receiver object. All user input events can be found in this object. If an event receiver is never been requested from the composition, the event receiver will not be created, and all route events will not pass through this event receiver(performance will be better). /// The event receiver. compositions::GuiGraphicsEventReceiver* GetEventReceiver(); /// Test if any event receiver has already been requested. /// Returns true if any event receiver has already been requested. bool HasEventReceiver(); /// Find a deepest composition that under a specified location. If the location is inside a compsition but not hit any sub composition, this function will return this composition. /// The deepest composition that under a specified location. /// The specified location. /// Find a composition for mouse event, it will ignore all compositions that are transparent to mouse events. GuiGraphicsComposition* FindComposition(Point location, bool forMouseEvent); /// Get is this composition transparent to mouse events. /// Returns true if this composition is transparent to mouse events, which means it just passes all mouse events to the composition under it. bool GetTransparentToMouse(); /// Set is the composition transparent to mouse events. /// Set to true to make this composition transparent to mouse events. void SetTransparentToMouse(bool value); /// Get the bounds in the top composition space. /// The bounds in the top composition space. Rect GetGlobalBounds(); /// Get the associated control. A control is associated to a composition only when the composition represents the bounds of this control. Such a composition usually comes from a control template. /// The associated control. controls::GuiControl* GetAssociatedControl(); /// Get the associated graphics host. A graphics host is associated to a composition only when the composition becomes the bounds of the graphics host. /// The associated graphics host. GuiGraphicsHost* GetAssociatedHost(); /// Get the associated cursor. /// The associated cursor. INativeCursor* GetAssociatedCursor(); /// Set the associated cursor. /// The associated cursor. void SetAssociatedCursor(INativeCursor* cursor); /// Get the associated hit test result. /// The associated hit test result. INativeWindowListener::HitTestResult GetAssociatedHitTestResult(); /// Set the associated hit test result. /// The associated hit test result. void SetAssociatedHitTestResult(INativeWindowListener::HitTestResult value); /// Get the related control. A related control is the deepest control that contains this composition. /// The related control. controls::GuiControl* GetRelatedControl(); /// Get the related graphics host. A related graphics host is the graphics host that contains this composition. /// The related graphics host. GuiGraphicsHost* GetRelatedGraphicsHost(); /// Get the related control host. A related control host is the control host that contains this composition. /// The related control host. controls::GuiControlHost* GetRelatedControlHost(); /// Get the related cursor. A related cursor is from the deepest composition that contains this composition and associated with a cursor. /// The related cursor. INativeCursor* GetRelatedCursor(); /// Get the margin. /// The margin. virtual Margin GetMargin(); /// Set the margin. /// The margin. virtual void SetMargin(Margin value); /// Get the internal margin. /// The internal margin. virtual Margin GetInternalMargin(); /// Set the internal margin. /// The internal margin. virtual void SetInternalMargin(Margin value); /// Get the preferred minimum size. /// The preferred minimum size. virtual Size GetPreferredMinSize(); /// Set the preferred minimum size. /// The preferred minimum size. virtual void SetPreferredMinSize(Size value); /// Get the client area. /// The client area. virtual Rect GetClientArea(); /// Force to calculate layout and size immediately virtual void ForceCalculateSizeImmediately(); /// Test is the size calculation affected by the parent. /// Returns true if the size calculation is affected by the parent. virtual bool IsSizeAffectParent()=0; /// Get the preferred minimum client size. /// The preferred minimum client size. virtual Size GetMinPreferredClientSize()=0; /// Get the preferred bounds. /// The preferred bounds. virtual Rect GetPreferredBounds()=0; /// Get the bounds. /// The bounds. virtual Rect GetBounds()=0; }; /// /// A general implementation for . /// class GuiGraphicsSite : public GuiGraphicsComposition, public Description { protected: Rect previousBounds; /// Calculate the final bounds from an expected bounds. /// The final bounds according to some configuration like margin, minimum size, etc.. /// The expected bounds. virtual Rect GetBoundsInternal(Rect expectedBounds); void UpdatePreviousBounds(Rect bounds); public: GuiGraphicsSite(); ~GuiGraphicsSite(); /// Event that will be raised when the final bounds is changed. compositions::GuiNotifyEvent BoundsChanged; bool IsSizeAffectParent()override; Size GetMinPreferredClientSize()override; Rect GetPreferredBounds()override; }; /*********************************************************************** Helper Functions ***********************************************************************/ /// Call [M:vl.presentation.controls.GuiInstanceRootObject.FinalizeInstance] in all child root objects. /// The container control to notify. extern void NotifyFinalizeInstance(controls::GuiControl* value); /// Call [M:vl.presentation.controls.GuiInstanceRootObject.FinalizeInstance] in all child root objects. /// The container composition to notify. extern void NotifyFinalizeInstance(GuiGraphicsComposition* value); /// Safely remove and delete a control. /// The control to delete. extern void SafeDeleteControl(controls::GuiControl* value); /// Safely remove and delete a composition. If some sub compositions are controls, those controls will be deleted too. /// The composition to delete. extern void SafeDeleteComposition(GuiGraphicsComposition* value); } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSBASICCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSBASICCOMPOSITION #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSBASICCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Basic Compositions ***********************************************************************/ /// /// Represents a composition for the client area in an . /// class GuiWindowComposition : public GuiGraphicsSite, public Description { public: GuiWindowComposition(); ~GuiWindowComposition(); Rect GetBounds()override; void SetMargin(Margin value)override; }; /// /// Represents a composition that is free to change the expected bounds. /// class GuiBoundsComposition : public GuiGraphicsSite, public Description { protected: bool sizeAffectParent = true; Rect compositionBounds; Margin alignmentToParent{ -1,-1,-1,-1 }; public: GuiBoundsComposition(); ~GuiBoundsComposition(); /// Get if the parent composition's size calculation is aware of the configuration of this composition. If you want to bind Bounds, PreferredMinSize, AlignmentToParent or other similar properties to some properties of parent compositions, this property should be set to false to prevent from infinite size glowing. /// Returns true if it is awared. bool GetSizeAffectParent(); /// Set if the parent composition's size calculation is aware of the configuration of this composition. /// Set to true to be awared. void SetSizeAffectParent(bool value); bool IsSizeAffectParent()override; Rect GetPreferredBounds()override; Rect GetBounds()override; /// Set the expected bounds. /// The expected bounds. void SetBounds(Rect value); /// Get the alignment to its parent. -1 in each alignment component means that the corressponding side is not aligned to its parent. /// The alignment to its parent. Margin GetAlignmentToParent(); /// Set the alignment to its parent. -1 in each alignment component means that the corressponding side is not aligned to its parent. /// The alignment to its parent. void SetAlignmentToParent(Margin value); /// Test is the composition aligned to its parent. /// Returns true if the composition is aligned to its parent. bool IsAlignedToParent(); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\INCLUDEFORWARD.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_INCLUDEFORWARD #define VCZH_PRESENTATION_COMPOSITION_INCLUDEFORWARD namespace vl { namespace presentation { namespace compositions { class GuiTableComposition; class GuiCellComposition; class GuiTableSplitterCompositionBase; class GuiRowSplitterComposition; class GuiColumnSplitterComposition; class GuiStackComposition; class GuiStackItemComposition; class GuiFlowComposition; class GuiFlowItemComposition; class GuiSideAlignedComposition; class GuiPartialViewComposition; class GuiResponsiveCompositionBase; class GuiResponsiveViewComposition; class GuiResponsiveSharedComposition; class GuiResponsiveFixedComposition; class GuiResponsiveStackComposition; class GuiResponsiveGroupComposition; class GuiResponsiveContainerComposition; class GuiSharedSizeItemComposition; class GuiSharedSizeRootComposition; class GuiRepeatCompositionBase; class GuiRepeatStackComposition; class GuiRepeatFlowComposition; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSFLOWCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSFLOWCOMPOSITION #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSFLOWCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Flow Compositions ***********************************************************************/ /// /// Alignment for a row in a flow layout /// enum class FlowAlignment { /// Align to the left. Left, /// Align to the center. Center, /// Extend to the entire row. Extend, }; /// /// Represents a flow composition. /// class GuiFlowComposition : public GuiBoundsComposition, public Description { friend class GuiFlowItemComposition; typedef collections::List ItemCompositionList; protected: Margin extraMargin; vint rowPadding = 0; vint columnPadding = 0; FlowAlignment alignment = FlowAlignment::Left; Ptr axis; ItemCompositionList flowItems; collections::Array flowItemBounds; Rect bounds; vint minHeight = 0; bool needUpdate = false; void UpdateFlowItemBounds(bool forceUpdate); void OnBoundsChanged(GuiGraphicsComposition* sender, GuiEventArgs& arguments); void OnChildInserted(GuiGraphicsComposition* child)override; void OnChildRemoved(GuiGraphicsComposition* child)override; public: GuiFlowComposition(); ~GuiFlowComposition(); /// Get all flow items inside the flow composition. /// All flow items inside the flow composition. const ItemCompositionList& GetFlowItems(); /// Insert a flow item at a specified position. /// Returns true if this operation succeeded. /// The position. /// The flow item to insert. bool InsertFlowItem(vint index, GuiFlowItemComposition* item); /// Get the extra margin inside the flow composition. /// The extra margin inside the flow composition. Margin GetExtraMargin(); /// Set the extra margin inside the flow composition. /// The extra margin inside the flow composition. void SetExtraMargin(Margin value); /// Get the distance between rows. /// The distance between rows. vint GetRowPadding(); /// Set the distance between rows. /// The distance between rows. void SetRowPadding(vint value); /// Get the distance between columns. /// The distance between columns. vint GetColumnPadding(); /// Set the distance between columns. /// The distance between columns. void SetColumnPadding(vint value); /// Get the axis of the layout. /// The axis. Ptr GetAxis(); /// Set the axis of the layout. /// The axis. void SetAxis(Ptr value); /// Get the alignment for rows. /// The alignment. FlowAlignment GetAlignment(); /// Set the alignment for rows. /// The alignment. void SetAlignment(FlowAlignment value); void ForceCalculateSizeImmediately()override; Size GetMinPreferredClientSize()override; Rect GetBounds()override; }; /// /// Represnets a base line configuration for a flow item. /// struct GuiFlowOption { /// Base line calculation algorithm enum BaselineType { /// By percentage of the height from the top. Percentage, /// By a distance from the top. FromTop, /// By a distance from the bottom. FromBottom, }; /// The base line calculation algorithm. BaselineType baseline = FromBottom; /// The percentage value. double percentage = 0.0; /// The distance value. vint distance = 0; }; /// /// Represents a flow item composition of a . /// class GuiFlowItemComposition : public GuiGraphicsSite, public Description { friend class GuiFlowComposition; protected: GuiFlowComposition* flowParent; Rect bounds; Margin extraMargin; GuiFlowOption option; void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent)override; Size GetMinSize(); public: GuiFlowItemComposition(); ~GuiFlowItemComposition(); bool IsSizeAffectParent()override; Rect GetBounds()override; void SetBounds(Rect value); /// Get the extra margin for this flow item. An extra margin is used to enlarge the bounds of the flow item, but only the non-extra part will be used for deciding the flow item layout. /// The extra margin for this flow item. Margin GetExtraMargin(); /// Set the extra margin for this flow item. An extra margin is used to enlarge the bounds of the flow item, but only the non-extra part will be used for deciding the flow item layout. /// The extra margin for this flow item. void SetExtraMargin(Margin value); /// Get the base line option for this flow item. /// The base line option. GuiFlowOption GetFlowOption(); /// Set the base line option for this flow item. /// The base line option. void SetFlowOption(GuiFlowOption value); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSRESPONSIVECOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSRESPONSIVECOMPOSITION #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSRESPONSIVECOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** GuiResponsiveCompositionBase ***********************************************************************/ enum class ResponsiveDirection { Horizontal = 1, Vertical = 2, Both = 3, }; /// Base class for responsive layout compositions. class GuiResponsiveCompositionBase abstract : public GuiBoundsComposition, public Description { protected: GuiResponsiveCompositionBase* responsiveParent = nullptr; ResponsiveDirection direction = ResponsiveDirection::Both; void OnParentLineChanged()override; virtual void OnResponsiveChildInserted(GuiResponsiveCompositionBase* child); virtual void OnResponsiveChildRemoved(GuiResponsiveCompositionBase* child); virtual void OnResponsiveChildLevelUpdated(); public: GuiResponsiveCompositionBase(); ~GuiResponsiveCompositionBase(); /// LevelCount changed event. GuiNotifyEvent LevelCountChanged; /// CurrentLevel chagned event. GuiNotifyEvent CurrentLevelChanged; /// Get the level count. A level count represents how many views this composition carries. /// The level count. virtual vint GetLevelCount() = 0; /// Get the current level. Zero is the view with the smallest size. /// The current level. virtual vint GetCurrentLevel() = 0; /// Switch to a smaller view. /// Returns true if this operation succeeded. virtual bool LevelDown() = 0; /// Switch to a larger view. /// Returns true if this operation succeeded. virtual bool LevelUp() = 0; /// Get all supported directions. If all directions of a child [T:vl.presentation.compositions.GuiResponsiveCompositionBase] are not supported, its view will not be changed when the parent composition changes its view . /// All supported directions. ResponsiveDirection GetDirection(); /// Set all supported directions. /// All supported directions. void SetDirection(ResponsiveDirection value); }; /*********************************************************************** GuiResponsiveViewComposition ***********************************************************************/ class GuiResponsiveSharedCollection : public collections::ObservableListBase { protected: GuiResponsiveViewComposition* view = nullptr; void BeforeInsert(vint index, controls::GuiControl* const& value)override; void AfterInsert(vint index, controls::GuiControl* const& value)override; void BeforeRemove(vint index, controls::GuiControl* const& value)override; void AfterRemove(vint index, vint count)override; public: GuiResponsiveSharedCollection(GuiResponsiveViewComposition* _view); ~GuiResponsiveSharedCollection(); }; class GuiResponsiveViewCollection : public collections::ObservableListBase { protected: GuiResponsiveViewComposition* view = nullptr; void BeforeInsert(vint index, GuiResponsiveCompositionBase* const& value)override; void AfterInsert(vint index, GuiResponsiveCompositionBase* const& value)override; void BeforeRemove(vint index, GuiResponsiveCompositionBase* const& value)override; void AfterRemove(vint index, vint count)override; public: GuiResponsiveViewCollection(GuiResponsiveViewComposition* _view); ~GuiResponsiveViewCollection(); }; /// Represents a composition, which will pick up a shared control and install inside it, when it is displayed by a [T:vl.presentation.compositions.GuiResponsiveViewComposition] class GuiResponsiveSharedComposition : public GuiBoundsComposition, public Description { protected: GuiResponsiveViewComposition* view = nullptr; controls::GuiControl* shared = nullptr; void SetSharedControl(); void OnParentLineChanged()override; public: GuiResponsiveSharedComposition(); ~GuiResponsiveSharedComposition(); /// Get the selected shared control. /// The selected shared control. controls::GuiControl* GetShared(); /// Set the selected shared control, which should be stored in [M:vl.presentation.compositions.GuiResponsiveViewComposition.GetSharedControls]. /// The selected shared control. void SetShared(controls::GuiControl* value); }; /// A responsive layout composition defined by views of different sizes. class GuiResponsiveViewComposition : public GuiResponsiveCompositionBase, public Description { friend class GuiResponsiveSharedCollection; friend class GuiResponsiveViewCollection; friend class GuiResponsiveSharedComposition; using ControlSet = collections::SortedList; protected: vint levelCount = 1; vint currentLevel = 0; bool skipUpdatingLevels = false; GuiResponsiveCompositionBase* currentView = nullptr; ControlSet usedSharedControls; GuiResponsiveSharedCollection sharedControls; GuiResponsiveViewCollection views; bool destructing = false; bool CalculateLevelCount(); bool CalculateCurrentLevel(); void OnResponsiveChildLevelUpdated()override; public: GuiResponsiveViewComposition(); ~GuiResponsiveViewComposition(); /// Before switch view event. This event happens between hiding the previous view and showing the next view. The itemIndex field can be used to access [M:vl.presentation.compositions.GuiResponsiveViewComposition.GetViews], it is not the level number. GuiItemNotifyEvent BeforeSwitchingView; vint GetLevelCount()override; vint GetCurrentLevel()override; bool LevelDown()override; bool LevelUp()override; /// Get the current displaying view. /// The current displaying view. GuiResponsiveCompositionBase* GetCurrentView(); /// Get all shared controls. A shared control can jump between different views if it is contained in a [T:vl.presentation.compositions.GuiResponsiveSharedComposition]. This helps to keep control states during switching views. /// All shared controls. collections::ObservableListBase& GetSharedControls(); /// Get all individual views to switch. /// All individual views to switch. collections::ObservableListBase& GetViews(); }; /*********************************************************************** Others ***********************************************************************/ /// A responsive layout composition which stop parent responsive composition to search its children. class GuiResponsiveFixedComposition : public GuiResponsiveCompositionBase, public Description { protected: void OnResponsiveChildLevelUpdated()override; public: GuiResponsiveFixedComposition(); ~GuiResponsiveFixedComposition(); vint GetLevelCount()override; vint GetCurrentLevel()override; bool LevelDown()override; bool LevelUp()override; }; /// A responsive layout composition which change its size by changing children's views one by one in one direction. class GuiResponsiveStackComposition : public GuiResponsiveCompositionBase, public Description { using ResponsiveChildList = collections::List; protected: vint levelCount = 1; vint currentLevel = 0; ResponsiveChildList responsiveChildren; bool CalculateLevelCount(); bool CalculateCurrentLevel(); void OnResponsiveChildInserted(GuiResponsiveCompositionBase* child)override; void OnResponsiveChildRemoved(GuiResponsiveCompositionBase* child)override; void OnResponsiveChildLevelUpdated()override; bool ChangeLevel(bool levelDown); public: GuiResponsiveStackComposition(); ~GuiResponsiveStackComposition(); vint GetLevelCount()override; vint GetCurrentLevel()override; bool LevelDown()override; bool LevelUp()override; }; /// A responsive layout composition which change its size by changing children's views at the same time. class GuiResponsiveGroupComposition : public GuiResponsiveCompositionBase, public Description { using ResponsiveChildList = collections::List; protected: vint levelCount = 1; vint currentLevel = 0; ResponsiveChildList responsiveChildren; bool CalculateLevelCount(); bool CalculateCurrentLevel(); void OnResponsiveChildInserted(GuiResponsiveCompositionBase* child)override; void OnResponsiveChildRemoved(GuiResponsiveCompositionBase* child)override; void OnResponsiveChildLevelUpdated()override; public: GuiResponsiveGroupComposition(); ~GuiResponsiveGroupComposition(); vint GetLevelCount()override; vint GetCurrentLevel()override; bool LevelDown()override; bool LevelUp()override; }; /*********************************************************************** GuiResponsiveContainerComposition ***********************************************************************/ /// A composition which will automatically tell its target responsive composition to switch between views according to its size. class GuiResponsiveContainerComposition : public GuiBoundsComposition, public Description { protected: GuiResponsiveCompositionBase* responsiveTarget = nullptr; Size upperLevelSize; void AdjustLevel(); void OnBoundsChanged(GuiGraphicsComposition* sender, GuiEventArgs& arguments); public: GuiResponsiveContainerComposition(); ~GuiResponsiveContainerComposition(); /// Get the responsive composition to control. /// The responsive composition to control. GuiResponsiveCompositionBase* GetResponsiveTarget(); /// Get the responsive composition to control. /// The responsive composition to control. void SetResponsiveTarget(GuiResponsiveCompositionBase* value); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSSHAREDSIZECOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSSHAREDSIZECOMPOSITION #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSSHAREDSIZECOMPOSITION namespace vl { namespace presentation { namespace compositions { /// A shared size composition that shares the same size with all other that has a same group name. class GuiSharedSizeItemComposition : public GuiBoundsComposition, public Description { protected: GuiSharedSizeRootComposition* parentRoot = nullptr; WString group; bool sharedWidth = false; bool sharedHeight = false; void Update(); void OnParentLineChanged()override; public: GuiSharedSizeItemComposition(); ~GuiSharedSizeItemComposition(); /// Get the group name of this item. /// The group name. const WString& GetGroup(); /// Set the group name of this item. /// The group name. void SetGroup(const WString& value); /// Test is the width of this item is shared. /// Returns true if the width of this item is shared. bool GetSharedWidth(); /// Enable or disable sharing the width of this item. /// Set to true to share the width of this item. void SetSharedWidth(bool value); /// Test is the height of this item is shared. /// Returns true if the height of this item is shared. bool GetSharedHeight(); /// Enable or disable sharing the height of this item. /// Set to true to share the height of this item. void SetSharedHeight(bool value); }; /// A root composition that takes care of all direct or indirect to enable size sharing. class GuiSharedSizeRootComposition :public GuiBoundsComposition, public Description { friend class GuiSharedSizeItemComposition; protected: collections::Dictionary itemWidths; collections::Dictionary itemHeights; collections::List childItems; void AddSizeComponent(collections::Dictionary& sizes, const WString& group, vint sizeComponent); void CollectSizes(collections::Dictionary& widths, collections::Dictionary& heights); void AlignSizes(collections::Dictionary& widths, collections::Dictionary& heights); public: GuiSharedSizeRootComposition(); ~GuiSharedSizeRootComposition(); void ForceCalculateSizeImmediately()override; Rect GetBounds()override; }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSSPECIALIZEDCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSSPECIALIZEDCOMPOSITION #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSSPECIALIZEDCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Specialized Compositions ***********************************************************************/ /// /// Represents a composition that is aligned to one border of the parent composition. /// class GuiSideAlignedComposition : public GuiGraphicsSite, public Description { public: /// The border to align. enum Direction { /// The left border. Left, /// The top border. Top, /// The right border. Right, /// The bottom border. Bottom, }; protected: Direction direction; vint maxLength; double maxRatio; public: GuiSideAlignedComposition(); ~GuiSideAlignedComposition(); /// Get the border to align. /// The border to align. Direction GetDirection(); /// Set the border to align. /// The border to align. void SetDirection(Direction value); /// Get the maximum length of this composition. /// The maximum length of this composition. vint GetMaxLength(); /// Set the maximum length of this composition. /// The maximum length of this composition. void SetMaxLength(vint value); /// Get the maximum ratio to limit the size according to the size of the parent. /// The maximum ratio to limit the size according to the size of the parent. double GetMaxRatio(); /// Set the maximum ratio to limit the size according to the size of the parent. /// The maximum ratio to limit the size according to the size of the parent. void SetMaxRatio(double value); bool IsSizeAffectParent()override; Rect GetBounds()override; }; /// /// Represents a composition that its location and size are decided by the client area of the parent composition by setting ratios. /// class GuiPartialViewComposition : public GuiGraphicsSite, public Description { protected: double wRatio; double wPageSize; double hRatio; double hPageSize; public: GuiPartialViewComposition(); ~GuiPartialViewComposition(); /// Get the width ratio to decided the horizontal location. Value in [0, 1-pageSize]. /// The width ratio to decided the horizontal location. double GetWidthRatio(); /// Get the page size to decide the horizontal size. Value in [0, 1]. /// The page size to decide the horizontal size. double GetWidthPageSize(); /// Get the height ratio to decided the vertical location. Value in [0, 1-pageSize]. /// The height ratio to decided the vertical location. double GetHeightRatio(); /// Get the page size to decide the vertical size. Value in [0, 1]. /// The page size to decide the vertical size. double GetHeightPageSize(); /// Set the width ratio to decided the horizontal location. Value in [0, 1-pageSize]. /// The width ratio to decided the horizontal location. void SetWidthRatio(double value); /// Set the page size to decide the horizontal size. Value in [0, 1]. /// The page size to decide the horizontal size. void SetWidthPageSize(double value); /// Set the height ratio to decided the vertical location. Value in [0, 1-pageSize]. /// The height ratio to decided the vertical location. void SetHeightRatio(double value); /// Set the page size to decide the vertical size. Value in [0, 1]. /// The page size to decide the vertical size. void SetHeightPageSize(double value); bool IsSizeAffectParent()override; Rect GetBounds()override; }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSSTACKCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSSTACKCOMPOSITION #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSSTACKCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Stack Compositions ***********************************************************************/ /// /// Represents a stack composition. /// class GuiStackComposition : public GuiBoundsComposition, public Description { friend class GuiStackItemComposition; typedef collections::List ItemCompositionList; public: /// Stack item layout direction. enum Direction { /// Stack items is layouted from left to right. Horizontal, /// Stack items is layouted from top to bottom. Vertical, /// Stack items is layouted from right to left. ReversedHorizontal, /// Stack items is layouted from bottom to top. ReversedVertical, }; protected: Direction direction = Horizontal; ItemCompositionList stackItems; GuiStackItemComposition* ensuringVisibleStackItem = nullptr; vint padding = 0; vint adjustment = 0; Margin extraMargin; collections::Array stackItemBounds; Size stackItemTotalSize; Rect previousBounds; void UpdateStackItemBounds(); void EnsureStackItemVisible(); void OnBoundsChanged(GuiGraphicsComposition* sender, GuiEventArgs& arguments); void OnChildInserted(GuiGraphicsComposition* child)override; void OnChildRemoved(GuiGraphicsComposition* child)override; public: GuiStackComposition(); ~GuiStackComposition(); /// Get all stack items inside the stack composition. /// All stack items inside the stack composition. const ItemCompositionList& GetStackItems(); /// Insert a stack item at a specified position. /// Returns true if this operation succeeded. /// The position. /// The statck item to insert. bool InsertStackItem(vint index, GuiStackItemComposition* item); /// Get the stack item layout direction. /// The stack item layout direction. Direction GetDirection(); /// Set the stack item layout direction. /// The stack item layout direction. void SetDirection(Direction value); /// Get the stack item padding. /// The stack item padding. vint GetPadding(); /// Set the stack item padding. /// The stack item padding. void SetPadding(vint value); void ForceCalculateSizeImmediately()override; Size GetMinPreferredClientSize()override; Rect GetBounds()override; /// Get the extra margin inside the stack composition. /// The extra margin inside the stack composition. Margin GetExtraMargin(); /// Set the extra margin inside the stack composition. /// The extra margin inside the stack composition. void SetExtraMargin(Margin value); /// Test is any stack item clipped in the stack direction. /// Returns true if any stack item is clipped. bool IsStackItemClipped(); /// Make an item visible as complete as possible. /// Returns true if this operation succeeded. /// The index of the item. bool EnsureVisible(vint index); }; /// /// Represents a stack item composition of a . /// class GuiStackItemComposition : public GuiGraphicsSite, public Description { friend class GuiStackComposition; protected: GuiStackComposition* stackParent; Rect bounds; Margin extraMargin; void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent)override; Size GetMinSize(); public: GuiStackItemComposition(); ~GuiStackItemComposition(); bool IsSizeAffectParent()override; Rect GetBounds()override; /// Set the expected bounds of a stack item. In most of the cases only the size of the bounds is used. /// The expected bounds of a stack item. void SetBounds(Rect value); /// Get the extra margin for this stack item. An extra margin is used to enlarge the bounds of the stack item, but only the non-extra part will be used for deciding the stack item layout. /// The extra margin for this stack item. Margin GetExtraMargin(); /// Set the extra margin for this stack item. An extra margin is used to enlarge the bounds of the stack item, but only the non-extra part will be used for deciding the stack item layout. /// The extra margin for this stack item. void SetExtraMargin(Margin value); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSREPEATCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSREPEATCOMPOSITION #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSREPEATCOMPOSITION namespace vl { namespace presentation { namespace compositions { /// A base class for all bindable repeat compositions. class GuiRepeatCompositionBase : public Object, public Description { using ItemStyleProperty = TemplateProperty; using IValueEnumerable = reflection::description::IValueEnumerable; using IValueList = reflection::description::IValueList; protected: ItemStyleProperty itemTemplate; Ptr itemSource; Ptr itemChangedHandler; virtual vint GetRepeatCompositionCount() = 0; virtual GuiGraphicsComposition* GetRepeatComposition(vint index) = 0; virtual GuiGraphicsComposition* InsertRepeatComposition(vint index) = 0; virtual GuiGraphicsComposition* RemoveRepeatComposition(vint index) = 0; void OnItemChanged(vint index, vint oldCount, vint newCount); void RemoveItem(vint index); void InstallItem(vint index); void ClearItems(); void InstallItems(); public: GuiRepeatCompositionBase(); ~GuiRepeatCompositionBase(); /// An event called after a new item is inserted. GuiItemNotifyEvent ItemInserted; /// An event called before a new item is removed. GuiItemNotifyEvent ItemRemoved; /// Get the item style provider. /// The item style provider. ItemStyleProperty GetItemTemplate(); /// Set the item style provider /// The new item style provider void SetItemTemplate(ItemStyleProperty value); /// Get the item source. /// The item source. Ptr GetItemSource(); /// Set the item source. /// The item source. Null is acceptable if you want to clear all data. void SetItemSource(Ptr value); }; /// Bindable stack composition. class GuiRepeatStackComposition : public GuiStackComposition, public GuiRepeatCompositionBase, public Description { protected: vint GetRepeatCompositionCount()override; GuiGraphicsComposition* GetRepeatComposition(vint index)override; GuiGraphicsComposition* InsertRepeatComposition(vint index)override; GuiGraphicsComposition* RemoveRepeatComposition(vint index)override; public: }; /// Bindable flow composition. class GuiRepeatFlowComposition : public GuiFlowComposition, public GuiRepeatCompositionBase, public Description { protected: vint GetRepeatCompositionCount()override; GuiGraphicsComposition* GetRepeatComposition(vint index)override; GuiGraphicsComposition* InsertRepeatComposition(vint index)override; GuiGraphicsComposition* RemoveRepeatComposition(vint index)override; public: }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSTABLECOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSTABLECOMPOSITION #define VCZH_PRESENTATION_COMPOSITION_GUIGRAPHICSTABLECOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Table Compositions ***********************************************************************/ /// /// Represnets a sizing configuration for a row or a column. /// struct GuiCellOption { /// Sizing algorithm enum ComposeType { /// Set the size to an absolute value. Absolute, /// Set the size to a percentage number of the whole table. Percentage, /// Set the size to the minimum size of the cell element. MinSize, }; /// Sizing algorithm ComposeType composeType; /// The absolute size when is ::Absolute. vint absolute; /// The percentage number when is ::Percentage. double percentage; GuiCellOption() :composeType(Absolute) ,absolute(20) ,percentage(0) { } bool operator==(const GuiCellOption& value){return false;} bool operator!=(const GuiCellOption& value){return true;} /// Creates an absolute sizing option /// The created option. /// The absolute size. static GuiCellOption AbsoluteOption(vint value) { GuiCellOption option; option.composeType=Absolute; option.absolute=value; return option; } /// Creates an percantage sizing option /// The created option. /// The percentage number. static GuiCellOption PercentageOption(double value) { GuiCellOption option; option.composeType=Percentage; option.percentage=value; return option; } /// Creates an minimum sizing option /// The created option. static GuiCellOption MinSizeOption() { GuiCellOption option; option.composeType=MinSize; return option; } }; /// /// Represents a table composition. /// class GuiTableComposition : public GuiBoundsComposition, public Description { friend class GuiCellComposition; friend class GuiTableSplitterCompositionBase; friend class GuiRowSplitterComposition; friend class GuiColumnSplitterComposition; protected: vint rows; vint columns; vint cellPadding; bool borderVisible; vint rowExtending; vint columnExtending; collections::Array rowOptions; collections::Array columnOptions; collections::Array cellCompositions; collections::Array cellBounds; collections::Array rowOffsets; collections::Array columnOffsets; collections::Array rowSizes; collections::Array columnSizes; Size tableContentMinSize; vint GetSiteIndex(vint _rows, vint _columns, vint _row, vint _column); void SetSitedCell(vint _row, vint _column, GuiCellComposition* cell); void UpdateCellBoundsInternal( collections::Array& dimSizes, vint& dimSize, vint& dimSizeWithPercentage, collections::Array& dimOptions, vint GuiTableComposition::* dim1, vint GuiTableComposition::* dim2, vint (*getSize)(Size), vint (*getLocation)(GuiCellComposition*), vint (*getSpan)(GuiCellComposition*), vint (*getRow)(vint, vint), vint (*getCol)(vint, vint), vint maxPass ); void UpdateCellBoundsPercentages( collections::Array& dimSizes, vint dimSize, vint maxDimSize, collections::Array& dimOptions ); vint UpdateCellBoundsOffsets( collections::Array& offsets, collections::Array& sizes, vint max ); void OnRenderContextChanged()override; public: GuiTableComposition(); ~GuiTableComposition(); /// Event that will be raised with row numbers, column numbers or options are changed. compositions::GuiNotifyEvent ConfigChanged; /// Get the number of rows. /// The number of rows. vint GetRows(); /// Get the number of columns. /// The number of columns. vint GetColumns(); /// Change the number of rows and columns. /// Returns true if this operation succeeded. /// The number of rows. /// The number of columns. bool SetRowsAndColumns(vint _rows, vint _columns); /// Get the cell composition that covers the specified cell location. /// The cell composition that covers the specified cell location. /// The number of rows. /// The number of columns. GuiCellComposition* GetSitedCell(vint _row, vint _column); /// Get the sizing option of the specified row. /// The sizing option of the specified row. /// The specified row number. GuiCellOption GetRowOption(vint _row); /// Set the sizing option of the specified row. /// The specified row number. /// The sizing option of the specified row. void SetRowOption(vint _row, GuiCellOption option); /// Get the sizing option of the specified column. /// The sizing option of the specified column. /// The specified column number. GuiCellOption GetColumnOption(vint _column); /// Set the sizing option of the specified column. /// The specified column number. /// The sizing option of the specified column. void SetColumnOption(vint _column, GuiCellOption option); /// Get the cell padding. A cell padding is the distance between a table client area and a cell, or between two cells. /// The cell padding. vint GetCellPadding(); /// Set the cell padding. A cell padding is the distance between a table client area and a cell, or between two cells. /// The cell padding. void SetCellPadding(vint value); /// Get the border visibility. /// Returns true means the border thickness equals to the cell padding, otherwise zero. bool GetBorderVisible(); /// Set the border visibility. /// Set to true to let the border thickness equal to the cell padding, otherwise zero. void SetBorderVisible(bool value); /// Get the cell area in the space of the table's parent composition's client area. /// The cell area. Rect GetCellArea(); /// Update the sizing of the table and cells after all rows' and columns' sizing options are prepared. void UpdateCellBounds(); void ForceCalculateSizeImmediately()override; Size GetMinPreferredClientSize()override; Rect GetBounds()override; }; /// /// Represents a cell composition of a . /// class GuiCellComposition : public GuiGraphicsSite, public Description { friend class GuiTableComposition; protected: vint row; vint rowSpan; vint column; vint columnSpan; GuiTableComposition* tableParent; Size lastPreferredSize; void ClearSitedCells(GuiTableComposition* table); void SetSitedCells(GuiTableComposition* table); void ResetSiteInternal(); bool SetSiteInternal(vint _row, vint _column, vint _rowSpan, vint _columnSpan); void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent)override; void OnTableRowsAndColumnsChanged(); public: GuiCellComposition(); ~GuiCellComposition(); /// Get the owner table composition. /// The owner table composition. GuiTableComposition* GetTableParent(); /// Get the row number for this cell composition. /// The row number for this cell composition. vint GetRow(); /// Get the total numbers of acrossed rows for this cell composition. /// The total numbers of acrossed rows for this cell composition. vint GetRowSpan(); /// Get the column number for this cell composition. /// The column number for this cell composition. vint GetColumn(); /// Get the total numbers of acrossed columns for this cell composition. /// The total numbers of acrossed columns for this cell composition. vint GetColumnSpan(); /// Set the position for this cell composition in the table. /// Returns true if this operation succeeded. /// The row number for this cell composition. /// The column number for this cell composition. /// The total numbers of acrossed rows for this cell composition. /// The total numbers of acrossed columns for this cell composition. bool SetSite(vint _row, vint _column, vint _rowSpan, vint _columnSpan); Rect GetBounds()override; }; class GuiTableSplitterCompositionBase : public GuiGraphicsSite, public Description { protected: GuiTableComposition* tableParent; bool dragging; Point draggingPoint; void OnParentChanged(GuiGraphicsComposition* oldParent, GuiGraphicsComposition* newParent)override; void OnLeftButtonDown(GuiGraphicsComposition* sender, GuiMouseEventArgs& arguments); void OnLeftButtonUp(GuiGraphicsComposition* sender, GuiMouseEventArgs& arguments); void OnMouseMoveHelper( vint cellsBefore, vint GuiTableComposition::* cells, collections::Array& cellSizes, vint offset, GuiCellOption(GuiTableComposition::*getOption)(vint), void(GuiTableComposition::*setOption)(vint, GuiCellOption) ); Rect GetBoundsHelper( vint cellsBefore, vint GuiTableComposition::* cells, vint(Rect::* dimSize)()const, collections::Array& cellOffsets, vint Rect::* dimU1, vint Rect::* dimU2, vint Rect::* dimV1, vint Rect::* dimV2 ); public: GuiTableSplitterCompositionBase(); ~GuiTableSplitterCompositionBase(); /// Get the owner table composition. /// The owner table composition. GuiTableComposition* GetTableParent(); }; /// /// Represents a row splitter composition of a . /// class GuiRowSplitterComposition : public GuiTableSplitterCompositionBase, public Description { protected: vint rowsToTheTop; void OnMouseMove(GuiGraphicsComposition* sender, GuiMouseEventArgs& arguments); public: GuiRowSplitterComposition(); ~GuiRowSplitterComposition(); /// Get the number of rows that above the splitter. /// The number of rows that above the splitter. vint GetRowsToTheTop(); /// Set the number of rows that above the splitter. /// The number of rows that above the splitter void SetRowsToTheTop(vint value); Rect GetBounds()override; }; /// /// Represents a column splitter composition of a . /// class GuiColumnSplitterComposition : public GuiTableSplitterCompositionBase, public Description { protected: vint columnsToTheLeft; void OnMouseMove(GuiGraphicsComposition* sender, GuiMouseEventArgs& arguments); public: GuiColumnSplitterComposition(); ~GuiColumnSplitterComposition(); /// Get the number of columns that before the splitter. /// The number of columns that before the splitter. vint GetColumnsToTheLeft(); /// Set the number of columns that before the splitter. /// The number of columns that before the splitter void SetColumnsToTheLeft(vint value); Rect GetBounds()override; }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\INCLUDEALL.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_COMPOSITION_INCLUDEALL #define VCZH_PRESENTATION_COMPOSITION_INCLUDEALL #endif /*********************************************************************** .\GRAPHICSELEMENT\GUIGRAPHICSRESOURCEMANAGER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Element System and Infrastructure Interfaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSRESOURCEMANAGER #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSRESOURCEMANAGER namespace vl { namespace presentation { namespace elements { /*********************************************************************** Resource Manager ***********************************************************************/ /// /// This is a class for managing grpahics element factories and graphics renderer factories /// class GuiGraphicsResourceManager : public Object { protected: collections::List elementTypes; collections::Array> rendererFactories; public: /// /// Create a graphics resource manager without any predefined factories /// GuiGraphicsResourceManager(); ~GuiGraphicsResourceManager(); /// /// Register a element type name. /// This function crashes when an element type has already been registered. /// /// The element type. /// A number identifies this element type. vint RegisterElementType(const WString& elementTypeName); /// /// Register a and bind it to an registered element type from . /// This function crashes when an element type has already been binded a renderer factory. /// /// The element type to represent a graphics element factory. /// The instance of the graphics renderer factory to register. void RegisterRendererFactory(vint elementType, Ptr factory); /// /// Get the instance of a registered that is binded to a specified element type. /// /// Returns the renderer factory. /// The registered element type from to get a binded graphics renderer factory. IGuiGraphicsRendererFactory* GetRendererFactory(vint elementType); /// /// Get the instance of a that is binded to an . /// /// The specified window. /// Returns the render target. virtual IGuiGraphicsRenderTarget* GetRenderTarget(INativeWindow* window) = 0; /// /// Recreate the render target for the specified window. /// /// The specified window. virtual void RecreateRenderTarget(INativeWindow* window) = 0; /// /// Resize the render target to fit the current window size. /// /// The specified window. virtual void ResizeRenderTarget(INativeWindow* window) = 0; /// /// Get the renderer awared rich text document layout engine provider object. /// /// Returns the layout provider. virtual IGuiGraphicsLayoutProvider* GetLayoutProvider() = 0; }; /// /// Get the current . /// /// Returns the current resource manager. extern GuiGraphicsResourceManager* GetGuiGraphicsResourceManager(); /// /// Set the current . /// /// The resource manager to set. extern void SetGuiGraphicsResourceManager(GuiGraphicsResourceManager* resourceManager); /*********************************************************************** Helpers ***********************************************************************/ template class GuiElementBase : public Object, public IGuiGraphicsElement, public Description { protected: Ptr renderer; compositions::GuiGraphicsComposition* ownerComposition = nullptr; void SetOwnerComposition(compositions::GuiGraphicsComposition* composition)override { ownerComposition = composition; } void InvokeOnCompositionStateChanged() { if (ownerComposition) { compositions::InvokeOnCompositionStateChanged(ownerComposition); } } void InvokeOnElementStateChanged() { if (renderer) { renderer->OnElementStateChanged(); } InvokeOnCompositionStateChanged(); } public: static TElement* Create() { auto rendererFactory = GetGuiGraphicsResourceManager()->GetRendererFactory(TElement::GetElementType()); CHECK_ERROR(rendererFactory != nullptr, L"This element is not supported by the selected renderer."); auto element = new TElement; element->renderer = rendererFactory->Create(); element->renderer->Initialize(element); return element; } ~GuiElementBase() { if (renderer) { renderer->Finalize(); } } IGuiGraphicsRenderer* GetRenderer()override { return renderer.Obj(); } compositions::GuiGraphicsComposition* GetOwnerComposition()override { return ownerComposition; } }; #define DEFINE_GUI_GRAPHICS_ELEMENT(TELEMENT, ELEMENT_TYPE_NAME)\ friend class GuiElementBase;\ public:\ static vint GetElementType()\ {\ static vint elementType = -1;\ if (elementType == -1)\ {\ auto manager = GetGuiGraphicsResourceManager();\ CHECK_ERROR(manager != nullptr, L"SetGuiGraphicsResourceManager must be called before registering element types.");\ elementType = manager->RegisterElementType(WString::Unmanaged(ELEMENT_TYPE_NAME));\ }\ return elementType;\ }\ #define DEFINE_GUI_GRAPHICS_RENDERER(TELEMENT, TRENDERER, TTARGET)\ public:\ class Factory : public Object, public IGuiGraphicsRendererFactory\ {\ public:\ IGuiGraphicsRenderer* Create()\ {\ TRENDERER* renderer=new TRENDERER;\ renderer->factory=this;\ renderer->element=0;\ renderer->renderTarget=0;\ return renderer;\ }\ };\ protected:\ IGuiGraphicsRendererFactory* factory;\ TELEMENT* element;\ TTARGET* renderTarget;\ Size minSize;\ public:\ static void Register()\ {\ auto manager = GetGuiGraphicsResourceManager();\ CHECK_ERROR(manager != nullptr, L"SetGuiGraphicsResourceManager must be called before registering element renderers.");\ manager->RegisterRendererFactory(TELEMENT::GetElementType(), new TRENDERER::Factory);\ }\ IGuiGraphicsRendererFactory* GetFactory()override\ {\ return factory;\ }\ void Initialize(IGuiGraphicsElement* _element)override\ {\ element=dynamic_cast(_element);\ InitializeInternal();\ }\ void Finalize()override\ {\ FinalizeInternal();\ }\ void SetRenderTarget(IGuiGraphicsRenderTarget* _renderTarget)override\ {\ TTARGET* oldRenderTarget=renderTarget;\ renderTarget=dynamic_cast(_renderTarget);\ RenderTargetChangedInternal(oldRenderTarget, renderTarget);\ }\ Size GetMinSize()override\ {\ return minSize;\ }\ #define DEFINE_CACHED_RESOURCE_ALLOCATOR(TKEY, TVALUE)\ public:\ static const vint DeadPackageMax=32;\ struct Package\ {\ TVALUE resource;\ vint counter;\ bool operator==(const Package& package)const{return false;}\ bool operator!=(const Package& package)const{return true;}\ };\ struct DeadPackage\ {\ TKEY key;\ TVALUE value;\ bool operator==(const DeadPackage& package)const{return false;}\ bool operator!=(const DeadPackage& package)const{return true;}\ };\ Dictionary aliveResources;\ List deadResources;\ public:\ TVALUE Create(const TKEY& key)\ {\ vint index=aliveResources.Keys().IndexOf(key);\ if(index!=-1)\ {\ Package package=aliveResources.Values().Get(index);\ package.counter++;\ aliveResources.Set(key, package);\ return package.resource;\ }\ TVALUE resource;\ for(vint i=0;iIGuiAltAction is the handler when an alt-combined shortcut key is activated. class IGuiAltAction : public virtual IDescriptable { public: /// The identifier for this service. static const wchar_t* const Identifier; static bool IsLegalAlt(const WString& alt); virtual const WString& GetAlt() = 0; virtual bool IsAltEnabled() = 0; virtual bool IsAltAvailable() = 0; virtual GuiGraphicsComposition* GetAltComposition() = 0; virtual IGuiAltActionHost* GetActivatingAltHost() = 0; virtual void OnActiveAlt() = 0; }; /// IGuiAltActionContainer enumerates multiple . class IGuiAltActionContainer : public virtual IDescriptable { public: /// The identifier for this service. static const wchar_t* const Identifier; virtual vint GetAltActionCount() = 0; virtual IGuiAltAction* GetAltAction(vint index) = 0; }; /// IGuiAltActionHost is an alt-combined shortcut key host. A host can also be entered or leaved, with multiple sub actions enabled or disabled. class IGuiAltActionHost : public virtual IDescriptable { public: /// The identifier for this service. static const wchar_t* const Identifier; static void CollectAltActionsFromControl(controls::GuiControl* control, bool includeThisControl, collections::Group& actions); virtual GuiGraphicsComposition* GetAltComposition() = 0; virtual IGuiAltActionHost* GetPreviousAltHost() = 0; virtual void OnActivatedAltHost(IGuiAltActionHost* previousHost) = 0; virtual void OnDeactivatedAltHost() = 0; virtual void CollectAltActions(collections::Group& actions) = 0; }; /// Default implementation for class GuiAltActionHostBase : public virtual IGuiAltActionHost { private: GuiGraphicsComposition* composition = nullptr; controls::GuiControl* control = nullptr; bool includeControl = true; IGuiAltActionHost* previousHost = nullptr; protected: void SetAltComposition(GuiGraphicsComposition* _composition); void SetAltControl(controls::GuiControl* _control, bool _includeControl); public: GuiGraphicsComposition* GetAltComposition()override; IGuiAltActionHost* GetPreviousAltHost()override; void OnActivatedAltHost(IGuiAltActionHost* _previousHost)override; void OnDeactivatedAltHost()override; void CollectAltActions(collections::Group& actions)override; }; /*********************************************************************** Alt-Combined Shortcut Key Interfaces Helpers ***********************************************************************/ class GuiAltActionManager : public Object { typedef collections::Dictionary AltActionMap; typedef collections::Dictionary AltControlMap; protected: controls::GuiControlHost* controlHost = nullptr; IGuiAltActionHost* currentAltHost = nullptr; AltActionMap currentActiveAltActions; AltControlMap currentActiveAltTitles; WString currentAltPrefix; VKEY supressAltKey = VKEY::KEY_UNKNOWN; void EnterAltHost(IGuiAltActionHost* host); void LeaveAltHost(); bool EnterAltKey(wchar_t key); void LeaveAltKey(); void CreateAltTitles(const collections::Group& actions); vint FilterTitles(); void ClearAltHost(); public: GuiAltActionManager(controls::GuiControlHost* _controlHost); ~GuiAltActionManager(); void CloseAltHost(); bool KeyDown(const NativeWindowKeyInfo& info); bool KeyUp(const NativeWindowKeyInfo& info); bool SysKeyDown(const NativeWindowKeyInfo& info); bool SysKeyUp(const NativeWindowKeyInfo& info); bool Char(const NativeWindowCharInfo& info); }; } } } #endif /*********************************************************************** .\GRAPHICSHOST\GUIGRAPHICSHOST_SHORTCUTKEY.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Graphics Composition Host Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_HOST_GUIGRAPHICSHOST_SHORTCUTKEY #define VCZH_PRESENTATION_HOST_GUIGRAPHICSHOST_SHORTCUTKEY namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Shortcut Key Manager ***********************************************************************/ class IGuiShortcutKeyManager; /// Shortcut key item. class IGuiShortcutKeyItem : public virtual IDescriptable, public Description { public: /// Shortcut key executed event. GuiNotifyEvent Executed; /// Get the associated object. /// The associated shortcut key manager. virtual IGuiShortcutKeyManager* GetManager()=0; /// Get the name represents the shortcut key combination for this item. /// The name represents the shortcut key combination for this item. virtual WString GetName()=0; }; /// Shortcut key manager item. class IGuiShortcutKeyManager : public virtual IDescriptable, public Description { public: /// Get the number of shortcut key items that already attached to the manager. /// T number of shortcut key items that already attached to the manager. virtual vint GetItemCount()=0; /// Get the associated with the index. /// The shortcut key item. /// The index. virtual IGuiShortcutKeyItem* GetItem(vint index)=0; /// Execute shortcut key items using a key event info. /// Returns true if at least one shortcut key item is executed. /// The key event info. virtual bool Execute(const NativeWindowKeyInfo& info)=0; }; /*********************************************************************** Shortcut Key Manager Helpers ***********************************************************************/ class GuiShortcutKeyManager; class GuiShortcutKeyItem : public Object, public IGuiShortcutKeyItem { protected: GuiShortcutKeyManager* shortcutKeyManager; bool ctrl; bool shift; bool alt; VKEY key; void AttachManager(GuiShortcutKeyManager* manager); void DetachManager(GuiShortcutKeyManager* manager); public: GuiShortcutKeyItem(GuiShortcutKeyManager* _shortcutKeyManager, bool _ctrl, bool _shift, bool _alt, VKEY _key); ~GuiShortcutKeyItem(); IGuiShortcutKeyManager* GetManager()override; WString GetName()override; bool CanActivate(const NativeWindowKeyInfo& info); bool CanActivate(bool _ctrl, bool _shift, bool _alt, VKEY _key); }; /// A default implementation for . class GuiShortcutKeyManager : public Object, public IGuiShortcutKeyManager, public Description { typedef collections::List> ShortcutKeyItemList; protected: ShortcutKeyItemList shortcutKeyItems; public: /// Create the shortcut key manager. GuiShortcutKeyManager(); ~GuiShortcutKeyManager(); vint GetItemCount()override; IGuiShortcutKeyItem* GetItem(vint index)override; bool Execute(const NativeWindowKeyInfo& info)override; /// Create a shortcut key item using a key combination. If the item for the key combination exists, this function returns the item that is created before. /// The created shortcut key item. /// Set to true if the CTRL key is required. /// Set to true if the SHIFT key is required. /// Set to true if the ALT key is required. /// The non-control key. IGuiShortcutKeyItem* CreateShortcut(bool ctrl, bool shift, bool alt, VKEY key); /// Destroy a shortcut key item using a key combination /// Returns true if the manager destroyed a existing shortcut key item. /// Set to true if the CTRL key is required. /// Set to true if the SHIFT key is required. /// Set to true if the ALT key is required. /// The non-control key. bool DestroyShortcut(bool ctrl, bool shift, bool alt, VKEY key); /// Get a shortcut key item using a key combination. If the item for the key combination does not exist, this function returns null. /// The shortcut key item. /// Set to true if the CTRL key is required. /// Set to true if the SHIFT key is required. /// Set to true if the ALT key is required. /// The non-control key. IGuiShortcutKeyItem* TryGetShortcut(bool ctrl, bool shift, bool alt, VKEY key); }; } } } #endif /*********************************************************************** .\GRAPHICSHOST\GUIGRAPHICSHOST_TAB.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Graphics Composition Host Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_HOST_GUIGRAPHICSHOST_TAB #define VCZH_PRESENTATION_HOST_GUIGRAPHICSHOST_TAB namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Tab-Combined Shortcut Key Interfaces ***********************************************************************/ /// IGuiTabAction is the handler when an tab-combined shortcut key is activated. class IGuiTabAction : public virtual IDescriptable { public: /// The identifier for this service. static const wchar_t* const Identifier; virtual bool GetAcceptTabInput() = 0; virtual vint GetTabPriority() = 0; virtual bool IsTabEnabled() = 0; virtual bool IsTabAvailable() = 0; }; /*********************************************************************** Tab-Combined Shortcut Key Interfaces Helpers ***********************************************************************/ class GuiTabActionManager : public Object { using ControlList = collections::List; protected: controls::GuiControlHost* controlHost = nullptr; ControlList controlsInOrder; bool available = true; bool supressTabOnce = false; void BuildControlList(); controls::GuiControl* GetNextFocusControl(controls::GuiControl* focusedControl, vint offset); public: GuiTabActionManager(controls::GuiControlHost* _controlHost); ~GuiTabActionManager(); void InvalidateTabOrderCache(); bool KeyDown(const NativeWindowKeyInfo& info, GuiGraphicsComposition* focusedComposition); bool Char(const NativeWindowCharInfo& info); }; } } } #endif /*********************************************************************** .\GRAPHICSHOST\GUIGRAPHICSHOST.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Graphics Composition Host Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_HOST_GUIGRAPHICSHOST #define VCZH_PRESENTATION_HOST_GUIGRAPHICSHOST namespace vl { namespace presentation { namespace controls { class GuiWindow; } namespace compositions { /*********************************************************************** Animation ***********************************************************************/ /// /// Represents a timer callback object. /// class IGuiGraphicsTimerCallback : public virtual IDescriptable, public Description { public: /// Called periodically. /// Returns false to indicate that this callback need to be removed. virtual bool Play() = 0; }; /// /// Timer callback manager. /// class GuiGraphicsTimerManager : public Object, public Description { typedef collections::List> CallbackList; protected: CallbackList callbacks; public: GuiGraphicsTimerManager(); ~GuiGraphicsTimerManager(); /// Add a new callback. /// The new callback to add. void AddCallback(Ptr callback); /// Called periodically. void Play(); }; /*********************************************************************** Host ***********************************************************************/ /// /// GuiGraphicsHost hosts an in an . The composition will fill the whole window. /// class GuiGraphicsHost : public Object, private INativeWindowListener, private INativeControllerListener, public Description { typedef collections::List CompositionList; typedef GuiGraphicsComposition::GraphicsHostRecord HostRecord; typedef collections::Pair ProcKey; typedef collections::List> ProcList; typedef collections::Dictionary> ProcMap; public: static const vuint64_t CaretInterval = 500; protected: HostRecord hostRecord; bool supressPaint = false; bool needRender = true; ProcList afterRenderProcs; ProcMap afterRenderKeyedProcs; GuiAltActionManager* altActionManager = nullptr; GuiTabActionManager* tabActionManager = nullptr; IGuiShortcutKeyManager* shortcutKeyManager = nullptr; controls::GuiControlHost* controlHost = nullptr; GuiWindowComposition* windowComposition = nullptr; GuiGraphicsComposition* focusedComposition = nullptr; NativeSize previousClientSize; Size minSize; Point caretPoint; vuint64_t lastCaretTime = 0; GuiGraphicsTimerManager timerManager; GuiGraphicsComposition* mouseCaptureComposition = nullptr; CompositionList mouseEnterCompositions; void RefreshRelatedHostRecord(INativeWindow* nativeWindow); void DisconnectCompositionInternal(GuiGraphicsComposition* composition); void MouseCapture(const NativeWindowMouseInfo& info); void MouseUncapture(const NativeWindowMouseInfo& info); void OnCharInput(const NativeWindowCharInfo& info, GuiGraphicsComposition* composition, GuiCharEvent GuiGraphicsEventReceiver::* eventReceiverEvent); void OnKeyInput(const NativeWindowKeyInfo& info, GuiGraphicsComposition* composition, GuiKeyEvent GuiGraphicsEventReceiver::* eventReceiverEvent); void RaiseMouseEvent(GuiMouseEventArgs& arguments, GuiGraphicsComposition* composition, GuiMouseEvent GuiGraphicsEventReceiver::* eventReceiverEvent); void OnMouseInput(const NativeWindowMouseInfo& info, GuiMouseEvent GuiGraphicsEventReceiver::* eventReceiverEvent); void RecreateRenderTarget(); private: INativeWindowListener::HitTestResult HitTest(NativePoint location)override; void Moving(NativeRect& bounds, bool fixSizeOnly, bool draggingBorder)override; void Moved()override; void DpiChanged()override; void Paint()override; void LeftButtonDown(const NativeWindowMouseInfo& info)override; void LeftButtonUp(const NativeWindowMouseInfo& info)override; void LeftButtonDoubleClick(const NativeWindowMouseInfo& info)override; void RightButtonDown(const NativeWindowMouseInfo& info)override; void RightButtonUp(const NativeWindowMouseInfo& info)override; void RightButtonDoubleClick(const NativeWindowMouseInfo& info)override; void MiddleButtonDown(const NativeWindowMouseInfo& info)override; void MiddleButtonUp(const NativeWindowMouseInfo& info)override; void MiddleButtonDoubleClick(const NativeWindowMouseInfo& info)override; void HorizontalWheel(const NativeWindowMouseInfo& info)override; void VerticalWheel(const NativeWindowMouseInfo& info)override; void MouseMoving(const NativeWindowMouseInfo& info)override; void MouseEntered()override; void MouseLeaved()override; void KeyDown(const NativeWindowKeyInfo& info)override; void KeyUp(const NativeWindowKeyInfo& info)override; void SysKeyDown(const NativeWindowKeyInfo& info)override; void SysKeyUp(const NativeWindowKeyInfo& info)override; void Char(const NativeWindowCharInfo& info)override; void GlobalTimer()override; public: GuiGraphicsHost(controls::GuiControlHost* _controlHost, GuiGraphicsComposition* boundsComposition); ~GuiGraphicsHost(); /// Get the associated window. /// The associated window. INativeWindow* GetNativeWindow(); /// Associate a window. A will fill and appear in the window. /// The window to associated. void SetNativeWindow(INativeWindow* _nativeWindow); /// Get the main . If a window is associated, everything that put into the main composition will be shown in the window. /// The main compositoin. GuiGraphicsComposition* GetMainComposition(); /// Render the main composition and all content to the associated window. /// Set to true to force updating layout and then render. void Render(bool forceUpdate); /// Request a rendering void RequestRender(); /// Invoke a specified function after rendering. /// The specified function. /// A key to cancel a previous binded key if not null. void InvokeAfterRendering(const Func& proc, ProcKey key = { nullptr,-1 }); /// Invalidte the internal tab order control list. Next time when TAB is pressed it will be rebuilt. void InvalidateTabOrderCache(); /// Get the attached with this graphics host. /// The shortcut key manager. IGuiShortcutKeyManager* GetShortcutKeyManager(); /// Attach or detach the associated with this graphics host. When this graphics host is disposing, the associated shortcut key manager will be deleted if exists. /// The shortcut key manager. Set to null to detach the previous shortcut key manager from this graphics host. void SetShortcutKeyManager(IGuiShortcutKeyManager* value); /// Set the focus composition. A focused composition will receive keyboard messages. /// Returns true if this operation succeeded. /// The composition to set focus. This composition should be or in the main composition. bool SetFocus(GuiGraphicsComposition* composition); /// Get the focus composition. A focused composition will receive keyboard messages. /// The focus composition. GuiGraphicsComposition* GetFocusedComposition(); /// Get the caret point. A caret point is the position to place the edit box of the activated input method editor. /// The caret point. Point GetCaretPoint(); /// Set the caret point. A caret point is the position to place the edit box of the activated input method editor. /// The caret point. /// The point space. If this argument is null, the "value" argument will use the point space of the client area in the main composition. void SetCaretPoint(Point value, GuiGraphicsComposition* referenceComposition=0); /// Get the timer manager. /// The timer manager. GuiGraphicsTimerManager* GetTimerManager(); /// Notify that a composition is going to disconnect from this graphics host. Generally this happens when a composition's parent line changes. /// The composition to disconnect void DisconnectComposition(GuiGraphicsComposition* composition); }; } } } #endif /*********************************************************************** .\RESOURCES\GUIRESOURCE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Resource Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_RESOURCES_GUIRESOURCE #define VCZH_PRESENTATION_RESOURCES_GUIRESOURCE namespace vl { namespace workflow { class IWfCompilerCallback; } namespace presentation { class GuiResourceItem; class GuiResourceFolder; class GuiResource; /*********************************************************************** Helper Functions ***********************************************************************/ /// Get the folder path from a file path. The result folder path is ended with a separator. /// The folder path. /// The file path. extern WString GetFolderPath(const WString& filePath); /// Get the file name from a file path. /// The file name. /// The file path. extern WString GetFileName(const WString& filePath); /// Load a text file. /// Returns true if the operation succeeded. /// The text file path. /// The text file content, if succeeded. extern bool LoadTextFile(const WString& filePath, WString& text); /// Test is a text a resource url and extract the protocol and the path. /// Returns true if the text is a resource url. /// The text. /// The extracted protocol. /// The extracted path. extern bool IsResourceUrl(const WString& text, WString& protocol, WString& path); extern void HexToBinary(stream::IStream& binaryStream, const WString& hexText); extern WString BinaryToHex(stream::IStream& binaryStream); /*********************************************************************** Global String Key ***********************************************************************/ struct GlobalStringKey { public: static GlobalStringKey Empty; static GlobalStringKey _InferType; static GlobalStringKey _Set; static GlobalStringKey _Ref; static GlobalStringKey _Bind; static GlobalStringKey _Format; static GlobalStringKey _Str; static GlobalStringKey _Eval; static GlobalStringKey _Uri; static GlobalStringKey _ControlTemplate; static GlobalStringKey _ItemTemplate; private: vint key = -1; public: inline vint Compare(GlobalStringKey value)const{ return key - value.key; } GUI_DEFINE_COMPARE_OPERATORS(GlobalStringKey) static GlobalStringKey Get(const WString& string); vint ToKey()const; WString ToString()const; }; /*********************************************************************** Resource Image ***********************************************************************/ /// /// Represnets an image to display. /// class GuiImageData : public Object, public Description { protected: Ptr image; vint frameIndex; public: /// Create an empty image data. GuiImageData(); /// Create an image data with a specified image and a frame index. /// The specified image. /// The specified frame index. GuiImageData(Ptr _image, vint _frameIndex); ~GuiImageData(); /// Get the specified image. /// The specified image. Ptr GetImage(); /// Get the specified frame index. /// The specified frame index. vint GetFrameIndex(); }; /*********************************************************************** Resource String ***********************************************************************/ /// Represents a text resource. class GuiTextData : public Object, public Description { protected: WString text; public: /// Create an empty text data. GuiTextData(); /// Create a text data with a specified text. /// The specified text. GuiTextData(const WString& _text); /// Get the specified text. /// The specified text. WString GetText(); }; /*********************************************************************** Resource Structure ***********************************************************************/ /// Resource node base. class GuiResourceNodeBase : public Object, public Description { friend class GuiResourceFolder; protected: GuiResourceFolder* parent; WString name; WString fileContentPath; WString fileAbsolutePath; public: GuiResourceNodeBase(); ~GuiResourceNodeBase(); /// Get the containing folder. Returns null means that this is the root resource node. /// The containing folder. GuiResourceFolder* GetParent(); /// Get the name of this resource node. /// The name of this resource node . const WString& GetName(); /// Get the resource path of this resource node /// The resource path of this resource node . WString GetResourcePath(); /// Get the file content path of this resource node. When saving the resource, if the path is not empty, the path will be serialized instead of the content. /// The file content path of this resource node . const WString& GetFileContentPath(); /// Get the absolute file content path of this resource node. This path points to an existing file containing the content. /// The file absolute path of this resource node . const WString& GetFileAbsolutePath(); /// Set the file content path of this resource node. /// The file content path of this resource node . /// The file absolute path of this resource node . void SetFileContentPath(const WString& content, const WString& absolute); }; struct GuiResourceLocation { WString resourcePath; WString filePath; GuiResourceLocation() = default; GuiResourceLocation(const WString& _resourcePath, const WString& _filePath); GuiResourceLocation(Ptr node); bool operator==(const GuiResourceLocation& b)const { return resourcePath == b.resourcePath && filePath == b.filePath; } bool operator!=(const GuiResourceLocation& b)const { return !(*this == b); } }; struct GuiResourceTextPos { GuiResourceLocation originalLocation; vint row = glr::ParsingTextPos::UnknownValue; vint column = glr::ParsingTextPos::UnknownValue; GuiResourceTextPos() = default; GuiResourceTextPos(GuiResourceLocation location, glr::ParsingTextPos position); bool operator==(const GuiResourceTextPos& b)const { return originalLocation == b.originalLocation && row == b.row && column == b.column; } bool operator!=(const GuiResourceTextPos& b)const { return !(*this == b); } }; struct GuiResourceError { public: using List = collections::List; GuiResourceLocation location; GuiResourceTextPos position; WString message; GuiResourceError() = default; GuiResourceError(GuiResourceTextPos _position, const WString& _message); GuiResourceError(GuiResourceLocation _location, const WString& _message); GuiResourceError(GuiResourceLocation _location, GuiResourceTextPos _position, const WString& _message); bool operator==(const GuiResourceError& b)const { return location == b.location && position == b.position && message == b.message; } bool operator!=(const GuiResourceError& b)const { return !(*this == b); } static void Transform(GuiResourceLocation _location, GuiResourceError::List& errors, collections::List& parsingErrors); static void Transform(GuiResourceLocation _location, GuiResourceError::List& errors, collections::List& parsingErrors, glr::ParsingTextPos offset); static void Transform(GuiResourceLocation _location, GuiResourceError::List& errors, collections::List& parsingErrors, GuiResourceTextPos offset); static void SortAndLog(List& errors, collections::List& output, const WString& workingDirectory = WString::Empty); }; class DocumentModel; class GuiResourcePathResolver; struct GuiResourcePrecompileContext; struct GuiResourceInitializeContext; class IGuiResourcePrecompileCallback; /// Resource item. class GuiResourceItem : public GuiResourceNodeBase, public Description { friend class GuiResourceFolder; protected: Ptr content; WString typeName; public: /// Create a resource item. GuiResourceItem(); ~GuiResourceItem(); /// Get the type of this resource item. /// The type name. const WString& GetTypeName(); /// Get the contained object for this resource item. /// The contained object. Ptr GetContent(); /// Set the containd object for this resource item. /// The type name of this contained object. /// The contained object. void SetContent(const WString& _typeName, Ptr value); /// Get the contained object as an image. /// The contained object. Ptr AsImage(); /// Get the contained object as an xml. /// The contained object. Ptr AsXml(); /// Get the contained object as a string. /// The contained object. Ptr AsString(); /// Get the contained object as a document model. /// The contained object. Ptr AsDocument(); }; /// Resource folder. A resource folder contains many sub folders and sub items. class GuiResourceFolder : public GuiResourceNodeBase, public Description { protected: typedef collections::Dictionary> ItemMap; typedef collections::Dictionary> FolderMap; typedef collections::List> ItemList; typedef collections::List> FolderList; struct DelayLoading { WString type; WString workingDirectory; Ptr preloadResource; }; typedef collections::List DelayLoadingList; WString importUri; ItemMap items; FolderMap folders; void LoadResourceFolderFromXml(DelayLoadingList& delayLoadings, const WString& containingFolder, Ptr folderXml, GuiResourceError::List& errors); void SaveResourceFolderToXml(Ptr xmlParent); void CollectTypeNames(collections::List& typeNames); void LoadResourceFolderFromBinary(DelayLoadingList& delayLoadings, stream::internal::ContextFreeReader& reader, collections::List& typeNames, GuiResourceError::List& errors); void SaveResourceFolderToBinary(stream::internal::ContextFreeWriter& writer, collections::List& typeNames); void PrecompileResourceFolder(GuiResourcePrecompileContext& context, IGuiResourcePrecompileCallback* callback, GuiResourceError::List& errors); void InitializeResourceFolder(GuiResourceInitializeContext& context, GuiResourceError::List& errors); void ImportFromUri(const WString& uri, GuiResourceTextPos position, GuiResourceError::List& errors); public: /// Create a resource folder. GuiResourceFolder(); ~GuiResourceFolder(); ///Get the import uri for this folder. ///The import uri for this folder. Returns an empty string for non-import folders const WString& GetImportUri(); ///Set the import uri for this folder. ///The import uri for this folder. Set an empty string for non-import folders void SetImportUri(const WString& uri); /// Get all sub items. /// All sub items. const ItemList& GetItems(); /// Get the item of a specified name. /// The item of a specified name. /// The specified name. Ptr GetItem(const WString& name); /// Add a resource item. /// Returns true if this operation succeeded. /// The name of this resource item. /// The resource item. bool AddItem(const WString& name, Ptr item); /// Remove a resource item of a specified name. /// Returns the removed resource item if this operation succeeded. /// The name of this resource item. Ptr RemoveItem(const WString& name); /// Remove all resource item. void ClearItems(); /// Get all sub folders. /// All sub folders. const FolderList& GetFolders(); /// Get the folder of a specified name. /// The folder of a specified name. /// The specified name. Ptr GetFolder(const WString& name); /// Add a resource folder. /// Returns true if this operation succeeded. /// The name of this resource folder. /// The resource folder. bool AddFolder(const WString& name, Ptr folder); /// Remove a resource folder of a specified name. /// Returns the removed resource folder if this operation succeeded. /// The name of this resource folder. Ptr RemoveFolder(const WString& name); /// Remove all resource folders. void ClearFolders(); /// Get a contained resource object using a path like "Packages\Application\Name". /// The containd resource object. /// The path. Ptr GetValueByPath(const WString& path); /// Get a resource folder using a path like "Packages\Application\Name\". /// The resource folder. /// The path. Ptr GetFolderByPath(const WString& path); /// Create a contained resource object using a path like "Packages\Application\Name". /// Returns true if this operation succeeded. /// The path. /// The type name of this contained object. /// The contained object. bool CreateValueByPath(const WString& path, const WString& typeName, Ptr value); }; /*********************************************************************** Resource ***********************************************************************/ enum class GuiResourceUsage { DataOnly, InstanceClass, }; /// Resource metadata. class GuiResourceMetadata : public Object { public: WString name; WString version; collections::List dependencies; void LoadFromXml(Ptr xml, GuiResourceLocation location, GuiResourceError::List& errors); Ptr SaveToXml(); }; /// Resource. A resource is a root resource folder that does not have a name. class GuiResource : public GuiResourceFolder, public Description { protected: WString workingDirectory; Ptr metadata; static void ProcessDelayLoading(Ptr resource, DelayLoadingList& delayLoadings, GuiResourceError::List& errors); public: static const wchar_t* CurrentVersionString; /// Create a resource. GuiResource(); ~GuiResource(); /// Get the metadata of the resource. /// The metadata. Ptr GetMetadata(); /// Get the directory where the resource is load. /// The directory. WString GetWorkingDirectory(); /// Load a resource from an xml file. If the xml file refers other files, they will be loaded as well. /// The loaded resource. /// The xml document. /// The file path of the resource. /// The working directory for loading external resources. /// All collected errors during loading a resource. static Ptr LoadFromXml(Ptr xml, const WString& filePath, const WString& workingDirectory, GuiResourceError::List& errors); /// Load a resource from an xml file. If the xml file refers other files, they will be loaded as well. /// The loaded resource. /// The file path of the xml file. /// All collected errors during loading a resource. static Ptr LoadFromXml(const WString& filePath, GuiResourceError::List& errors); /// Save the resource to xml. /// The xml. Ptr SaveToXml(); /// Load a precompiled resource from a stream. /// The loaded resource. /// The stream. /// All collected errors during loading a resource. static Ptr LoadPrecompiledBinary(stream::IStream& binaryStream, GuiResourceError::List& errors); /// Load a precompiled resource from a stream. This function will hit an assert if there are errors. /// The loaded resource. /// The stream. static Ptr LoadPrecompiledBinary(stream::IStream& binaryStream); /// Save the precompiled resource to a stream. /// The stream. void SavePrecompiledBinary(stream::IStream& binaryStream); /// Precompile this resource to improve performance. /// The resource folder contains all precompiled result. The folder will be added to the resource if there is no error. /// A callback to receive progress. /// All collected errors during precompiling a resource. Ptr Precompile(IGuiResourcePrecompileCallback* callback, GuiResourceError::List& errors); /// Initialize a precompiled resource. /// In which role an application is initializing this resource. /// All collected errors during initializing a resource. void Initialize(GuiResourceUsage usage, GuiResourceError::List& errors); /// Get a contained document model using a path like "Packages\Application\Name". If the path does not exists or the type does not match, an exception will be thrown. /// The containd resource object. /// The path. Ptr GetDocumentByPath(const WString& path); /// Get a contained image using a path like "Packages\Application\Name". If the path does not exists or the type does not match, an exception will be thrown. /// The containd resource object. /// The path. Ptr GetImageByPath(const WString& path); /// Get a contained xml using a path like "Packages\Application\Name". If the path does not exists or the type does not match, an exception will be thrown. /// The containd resource object. /// The path. Ptr GetXmlByPath(const WString& path); /// Get a contained string object using a path like "Packages\Application\Name". If the path does not exists or the type does not match, an exception will be thrown. /// The containd resource object. /// The path. WString GetStringByPath(const WString& path); }; /*********************************************************************** Resource Path Resolver ***********************************************************************/ /// Represents a symbol resolver for loading a resource of a certain protocol. class IGuiResourcePathResolver : public IDescriptable, public Description { public: /// Load a resource when the descriptor is something like a protocol-prefixed uri. /// The loaded resource. Returns null if failed to load. /// The path. virtual Ptr ResolveResource(const WString& path)=0; }; /// Represents an factory. class IGuiResourcePathResolverFactory : public IDescriptable, public Description { public: /// Get the protocol for this resolver. /// The protocol. virtual WString GetProtocol()=0; /// Create an object. /// The created resolver. /// The resource context. /// The working directory context. virtual Ptr CreateResolver(Ptr resource, const WString& workingDirectory)=0; }; /// Represents a symbol resolver for loading a resource. class GuiResourcePathResolver : public Object, public Description { typedef collections::Dictionary> ResolverMap; protected: ResolverMap resolvers; Ptr resource; WString workingDirectory; public: /// Create a resolver. /// The resource context. /// The working directory context. GuiResourcePathResolver(Ptr _resource, const WString& _workingDirectory); ~GuiResourcePathResolver(); /// Load a resource when the descriptor is something like a protocol-prefixed uri. /// The loaded resource. Returns null if failed to load. /// The protocol. /// The path. Ptr ResolveResource(const WString& protocol, const WString& path); }; /*********************************************************************** Resource Type Resolver ***********************************************************************/ class IGuiResourceTypeResolver_Precompile; class IGuiResourceTypeResolver_Initialize; class IGuiResourceTypeResolver_DirectLoadXml; class IGuiResourceTypeResolver_DirectLoadStream; class IGuiResourceTypeResolver_IndirectLoad; /// Represents a symbol type for loading a resource. class IGuiResourceTypeResolver : public virtual IDescriptable, public Description { public: /// Get the type of the resource that load by this resolver. /// The type. virtual WString GetType() = 0; /// Test is this resource able to serialize in an XML resource or not. /// Returns true if this resource is able to serialize in an XML resource. virtual bool XmlSerializable() = 0; /// Test is this resource able to serialize in a precompiled binary resource or not. /// Returns true if this resource is able to serialize in a precompiled binary resource. virtual bool StreamSerializable() = 0; /// Get the precompiler for the type resolver. /// Returns null if the type resolve does not support precompiling. virtual IGuiResourceTypeResolver_Precompile* Precompile(){ return 0; } /// Get the initializer for the type resolver. /// Returns null if the type resolve does not support initializing. virtual IGuiResourceTypeResolver_Initialize* Initialize(){ return 0; } /// Get the object for convert the resource between xml and object. /// Returns null if the type resolver does not have this ability. virtual IGuiResourceTypeResolver_DirectLoadXml* DirectLoadXml(){ return 0; } /// Get the object for convert the resource between stream and object. /// Returns null if the type resolver does not have this ability. virtual IGuiResourceTypeResolver_DirectLoadStream* DirectLoadStream(){ return 0; } /// Get the object for convert the resource between the preload type and the current type. /// Returns null if the type resolver does not have this ability. virtual IGuiResourceTypeResolver_IndirectLoad* IndirectLoad(){ return 0; } }; /// Provide a context for resource precompiling struct GuiResourcePrecompileContext { typedef collections::Dictionary, Ptr> PropertyMap; /// Progress callback. workflow::IWfCompilerCallback* compilerCallback = nullptr; /// The folder to contain compiled objects. Ptr targetFolder; /// The root resource object. GuiResource* rootResource = nullptr; /// Indicate the pass index of this precompiling pass. vint passIndex = -1; /// The path resolver. This is only for delay load resource. Ptr resolver; /// Additional properties for resource item contents PropertyMap additionalProperties; }; /// /// Represents a precompiler for resources of a specified type. /// Current resources that needs precompiling: /// Workflow: /// Pass 0: Collect workflow scripts / Compile localized strings / Generate ClassNameRecord /// Pass 1: Compile workflow scripts /// Instance: /// Pass 2: Collect instance types / Compile animation types /// Pass 3: Compile /// Pass 4: Generate instance types with event handler functions to TemporaryClass / Compile animation types /// Pass 5: Compile /// Pass 6: Generate instance types with everything to InstanceCtor / Compile animation types /// Pass 7: Compile /// class IGuiResourceTypeResolver_Precompile : public virtual IDescriptable, public Description { public: enum PassNames { Workflow_Collect = 0, Workflow_Compile = 1, Workflow_Max = Workflow_Compile, Instance_CollectInstanceTypes = 2, Instance_CompileInstanceTypes = 3, Instance_CollectEventHandlers = 4, Instance_CompileEventHandlers = 5, Instance_GenerateInstanceClass = 6, Instance_CompileInstanceClass = 7, Instance_Max = Instance_CompileInstanceClass, }; enum PassSupport { NotSupported, PerResource, PerPass, }; /// Get the maximum pass index that the precompiler needs. /// Returns the maximum pass index. The precompiler doesn't not need to response to every pass. virtual vint GetMaxPassIndex() = 0; /// Get how this resolver supports precompiling. /// The pass index. /// Returns how this resolver supports precompiling. virtual PassSupport GetPassSupport(vint passIndex) = 0; /// Precompile the resource item. /// The resource to precompile. /// The context for precompiling. /// All collected errors during loading a resource. virtual void PerResourcePrecompile(Ptr resource, GuiResourcePrecompileContext& context, GuiResourceError::List& errors) = 0; /// Precompile for a pass. /// The context for precompiling. /// All collected errors during loading a resource. virtual void PerPassPrecompile(GuiResourcePrecompileContext& context, GuiResourceError::List& errors) = 0; }; class IGuiResourcePrecompileCallback : public virtual IDescriptable, public Description { public: virtual workflow::IWfCompilerCallback* GetCompilerCallback() = 0; virtual void OnPerPass(vint passIndex) = 0; virtual void OnPerResource(vint passIndex, Ptr resource) = 0; }; /// Provide a context for resource initializing struct GuiResourceInitializeContext : GuiResourcePrecompileContext { GuiResourceUsage usage; }; /// /// Represents a precompiler for resources of a specified type. /// Current resources that needs precompiling: /// Pass 0: Script (initialize view model scripts) /// Pass 1: Script (initialize shared scripts) /// Pass 2: Script (initialize instance scripts) /// class IGuiResourceTypeResolver_Initialize : public virtual IDescriptable, public Description { public: /// Get the maximum pass index that the initializer needs. /// Returns the maximum pass index. The initializer doesn't not need to response to every pass. virtual vint GetMaxPassIndex() = 0; /// Initialize the resource item. /// The resource to initializer. /// The context for initializing. /// All collected errors during initializing a resource. virtual void Initialize(Ptr resource, GuiResourceInitializeContext& context, GuiResourceError::List& errors) = 0; }; /// Represents a symbol type for loading a resource without a preload type. class IGuiResourceTypeResolver_DirectLoadXml : public virtual IDescriptable, public Description { public: /// Serialize a resource to an xml element. This function is called if this type resolver does not have a preload type. /// The serialized xml element. /// The resource item containing the resource. /// The object to serialize. virtual Ptr Serialize(Ptr resource, Ptr content) = 0; /// Load a resource for a type inside an xml element. /// The resource. /// The resource item containing the resource. /// The xml element. /// All collected errors during loading a resource. virtual Ptr ResolveResource(Ptr resource, Ptr element, GuiResourceError::List& errors) = 0; /// Load a resource for a type from a file. /// The resource. /// The resource item containing the resource. /// The file path. /// All collected errors during loading a resource. virtual Ptr ResolveResource(Ptr resource, const WString& path, GuiResourceError::List& errors) = 0; }; /// Represents a symbol type for loading a resource without a preload type. class IGuiResourceTypeResolver_DirectLoadStream : public virtual IDescriptable, public Description { public: /// Serialize a precompiled resource to a stream. /// The resource item containing the resource. /// The content to serialize. /// The stream. virtual void SerializePrecompiled(Ptr resource, Ptr content, stream::IStream& binaryStream) = 0; /// Load a precompiled resource from a stream. /// The resource. /// The resource item containing the resource. /// The stream. /// All collected errors during loading a resource. virtual Ptr ResolveResourcePrecompiled(Ptr resource, stream::IStream& binaryStream, GuiResourceError::List& errors) = 0; }; /// Represents a symbol type for loading a resource with a preload type. class IGuiResourceTypeResolver_IndirectLoad : public virtual IDescriptable, public Description { public: /// Get the preload type to load the resource before loading itself. /// The preload type. Returns an empty string to indicate that there is no preload type for this resolver. virtual WString GetPreloadType() = 0; /// Get the delay load feature for this resolver. /// Returns true if this type need to delay load. virtual bool IsDelayLoad() = 0; /// Serialize a resource to a resource in preload type. /// The serialized resource. /// The resource item containing the resource. /// The object to serialize. virtual Ptr Serialize(Ptr resource, Ptr content) = 0; /// Load a resource for a type from a resource loaded by the preload type resolver. /// The resource. /// The resource item containing the resource. /// The path resolver. This is only for delay load resource. /// All collected errors during loading a resource. virtual Ptr ResolveResource(Ptr resource, Ptr resolver, GuiResourceError::List& errors) = 0; }; /*********************************************************************** Resource Resolver Manager ***********************************************************************/ /// A resource resolver manager. class IGuiResourceResolverManager : public IDescriptable, public Description { public: /// Get the for a protocol. /// The factory. /// The protocol. virtual IGuiResourcePathResolverFactory* GetPathResolverFactory(const WString& protocol) = 0; /// Set the for a protocol. /// Returns true if this operation succeeded. /// The factory. virtual bool SetPathResolverFactory(Ptr factory) = 0; /// Get the for a resource type. /// The resolver. /// The resource type. virtual IGuiResourceTypeResolver* GetTypeResolver(const WString& type) = 0; /// Set the for a resource type. /// Returns true if this operation succeeded. /// The resolver. virtual bool SetTypeResolver(Ptr resolver) = 0; /// Get the maximum precompiling pass index. /// The maximum precompiling pass index. virtual vint GetMaxPrecompilePassIndex() = 0; /// Get the maximum initializing pass index. /// The maximum initializing pass index. virtual vint GetMaxInitializePassIndex() = 0; /// Get names of all per resource resolvers for a pass. /// The pass index. /// Names of resolvers virtual void GetPerResourceResolverNames(vint passIndex, collections::List& names) = 0; /// Get names of all per pass resolvers for a pass. /// The pass index. /// Names of resolvers virtual void GetPerPassResolverNames(vint passIndex, collections::List& names) = 0; }; extern IGuiResourceResolverManager* GetResourceResolverManager(); extern void DecompressStream(const char** buffer, bool compress, vint rows, vint block, vint remain, stream::IStream& outputStream); } } #endif /*********************************************************************** .\CONTROLS\TEMPLATES\GUICONTROLSHARED.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Template System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_TEMPLATES_GUICONTROLSHARED #define VCZH_PRESENTATION_CONTROLS_TEMPLATES_GUICONTROLSHARED namespace vl { namespace presentation { namespace controls { class GuiControlHost; class GuiCustomControl; /// The visual state for button. enum class ButtonState { /// Normal state. Normal, /// Active state (when the cursor is hovering on a button). Active, /// Pressed state (when the buttin is being pressed). Pressed, }; /// Represents the sorting state of list view items related to this column. enum class ColumnSortingState { /// Not sorted. NotSorted, /// Ascending. Ascending, /// Descending. Descending, }; /// Represents the order of tab pages. enum class TabPageOrder { /// Unknown. Unknown, /// Left to right. LeftToRight, /// Right to left. RightToLeft, /// Top to bottom. TopToBottom, /// Bottom to top. BottomToTop, }; /// A command executor for the combo box to change the control state. class ITextBoxCommandExecutor : public virtual IDescriptable, public Description { public: /// Override the text content in the control. /// The new text content. virtual void UnsafeSetText(const WString& value) = 0; }; /// A command executor for the style controller to change the control state. class IScrollCommandExecutor : public virtual IDescriptable, public Description { public: /// Do small decrement. virtual void SmallDecrease() = 0; /// Do small increment. virtual void SmallIncrease() = 0; /// Do big decrement. virtual void BigDecrease() = 0; /// Do big increment. virtual void BigIncrease() = 0; /// Change to total size of the scroll. /// The total size. virtual void SetTotalSize(vint value) = 0; /// Change to page size of the scroll. /// The page size. virtual void SetPageSize(vint value) = 0; /// Change to position of the scroll. /// The position. virtual void SetPosition(vint value) = 0; }; /// A command executor for the style controller to change the control state. class ITabCommandExecutor : public virtual IDescriptable, public Description { public: /// Select a tab page. /// The specified position for the tab page. /// Set to true to set focus to the tab control. virtual void ShowTab(vint index, bool setFocus) = 0; }; /// A command executor for the style controller to change the control state. class IDatePickerCommandExecutor : public virtual IDescriptable, public Description { public: /// Called when the date has been changed. virtual void NotifyDateChanged() = 0; /// Called when navigated to a date. virtual void NotifyDateNavigated() = 0; /// Called when selected a date. virtual void NotifyDateSelected() = 0; }; /// A command executor for the style controller to change the control state. class IRibbonGroupCommandExecutor : public virtual IDescriptable, public Description { public: /// Called when the expand button is clicked. virtual void NotifyExpandButtonClicked() = 0; }; /// A command executor for the style controller to change the control state. class IRibbonGalleryCommandExecutor : public virtual IDescriptable, public Description { public: /// Called when the scroll up button is clicked. virtual void NotifyScrollUp() = 0; /// Called when the scroll down button is clicked. virtual void NotifyScrollDown() = 0; /// Called when the dropdown button is clicked. virtual void NotifyDropdown() = 0; }; class GuiInstanceRootObject; /// /// Represnets a component. /// class GuiComponent : public Object, public Description { public: GuiComponent(); ~GuiComponent(); virtual void Attach(GuiInstanceRootObject* rootObject); virtual void Detach(GuiInstanceRootObject* rootObject); }; /*********************************************************************** Animation ***********************************************************************/ /// Animation. class IGuiAnimation abstract : public virtual IDescriptable, public Description { public: /// Called when the animation is about to play the first frame. virtual void Start() = 0; /// Called when the animation is about to pause. virtual void Pause() = 0; /// Called when the animation is about to resume. virtual void Resume() = 0; /// Play the animation. The animation should calculate the time itself to determine the content of the current state of animating objects. virtual void Run() = 0; /// Test if the animation has ended. /// Returns true if the animation has ended. virtual bool GetStopped() = 0; /// Create a finite animation. /// Returns the created animation. /// The animation callback for each frame. /// The length of the animation. static Ptr CreateAnimation(const Func& run, vuint64_t milliseconds); /// Create an infinite animation. /// Returns the created animation. /// The animation callback for each frame. static Ptr CreateAnimation(const Func& run); }; /*********************************************************************** Root Object ***********************************************************************/ class RootObjectTimerCallback; /// Represnets a root GUI object. class GuiInstanceRootObject abstract : public Description { friend class RootObjectTimerCallback; typedef collections::List> SubscriptionList; protected: Ptr resourceResolver; SubscriptionList subscriptions; collections::SortedList components; Ptr timerCallback; collections::SortedList> runningAnimations; collections::SortedList> pendingAnimations; bool finalized = false; virtual controls::GuiControlHost* GetControlHostForInstance() = 0; void InstallTimerCallback(controls::GuiControlHost* controlHost); bool UninstallTimerCallback(controls::GuiControlHost* controlHost); void OnControlHostForInstanceChanged(); void StartPendingAnimations(); public: GuiInstanceRootObject(); ~GuiInstanceRootObject(); /// Clear all subscriptions and components. void FinalizeInstance(); /// Test has the object been finalized. /// Returns true if this object has been finalized. bool IsFinalized(); void FinalizeInstanceRecursively(templates::GuiTemplate* thisObject); void FinalizeInstanceRecursively(GuiCustomControl* thisObject); void FinalizeInstanceRecursively(GuiControlHost* thisObject); void FinalizeGeneralInstance(GuiInstanceRootObject* thisObject); /// Set the resource resolver to connect the current root object to the resource creating it. /// The resource resolver void SetResourceResolver(Ptr resolver); /// Resolve a resource using the current resource resolver. /// The loaded resource. Returns null if failed to load. /// The protocol. /// The path. /// Set to true and it will throw an exception if the resource doesn't exist. Ptr ResolveResource(const WString& protocol, const WString& path, bool ensureExist); /// Add a subscription. When this control host is disposing, all attached subscriptions will be deleted. /// Returns null if this operation failed. /// The subscription to test. Ptr AddSubscription(Ptr subscription); /// Clear all subscriptions. void UpdateSubscriptions(); /// Add a component. When this control host is disposing, all attached components will be deleted. /// Returns true if this operation succeeded. /// The component to add. bool AddComponent(GuiComponent* component); /// Add a control host as a component. When this control host is disposing, all attached components will be deleted. /// Returns true if this operation succeeded. /// The controlHost to add. bool AddControlHostComponent(GuiControlHost* controlHost); /// Add an animation. The animation will be paused if the root object is removed from a window. /// Returns true if this operation succeeded. /// The animation. bool AddAnimation(Ptr animation); /// Kill an animation. /// Returns true if this operation succeeded. /// The animation. bool KillAnimation(Ptr animation); }; } } } #endif /*********************************************************************** .\CONTROLS\TEMPLATES\GUIANIMATION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Template System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_TEMPLATES_GUIANIMATION #define VCZH_PRESENTATION_CONTROLS_TEMPLATES_GUIANIMATION namespace vl { namespace presentation { namespace controls { class IGuiAnimationCoroutine : public Object, public Description { public: class IImpl : public virtual IGuiAnimation, public Description { public: virtual void OnPlayAndWait(Ptr animation) = 0; virtual void OnPlayInGroup(Ptr animation, vint groupId) = 0; virtual void OnWaitForGroup(vint groupId) = 0; }; typedef Func(IImpl*)> Creator; static void WaitAndPause(IImpl* impl, vuint64_t milliseconds); static void PlayAndWaitAndPause(IImpl* impl, Ptr animation); static void PlayInGroupAndPause(IImpl* impl, Ptr animation, vint groupId); static void WaitForGroupAndPause(IImpl* impl, vint groupId); static void ReturnAndExit(IImpl* impl); static Ptr Create(const Creator& creator); }; } } } #endif /*********************************************************************** .\RESOURCES\GUIDOCUMENT.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Resource Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_RESOURCES_GUIDOCUMENT #define VCZH_PRESENTATION_RESOURCES_GUIDOCUMENT namespace vl { namespace presentation { class DocumentTextRun; class DocumentStylePropertiesRun; class DocumentStyleApplicationRun; class DocumentHyperlinkRun; class DocumentImageRun; class DocumentEmbeddedObjectRun; class DocumentParagraphRun; /*********************************************************************** Rich Content Document (style) ***********************************************************************/ struct DocumentFontSize { double size = 0; bool relative = false; DocumentFontSize() { } DocumentFontSize(double _size, bool _relative) :size(_size) , relative(_relative) { } static DocumentFontSize Parse(const WString& value); WString ToString()const; bool operator==(const DocumentFontSize& value)const { return size == value.size && relative == value.relative; } bool operator!=(const DocumentFontSize& value)const { return size != value.size || relative != value.relative; } }; /// Represents a text style. class DocumentStyleProperties : public Object, public Description { public: /// Font face. Nullable face; /// Font size. Nullable size; /// Font color. Nullable color; /// Font color. Nullable backgroundColor; /// Bold. Nullable bold; /// Italic. Nullable italic; /// Underline. Nullable underline; /// Strikeline. Nullable strikeline; /// Antialias. Nullable antialias; /// Vertical antialias. Nullable verticalAntialias; }; /*********************************************************************** Rich Content Document (run) ***********************************************************************/ /// Pepresents a logical run of a rich content document. class DocumentRun : public Object, public Description { public: /// A visitor interface for . class IVisitor : public Interface { public: /// Visit operation for . /// The run object. virtual void Visit(DocumentTextRun* run)=0; /// Visit operation for . /// The run object. virtual void Visit(DocumentStylePropertiesRun* run)=0; /// Visit operation for . /// The run object. virtual void Visit(DocumentStyleApplicationRun* run)=0; /// Visit operation for . /// The run object. virtual void Visit(DocumentHyperlinkRun* run)=0; /// Visit operation for . /// The run object. virtual void Visit(DocumentImageRun* run)=0; /// Visit operation for . /// The run object. virtual void Visit(DocumentEmbeddedObjectRun* run)=0; /// Visit operation for . /// The run object. virtual void Visit(DocumentParagraphRun* run)=0; }; DocumentRun(){} /// Accept a and trigger the selected visit operation. /// The visitor. virtual void Accept(IVisitor* visitor)=0; }; /// Pepresents a container run. class DocumentContainerRun : public DocumentRun, public Description { typedef collections::List> RunList; public: /// Sub runs. RunList runs; }; /// Pepresents a content run. class DocumentContentRun : public DocumentRun, public Description { public: /// Get representation text. /// The representation text. virtual WString GetRepresentationText()=0; }; //------------------------------------------------------------------------- /// Pepresents a text run. class DocumentTextRun : public DocumentContentRun, public Description { public: /// Run text. WString text; DocumentTextRun(){} WString GetRepresentationText()override{return text;} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// Pepresents a inline object run. class DocumentInlineObjectRun : public DocumentContentRun, public Description { public: /// Size of the inline object. Size size; /// Baseline of the inline object. vint baseline; DocumentInlineObjectRun():baseline(-1){} }; /// Pepresents a image run. class DocumentImageRun : public DocumentInlineObjectRun, public Description { public: static const wchar_t* RepresentationText; /// The image. Ptr image; /// The frame index. vint frameIndex; /// The image source string. WString source; DocumentImageRun():frameIndex(0){} WString GetRepresentationText()override{return RepresentationText;} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// Pepresents an embedded object run. class DocumentEmbeddedObjectRun : public DocumentInlineObjectRun, public Description { public: static const wchar_t* RepresentationText; /// The object name. WString name; WString GetRepresentationText()override{return RepresentationText;} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; //------------------------------------------------------------------------- /// Pepresents a style properties run. class DocumentStylePropertiesRun : public DocumentContainerRun, public Description { public: /// Style properties. Ptr style; DocumentStylePropertiesRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// Pepresents a style application run. class DocumentStyleApplicationRun : public DocumentContainerRun, public Description { public: /// Style name. WString styleName; DocumentStyleApplicationRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// Pepresents a hyperlink text run. class DocumentHyperlinkRun : public DocumentStyleApplicationRun, public Description { public: class Package : public Object, public Description { public: collections::List> hyperlinks; vint row = -1; vint start = -1; vint end = -1; }; /// Style name for normal state. WString normalStyleName; /// Style name for active state. WString activeStyleName; /// The reference of the hyperlink. WString reference; DocumentHyperlinkRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// Pepresents a paragraph run. class DocumentParagraphRun : public DocumentContainerRun, public Description { public: /// Paragraph alignment. Nullable alignment; DocumentParagraphRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} WString GetText(bool skipNonTextContent); void GetText(stream::TextWriter& writer, bool skipNonTextContent); }; /*********************************************************************** Rich Content Document (model) ***********************************************************************/ /// Represents a text style. class DocumentStyle : public Object, public Description { public: /// Parent style name, could be #Default, #Context, #NormalLink, #ActiveLink or style name of others WString parentStyleName; /// Properties of this style. Ptr styles; /// Resolved properties of this style using parent styles. Ptr resolvedStyles; }; /// Represents a rich content document model. class DocumentModel : public Object, public Description { public: static const wchar_t* DefaultStyleName; static const wchar_t* SelectionStyleName; static const wchar_t* ContextStyleName; static const wchar_t* NormalLinkStyleName; static const wchar_t* ActiveLinkStyleName; public: /// Represents a resolved style. struct ResolvedStyle { /// The style of the text. FontProperties style; /// The color of the text. Color color; /// The background color of the text. Color backgroundColor; ResolvedStyle() { } ResolvedStyle(const FontProperties& _style, Color _color, Color _backgroundColor) :style(_style) ,color(_color) ,backgroundColor(_backgroundColor) { } }; struct RunRange { vint start; vint end; }; typedef collections::Dictionary RunRangeMap; private: typedef collections::List> ParagraphList; typedef collections::Dictionary> StyleMap; public: /// All paragraphs. ParagraphList paragraphs; /// All available styles. These will not be persistant. StyleMap styles; DocumentModel(); static void MergeStyle(Ptr style, Ptr parent); void MergeBaselineStyle(Ptr style, const WString& styleName); void MergeBaselineStyle(Ptr baselineDocument, const WString& styleName); void MergeBaselineStyles(Ptr baselineDocument); void MergeDefaultFont(const FontProperties& defaultFont); ResolvedStyle GetStyle(Ptr sp, const ResolvedStyle& context); ResolvedStyle GetStyle(const WString& styleName, const ResolvedStyle& context); WString GetText(bool skipNonTextContent); void GetText(stream::TextWriter& writer, bool skipNonTextContent); bool CheckEditRange(TextPos begin, TextPos end, RunRangeMap& relatedRanges); Ptr CopyDocument(TextPos begin, TextPos end, bool deepCopy); Ptr CopyDocument(); bool CutParagraph(TextPos position); bool CutEditRange(TextPos begin, TextPos end); bool EditContainer(TextPos begin, TextPos end, const Func& editor); vint EditRun(TextPos begin, TextPos end, Ptr replaceToModel, bool copy); vint EditRunNoCopy(TextPos begin, TextPos end, const collections::Array>& runs); vint EditText(TextPos begin, TextPos end, bool frontSide, const collections::Array& text); bool EditStyle(TextPos begin, TextPos end, Ptr style); Ptr EditImage(TextPos begin, TextPos end, Ptr image); bool EditHyperlink(vint paragraphIndex, vint begin, vint end, const WString& reference, const WString& normalStyleName=NormalLinkStyleName, const WString& activeStyleName=ActiveLinkStyleName); bool RemoveHyperlink(vint paragraphIndex, vint begin, vint end); Ptr GetHyperlink(vint paragraphIndex, vint begin, vint end); bool EditStyleName(TextPos begin, TextPos end, const WString& styleName); bool RemoveStyleName(TextPos begin, TextPos end); bool RenameStyle(const WString& oldStyleName, const WString& newStyleName); bool ClearStyle(TextPos begin, TextPos end); Ptr SummarizeStyle(TextPos begin, TextPos end); Nullable SummarizeStyleName(TextPos begin, TextPos end); Nullable SummarizeParagraphAlignment(TextPos begin, TextPos end); /// Load a document model from an xml. /// The loaded document model. /// The resource item containing the resource. /// The xml document. /// A document resolver to resolve symbols in non-embedded objects like image. /// All collected errors during loading a resource. static Ptr LoadFromXml(Ptr resource, Ptr xml, Ptr resolver, GuiResourceError::List& errors); /// Save a document model to an xml. /// The saved xml document. Ptr SaveToXml(); }; } } #endif /*********************************************************************** .\GRAPHICSELEMENT\GUIGRAPHICSELEMENT.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Element System and Infrastructure Interfaces Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSELEMENT #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSELEMENT namespace vl { namespace presentation { namespace elements { /*********************************************************************** Elements ***********************************************************************/ /// /// Defines a shape for some . /// enum class ElementShapeType { /// Rectangle shape. Rectangle, /// Ellipse shape. Ellipse, /// Round rectangle shape. RoundRect, }; /// /// Defines a shape for some . /// struct ElementShape { ElementShapeType shapeType = ElementShapeType::Rectangle; int radiusX = 0; int radiusY = 0; bool operator==(const ElementShape& value)const { return shapeType == value.shapeType && radiusX == value.radiusX && radiusY == value.radiusY; } bool operator!=(const ElementShape& value)const { return !(*this == value); } }; /// /// Defines a focus rectangle with a thickness of one pixel. /// class GuiFocusRectangleElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiFocusRectangleElement, L"FocusRectangle") protected: GuiFocusRectangleElement(); public: }; /// /// Defines a border element with a thickness of one pixel. /// class GuiSolidBorderElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiSolidBorderElement, L"SolidBorder") protected: Color color; ElementShape shape; GuiSolidBorderElement(); public: /// /// Get the border color. /// /// The border color. Color GetColor(); /// /// Set the border color. /// /// The new border color. void SetColor(Color value); /// /// Get the shape. /// /// The shape. ElementShape GetShape(); /// /// Set the shape. /// /// The new shape. void SetShape(ElementShape value); }; /// /// Defines a 3D-like rectangle element with a thickness of two pixels. /// class Gui3DBorderElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(Gui3DBorderElement, L"3DBorder") protected: Color color1; Color color2; Gui3DBorderElement(); public: /// /// Get the left-top color. /// /// The left-top color. Color GetColor1(); /// /// Set the border color. /// /// The new left-top color. void SetColor1(Color value); /// /// Get the right-bottom color. /// /// The right-bottom color. Color GetColor2(); /// /// Set the border color. /// /// The new right-bottom color. void SetColor2(Color value); /// /// Set colors of the element. /// /// The new left-top color. /// The new right bottom color. void SetColors(Color value1, Color value2); }; /// /// Defines a 3D-like splitter element with a thickness of two pixels. /// class Gui3DSplitterElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(Gui3DSplitterElement, L"3DSplitter") public: /// /// Defines a direction of the . /// enum Direction { /// Horizontal direction. Horizontal, /// Vertical direction. Vertical, }; protected: Color color1; Color color2; Direction direction; Gui3DSplitterElement(); public: /// /// Get the left-top color. /// /// The left-top color. Color GetColor1(); /// /// Set the border color. /// /// The new left-top color. void SetColor1(Color value); /// /// Get the right-bottom color. /// /// The right-bottom color. Color GetColor2(); /// /// Set the border color. /// /// The new right-bottom color. void SetColor2(Color value); /// /// Set colors of the element. /// /// The new left-top color. /// The new right bottom color. void SetColors(Color value1, Color value2); /// /// Get the direction. /// /// The direction. Direction GetDirection(); /// /// Set the direction. /// /// The new direction. void SetDirection(Direction value); }; /// /// Defines a color-filled element without border. /// class GuiSolidBackgroundElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiSolidBackgroundElement, L"SolidBackground") protected: Color color; ElementShape shape; GuiSolidBackgroundElement(); public: /// /// Get the border color. /// /// The border color. Color GetColor(); /// /// Set the border color. /// /// The new border color. void SetColor(Color value); /// /// Get the shape. /// /// The shape. ElementShape GetShape(); /// /// Set the shape. /// /// The new shape. void SetShape(ElementShape value); }; /// /// Defines a color-filled gradient element without border. /// class GuiGradientBackgroundElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiGradientBackgroundElement, L"GradientBackground") public: /// /// Defines a direction of the . /// enum Direction { /// Horizontal direction. Horizontal, /// vertical direction. Vertical, /// Slash direction. Slash, /// Back slash direction. Backslash, }; protected: Color color1; Color color2; Direction direction; ElementShape shape; GuiGradientBackgroundElement(); public: /// /// Get the left-top color. /// /// The left-top color. Color GetColor1(); /// /// Set the border color. /// /// The new left-top color. void SetColor1(Color value); /// /// Get the right bottom color. /// /// The right-bottom color. Color GetColor2(); /// /// Set the border color. /// /// The new right-bottom color. void SetColor2(Color value); /// /// Set colors of the element. /// /// The new left-top color. /// The new right bottom color. void SetColors(Color value1, Color value2); /// /// Get the direction. /// /// The direction. Direction GetDirection(); /// /// Set the direction. /// /// The new direction. void SetDirection(Direction value); /// /// Get the shape. /// /// The shape. ElementShape GetShape(); /// /// Set the shape. /// /// The new shape. void SetShape(ElementShape value); }; /// /// Defines a gradient border for shadow. /// class GuiInnerShadowElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiInnerShadowElement, L"InnerShadow") protected: Color color; vint thickness = 0; GuiInnerShadowElement(); public: /// /// Get the shadow color. /// /// The shadow color. Color GetColor(); /// /// Set the shadow color. /// /// The new shadow color. void SetColor(Color value); /// /// Get the thickness. /// /// The thickness. vint GetThickness(); /// /// Set the thickness. /// /// The new thickness. void SetThickness(vint value); }; /// /// Defines an element of a plain text. /// class GuiSolidLabelElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiSolidLabelElement, L"SolidLabel"); protected: Color color; FontProperties fontProperties; WString text; Alignment hAlignment; Alignment vAlignment; bool wrapLine; bool ellipse; bool multiline; bool wrapLineHeightCalculation; GuiSolidLabelElement(); public: /// /// Get the text color. /// /// The text color. Color GetColor(); /// /// Set the text color. /// /// The new text color. void SetColor(Color value); /// /// Get the text font. /// /// The text font. const FontProperties& GetFont(); /// /// Set the text font. /// /// The new text font. void SetFont(const FontProperties& value); /// /// Get the text. /// /// The text. const WString& GetText(); /// /// Set the text. /// /// The new text. void SetText(const WString& value); /// /// Get the horizontal alignment of the text. /// /// The horizontal alignment of the text. Alignment GetHorizontalAlignment(); /// /// Get the vertical alignment of the text. /// /// The vertical alignment of the text. Alignment GetVerticalAlignment(); /// /// Set the horizontal alignment of the text. /// /// The new horizontal alignment of the text. void SetHorizontalAlignment(Alignment value); /// /// Set the vertical alignment of the text. /// /// The vertical alignment of the text. void SetVerticalAlignment(Alignment value); /// /// Set alignments in both directions of the text. /// /// The new horizontal alignment of the text. /// The vertical alignment of the text. void SetAlignments(Alignment horizontal, Alignment vertical); /// /// Get if line auto-wrapping is enabled for this text. /// /// Return true if line auto-wrapping is enabled for this text. bool GetWrapLine(); /// /// Set if line auto-wrapping is enabled for this text. /// /// True if line auto-wrapping is enabled for this text. void SetWrapLine(bool value); /// /// Get if ellipse is enabled for this text. Ellipse will appear when the text is clipped. /// /// Return true if ellipse is enabled for this text. bool GetEllipse(); /// /// Set if ellipse is enabled for this text. Ellipse will appear when the text is clipped. /// /// True if ellipse is enabled for this text. void SetEllipse(bool value); /// /// Get if multiple lines is enabled for this text. /// /// Return true if multiple lines is enabled for this text. bool GetMultiline(); /// /// Set if multiple lines is enabled for this text. /// /// True if multiple lines is enabled for this text. void SetMultiline(bool value); /// /// Get if the element calculates the min height when wrap line is enabled. /// /// Return true if the element calculates the min height when wrap line is enabled. bool GetWrapLineHeightCalculation(); /// /// Set if the element calculates the min height when wrap line is enabled. /// /// True if the element calculates the min height when wrap line is enabled. void SetWrapLineHeightCalculation(bool value); }; /// /// Defines an element containing an image. /// class GuiImageFrameElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiImageFrameElement, L"ImageFrame"); protected: Ptr image; vint frameIndex; Alignment hAlignment; Alignment vAlignment; bool stretch; bool enabled; GuiImageFrameElement(); public: /// /// Get the containing image. /// /// The contining picture. Ptr GetImage(); /// /// Get the index of the frame in the containing image. /// /// The index of the frame in the containing image vint GetFrameIndex(); /// /// Set the containing image. /// /// The new containing image. void SetImage(Ptr value); /// /// Set the frame index. /// /// The new frameIndex. void SetFrameIndex(vint value); /// /// Set the containing image and the frame index. /// /// The new containing image. /// The new frameIndex. void SetImage(Ptr _image, vint _frameIndex); /// /// Get the horizontal alignment of the image. /// /// The horizontal alignment of the image. Alignment GetHorizontalAlignment(); /// /// Get the vertical alignment of the image. /// /// The vertical alignment of the image. Alignment GetVerticalAlignment(); /// /// Set the horizontal alignment of the text. /// /// The new horizontal alignment of the text. void SetHorizontalAlignment(Alignment value); /// /// Set the vertical alignment of the text. /// /// The vertical alignment of the text. void SetVerticalAlignment(Alignment value); /// /// Set alignments in both directions of the image. /// /// The new horizontal alignment of the image. /// The vertical alignment of the image. void SetAlignments(Alignment horizontal, Alignment vertical); /// /// Get if stretching is enabled for this image. /// /// Return true if stretching is enabled for this image. bool GetStretch(); /// /// Set if stretching is enabled for this image. /// /// True if stretching is enabled for this image. void SetStretch(bool value); /// /// Get if the image is rendered as enabled. /// /// Return true if the image is rendered as enabled. bool GetEnabled(); /// /// Set if the image is rendered as enabled. /// /// True if the image is rendered as enabled. void SetEnabled(bool value); }; /// /// Defines a polygon element with a thickness of one pixel. /// class GuiPolygonElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiPolygonElement, L"Polygon"); typedef collections::Array PointArray; protected: Size size; PointArray points; Color borderColor; Color backgroundColor; GuiPolygonElement(); public: /// /// Get a suggested size. The polygon element will be layouted to the center of the required bounds using this size. /// /// The suggested size. Size GetSize(); /// /// Set a suggested size. The polygon element will be layouted to the center of the required bounds using this size. /// /// The new size. void SetSize(Size value); /// /// Get a point of the polygon element using an index. /// /// The index to access a point. /// The point of the polygon element associated with the index. const Point& GetPoint(vint index); /// /// Get the number of points /// /// The number of points. vint GetPointCount(); /// /// Set all points to the polygon element. /// /// A pointer to a buffer that stores all points. /// The number of points. void SetPoints(const Point* p, vint count); /// /// Get all points. /// /// All points const PointArray& GetPointsArray(); /// /// Set all points. /// /// All points void SetPointsArray(const PointArray& value); /// /// Get the border color. /// /// The border color. Color GetBorderColor(); /// /// Set the border color. /// /// The new border color. void SetBorderColor(Color value); /// /// Get the background color. /// /// The background color. Color GetBackgroundColor(); /// /// Set the background color. /// /// The new background color. void SetBackgroundColor(Color value); }; } } } #endif /*********************************************************************** .\GRAPHICSELEMENT\GUIGRAPHICSDOCUMENTELEMENT.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Element System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSDOCUMENTELEMENT #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSDOCUMENTELEMENT namespace vl { namespace presentation { namespace elements { namespace visitors { class SetPropertiesVisitor; } /*********************************************************************** Rich Content Document (element) ***********************************************************************/ /// Defines a rich text document element for rendering complex styled document. class GuiDocumentElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiDocumentElement, L"RichDocument"); public: /// Callback interface for this element. class ICallback : public virtual IDescriptable, public Description { public: /// Called when the rendering is started. virtual void OnStartRender() = 0; /// Called when the rendering is finished. virtual void OnFinishRender() = 0; /// Called when an embedded object is being rendered. /// Returns the new size of the rendered embedded object. /// The name of the embedded object /// The location of the embedded object, relative to the left-top corner of this element. virtual Size OnRenderEmbeddedObject(const WString& name, const Rect& location) = 0; }; class GuiDocumentElementRenderer : public Object, public IGuiGraphicsRenderer, private IGuiGraphicsParagraphCallback { friend class visitors::SetPropertiesVisitor; DEFINE_GUI_GRAPHICS_RENDERER(GuiDocumentElement, GuiDocumentElementRenderer, IGuiGraphicsRenderTarget) protected: struct EmbeddedObject { WString name; Size size; vint start; bool resized = false; }; typedef collections::Dictionary> IdEmbeddedObjectMap; typedef collections::Dictionary NameIdMap; typedef collections::List FreeIdList; struct ParagraphCache { WString fullText; Ptr graphicsParagraph; IdEmbeddedObjectMap embeddedObjects; vint selectionBegin; vint selectionEnd; ParagraphCache() :selectionBegin(-1) ,selectionEnd(-1) { } }; typedef collections::Array> ParagraphCacheArray; typedef collections::Array ParagraphHeightArray; private: Size OnRenderInlineObject(vint callbackId, Rect location)override; protected: vint paragraphDistance; vint lastMaxWidth; vint cachedTotalHeight; IGuiGraphicsLayoutProvider* layoutProvider; ParagraphCacheArray paragraphCaches; ParagraphHeightArray paragraphHeights; TextPos lastCaret; Color lastCaretColor; bool lastCaretFrontSide; NameIdMap nameCallbackIdMap; FreeIdList freeCallbackIds; vint usedCallbackIds = 0; vint renderingParagraph = -1; Point renderingParagraphOffset; void InitializeInternal(); void FinalizeInternal(); void RenderTargetChangedInternal(IGuiGraphicsRenderTarget* oldRenderTarget, IGuiGraphicsRenderTarget* newRenderTarget); Ptr EnsureAndGetCache(vint paragraphIndex, bool createParagraph); bool GetParagraphIndexFromPoint(Point point, vint& top, vint& index); public: GuiDocumentElementRenderer(); void Render(Rect bounds)override; void OnElementStateChanged()override; void NotifyParagraphUpdated(vint index, vint oldCount, vint newCount, bool updatedText); Ptr GetHyperlinkFromPoint(Point point); void OpenCaret(TextPos caret, Color color, bool frontSide); void CloseCaret(TextPos caret); void SetSelection(TextPos begin, TextPos end); TextPos CalculateCaret(TextPos comparingCaret, IGuiGraphicsParagraph::CaretRelativePosition position, bool& preferFrontSide); TextPos CalculateCaretFromPoint(Point point); Rect GetCaretBounds(TextPos caret, bool frontSide); }; protected: Ptr document; ICallback* callback = nullptr; TextPos caretBegin; TextPos caretEnd; bool caretVisible; bool caretFrontSide; Color caretColor; void UpdateCaret(); GuiDocumentElement(); public: /// Get the callback. /// The callback. ICallback* GetCallback(); /// Set the callback. /// The callback. void SetCallback(ICallback* value); /// Get the document. /// The document. Ptr GetDocument(); /// Set the document. When a document is set to this element, modifying the document without invoking will lead to undefined behavior. /// The document. void SetDocument(Ptr value); /// /// Get the begin position of the selection area. /// /// The begin position of the selection area. TextPos GetCaretBegin(); /// /// Get the end position of the selection area. /// /// The end position of the selection area. TextPos GetCaretEnd(); /// /// Get the prefer side for the caret. /// /// Returns true if the caret is rendered for the front side. bool IsCaretEndPreferFrontSide(); /// /// Set the end position of the selection area. /// /// The begin position of the selection area. /// The end position of the selection area. /// Set to true to show the caret for the character before it. This argument is ignored if begin and end are the same. void SetCaret(TextPos begin, TextPos end, bool frontSide); /// /// Get the caret visibility. /// /// Returns true if the caret will be rendered. bool GetCaretVisible(); /// /// Set the caret visibility. /// /// True if the caret will be rendered. void SetCaretVisible(bool value); /// /// Get the color of the caret. /// /// The color of the caret. Color GetCaretColor(); /// /// Set the color of the caret. /// /// The color of the caret. void SetCaretColor(Color value); /// Calculate a caret using a specified comparing caret and a relative position. /// The calculated caret. /// The comparing caret. /// The relative position. /// Specify the side for the comparingCaret. Retrive the suggested side for the new caret. If the return caret equals compareCaret, this output is ignored. TextPos CalculateCaret(TextPos comparingCaret, IGuiGraphicsParagraph::CaretRelativePosition position, bool& preferFrontSide); /// Calculate a caret using a specified point. /// The calculated caret. /// The specified point. TextPos CalculateCaretFromPoint(Point point); /// Get the bounds of a caret. /// The bounds. /// The caret. /// Set to true to get the bounds for the character before it. Rect GetCaretBounds(TextPos caret, bool frontSide); /// Notify that some paragraphs are updated. /// The start paragraph index. /// The number of paragraphs to be updated. /// The number of updated paragraphs. /// Set to true to notify that the text is updated. void NotifyParagraphUpdated(vint index, vint oldCount, vint newCount, bool updatedText); /// Edit run in a specified range. /// The begin position of the range. /// The end position of the range. /// The new run. /// Set to true to copy the model before editing. Otherwise, objects inside the model will be used directly void EditRun(TextPos begin, TextPos end, Ptr model, bool copy); /// Edit text in a specified range. /// The begin position of the range. /// The end position of the range. /// Set to true to use the text style in front of the specified range. /// The new text. void EditText(TextPos begin, TextPos end, bool frontSide, const collections::Array& text); /// Edit style in a specified range. /// The begin position of the range. /// The end position of the range. /// The new style. void EditStyle(TextPos begin, TextPos end, Ptr style); /// Edit image in a specified range. /// The begin position of the range. /// The end position of the range. /// The new image. void EditImage(TextPos begin, TextPos end, Ptr image); /// Set hyperlink in a specified range. /// The index of the paragraph to edit. /// The begin position of the range. /// The end position of the range. /// The reference of the hyperlink. /// The normal style name of the hyperlink. /// The active style name of the hyperlink. void EditHyperlink(vint paragraphIndex, vint begin, vint end, const WString& reference, const WString& normalStyleName=DocumentModel::NormalLinkStyleName, const WString& activeStyleName=DocumentModel::ActiveLinkStyleName); /// Remove hyperlink in a specified range. /// The index of the paragraph to edit. /// The begin position of the range. /// The end position of the range. void RemoveHyperlink(vint paragraphIndex, vint begin, vint end); /// Edit style name in a specified range. /// The begin position of the range. /// The end position of the range. /// The new style name. void EditStyleName(TextPos begin, TextPos end, const WString& styleName); /// Remove style name in a specified range. /// The begin position of the range. /// The end position of the range. void RemoveStyleName(TextPos begin, TextPos end); /// Rename a style. /// The name of the style. /// The new name. void RenameStyle(const WString& oldStyleName, const WString& newStyleName); /// Clear all styles in a specified range. /// The begin position of the range. /// The end position of the range. void ClearStyle(TextPos begin, TextPos end); /// Summarize the text style in a specified range. /// The text style summary. /// The begin position of the range. /// The end position of the range. Ptr SummarizeStyle(TextPos begin, TextPos end); /// Summarize the style name in a specified range. /// The style name summary. /// The begin position of the range. /// The end position of the range. Nullable SummarizeStyleName(TextPos begin, TextPos end); /// Set the alignment of paragraphs in a specified range. /// The begin position of the range. /// The end position of the range. /// The alignment for each paragraph. void SetParagraphAlignment(TextPos begin, TextPos end, const collections::Array>& alignments); /// Summarize the text alignment in a specified range. /// The text alignment summary. /// The begin position of the range. /// The end position of the range. Nullable SummarizeParagraphAlignment(TextPos begin, TextPos end); /// Get hyperlink from point. /// Corressponding hyperlink id. Returns -1 indicates that the point is not in a hyperlink. /// The point to get the hyperlink id. Ptr GetHyperlinkFromPoint(Point point); }; } } } #endif /*********************************************************************** .\GRAPHICSELEMENT\GUIGRAPHICSTEXTELEMENT.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Element System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSTEXTELEMENT #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSTEXTELEMENT namespace vl { namespace presentation { namespace elements { class GuiColorizedTextElement; /*********************************************************************** Colorized Plain Text (model) ***********************************************************************/ namespace text { /// /// Represents the extra information of a character to display. /// struct CharAtt { /// /// The distance from the head of the line to the right side of this character in pixel. /// vuint32_t rightOffset; /// /// The color index of the character. Use [M:vl.presentation.elements.GuiColorizedTextElement.GetColors] and [M:vl.presentation.elements.GuiColorizedTextElement.SetColors] to access the color table. /// vuint32_t colorIndex; }; /// /// Represents a line of characters. /// struct TextLine { static const vint BlockSize=32; static const vint MaxWidth=0xFFFF; /// /// A character buffer starts from the first character of this line. /// wchar_t* text; /// /// A extra information buffer starts from the first character of this line. /// CharAtt* att; /// /// The number of available in the buffer. /// vint availableOffsetCount; /// /// The number of elements in the allocated buffer memory. /// vint bufferLength; /// /// The number of available characters in the buffer. /// vint dataLength; /// /// The internal lexical analyzer state of a colorizer when it parses to the end of this line. -1 means that this state is not available. /// vint lexerFinalState; /// /// The internal context sensitive state of a colorizer when it parses to the end of this line. -1 means that this state is not available. /// vint contextFinalState; TextLine(); ~TextLine(); static vint CalculateBufferLength(vint dataLength); bool operator==(const TextLine& value)const{return false;} bool operator!=(const TextLine& value)const{return true;} /// /// Initialize the instance to be an empty line. /// void Initialize(); /// /// Release all resources used in this line. /// void Finalize(); /// /// Test is the line initialized. /// /// Returns true if the line is initialized. bool IsReady(); /// /// Modify the characters in the line by replacing characters. /// /// Returns true if the modification succeeded. /// The position of the first character to be replaced. /// The number of characters to be replaced. /// The buffer to the characters to write into this line. /// The numbers of the characters to write into this line. bool Modify(vint start, vint count, const wchar_t* input, vint inputCount); /// /// Split a text line into two by the position. The current line contains characters before this position. This function returns a new text line contains characters after this position. /// /// The new text line. /// . TextLine Split(vint index); /// /// Append a text line after the this text line, and finalize the input text line. /// /// The text line that contains all characters and color indices to append and be finalized. void AppendAndFinalize(TextLine& line); }; #if defined VCZH_MSVC /// Test if a wchar_t is the first character of a surrogate pair. /// The character to test. /// Returns true if it is the first character of a surrogate pair. inline bool UTF16SPFirst(wchar_t c) { return 0xD800 <= c && c < 0xDC00; } /// Test if a wchar_t is the second character of a surrogate pair. /// The character to test. /// Returns true if it is the second character of a surrogate pair. inline bool UTF16SPSecond(wchar_t c) { return 0xDC00 <= c && c < 0xDFFF; } #endif /// /// A unicode code point. /// In Windows, when the first character is not the leading character of a surrogate pair, the second character is ignored. /// In other platforms which treat wchar_t as a UTF-32 character, the second character is ignored. /// struct UnicodeCodePoint { #if defined VCZH_MSVC wchar_t characters[2]; UnicodeCodePoint(wchar_t c) :characters{ c,0 } {} UnicodeCodePoint(wchar_t c1, wchar_t c2) :characters{ c1,c2 } {} #elif defined VCZH_GCC wchar_t character; UnicodeCodePoint(wchar_t c) :character(c) {} #endif vuint32_t GetCodePoint()const { #if defined VCZH_MSVC if (UTF16SPFirst(characters[0]) && UTF16SPSecond(characters[1])) { return (wchar_t)(characters[0] - 0xD800) * 0x400 + (wchar_t)(characters[1] - 0xDC00) + 0x10000; } else { return (vuint32_t)characters[0]; } #elif defined VCZH_GCC return (vuint32_t)character; #endif } }; /// /// An abstract class for character size measuring in differect rendering technology. /// class CharMeasurer : public virtual IDescriptable { protected: IGuiGraphicsRenderTarget* oldRenderTarget = nullptr; vint rowHeight; vint widths[65536]; /// /// Measure the width of a character. /// /// The width in pixel. /// The unicode code point to measure. /// The render target which the character is going to be rendered. This is a pure virtual member function to be overrided. virtual vint MeasureWidthInternal(UnicodeCodePoint codePoint, IGuiGraphicsRenderTarget* renderTarget)=0; /// /// Measure the height of a character. /// /// The height in pixel. /// The render target which the character is going to be rendered. virtual vint GetRowHeightInternal(IGuiGraphicsRenderTarget* renderTarget)=0; public: /// /// Initialize a character measurer. /// /// The default character height in pixel before the character measurer is binded to a render target. CharMeasurer(vint _rowHeight); ~CharMeasurer(); /// /// Bind a render target to this character measurer. /// /// The render target to bind. void SetRenderTarget(IGuiGraphicsRenderTarget* value); /// /// Measure the width of a character using the binded render target. /// /// The width of a character, in pixel. /// The unicode code point to measure. vint MeasureWidth(UnicodeCodePoint codePoint); /// /// Measure the height of a character. /// /// The height of a character, in pixel. vint GetRowHeight(); }; /// /// A class to maintain multiple lines of text buffer. /// class TextLines : public Object, public Description { typedef collections::List TextLineList; protected: GuiColorizedTextElement* ownerElement; TextLineList lines; CharMeasurer* charMeasurer; IGuiGraphicsRenderTarget* renderTarget; vint tabWidth; vint tabSpaceCount; wchar_t passwordChar; public: TextLines(GuiColorizedTextElement* _ownerElement); ~TextLines(); /// /// Returns the number of text lines. /// /// The number of text lines. vint GetCount(); /// /// Returns the text line of a specified row number. /// /// The related text line object. /// The specified row number. TextLine& GetLine(vint row); /// /// Returns the binded . /// /// The binded . CharMeasurer* GetCharMeasurer(); /// /// Binded a . /// /// The to bind. void SetCharMeasurer(CharMeasurer* value); /// /// Returns the binded . /// /// The binded . IGuiGraphicsRenderTarget* GetRenderTarget(); /// /// Binded a . /// /// The to bind. void SetRenderTarget(IGuiGraphicsRenderTarget* value); /// /// Returns a string from a specified range of the text lines. /// /// The string. /// The start position. /// The end position. WString GetText(TextPos start, TextPos end); /// /// Returns the whole string in the text lines. /// /// The string. WString GetText(); /// /// Set the string to the text lines. This operation will modified every objects. /// /// The string to set into the text lines. void SetText(const WString& value); /// /// Remove text lines in a specified range. /// /// Returns true if this operation succeeded. /// The first row number. /// The number of text lines to be removed. bool RemoveLines(vint start, vint count); /// /// Test is a text position available in the text lines. /// /// Returns true if this position is available. /// The text position to test. bool IsAvailable(TextPos pos); /// /// Normalize a text position to be available. /// /// The normalized text position. /// The text position to normalize. TextPos Normalize(TextPos pos); /// /// Modify some text lines by replacing characters. /// /// The new end position. /// The start position of the range of characters to be replaced. /// The end position of the range of characters to be replaced. /// The buffer to the string buffers to replace into the text lines. /// The numbers of characters for each string buffer. /// The number of string buffers. TextPos Modify(TextPos start, TextPos end, const wchar_t** inputs, vint* inputCounts, vint rows); /// /// Modify some text lines by replacing characters. /// /// The new end position. /// The start position of the range of characters to be replaced. /// The end position of the range of characters to be replaced. /// The buffer to the string to replace into the text lines. /// The number of characters to replace into the text lines. TextPos Modify(TextPos start, TextPos end, const wchar_t* input, vint inputCount); /// /// Modify some text lines by replacing characters. /// /// The new end position. /// The start position of the range of characters to be replaced. /// The end position of the range of characters to be replaced. /// The string to replace into the text lines. TextPos Modify(TextPos start, TextPos end, const wchar_t* input); /// /// Modify some text lines by replacing characters. /// /// The new end position. /// The start position of the range of characters to be replaced. /// The end position of the range of characters to be replaced. /// The string to replace into the text lines. TextPos Modify(TextPos start, TextPos end, const WString& input); /// /// Remove every text lines. /// void Clear(); /// /// Clear all cached . /// void ClearMeasurement(); /// /// Returns the number of spaces to replace a tab character for rendering. /// /// The number of spaces to replace a tab character for rendering. vint GetTabSpaceCount(); /// /// Set the number of spaces to replace a tab character for rendering. /// /// The number of spaces to replace a tab character for rendering. void SetTabSpaceCount(vint value); /// /// Measure all characters in a specified row. /// /// The specified row number. void MeasureRow(vint row); /// /// Returns the width of a specified row. /// /// The width of a specified row, in pixel. /// The specified row number. vint GetRowWidth(vint row); /// /// Returns the height of a row. /// /// The height of a row, in pixel. vint GetRowHeight(); /// /// Returns the total width of the text lines. /// /// The width of the text lines, in pixel. vint GetMaxWidth(); /// /// Returns the total height of the text lines. /// /// The height of the text lines, in pixel. vint GetMaxHeight(); /// /// Get the text position near to specified point. /// /// The text position. /// The specified point, in pixel. TextPos GetTextPosFromPoint(Point point); /// /// Get the point of a specified text position. /// /// The point, in pixel. Returns (-1, -1) if the text position is not available. /// The specified text position. Point GetPointFromTextPos(TextPos pos); /// /// Get the bounds of a specified text position. /// /// The bounds, in pixel. Returns (-1, -1, -1, -1) if the text position is not available. /// The specified text position. Rect GetRectFromTextPos(TextPos pos); /// /// Get the password mode displaying character. /// /// The password mode displaying character. Returns L'\0' means the password mode is not activated. wchar_t GetPasswordChar(); /// /// Set the password mode displaying character. /// /// The password mode displaying character. Set to L'\0' to deactivate the password mode. void SetPasswordChar(wchar_t value); }; /// /// Represents colors of a character. /// struct ColorItem { /// /// Text color. /// Color text; /// /// Background color. /// Color background; inline vint64_t Compare(const ColorItem& value)const { vint64_t result; if ((result = text.Compare(value.text)) != 0) return result; if ((result = background.Compare(value.background)) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(ColorItem) }; /// /// Represents color entry in a color table. Use [M:vl.presentation.elements.GuiColorizedTextElement.GetColors] and [M:vl.presentation.elements.GuiColorizedTextElement.SetColors] to access the color table. /// struct ColorEntry { /// /// Colors in normal state. /// ColorItem normal; /// /// Colors in focused and selected state. /// ColorItem selectedFocused; /// /// Colors in not focused and selected state. /// ColorItem selectedUnfocused; inline vint64_t Compare(const ColorEntry& value)const { vint64_t result; if ((result = normal.Compare(value.normal)) != 0) return result; if ((result = selectedFocused.Compare(value.selectedFocused)) != 0) return result; if ((result = selectedUnfocused.Compare(value.selectedUnfocused)) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(ColorEntry) }; } /*********************************************************************** Colorized Plain Text (element) ***********************************************************************/ /// /// Defines a text element with separate color configuration for each character. /// class GuiColorizedTextElement : public GuiElementBase { DEFINE_GUI_GRAPHICS_ELEMENT(GuiColorizedTextElement, L"ColorizedText"); friend class text::TextLines; typedef collections::Array ColorArray; public: /// /// An callback interface. Member functions will be called when colors or fonts of a changed. /// class ICallback : public virtual IDescriptable, public Description { public: /// /// Called when the color table of a changed. /// virtual void ColorChanged()=0; /// /// Called when the font configuration of a changed. /// virtual void FontChanged()=0; }; protected: ICallback* callback; ColorArray colors; FontProperties font; Point viewPosition; bool isVisuallyEnabled; bool isFocused; TextPos caretBegin; TextPos caretEnd; bool caretVisible; Color caretColor; text::TextLines lines; GuiColorizedTextElement(); public: /// /// Get the internal object that stores all characters and colors. /// /// The internal object. text::TextLines& GetLines(); /// /// Get the binded callback object. /// /// The binded callback object. ICallback* GetCallback(); /// /// Bind a callback object. /// /// The callback object to bind. void SetCallback(ICallback* value); /// /// Get the binded color table. Use to use colors in this color table. /// /// The binded color table. const ColorArray& GetColors(); /// /// Bind a color table. Use to use colors in this color table. will be called. /// /// The color table to bind. void SetColors(const ColorArray& value); /// /// Reset color of all characters /// /// Color index of all characters. void ResetTextColorIndex(vint index); /// /// Get the font configuration for all characters. /// /// The font configuration. const FontProperties& GetFont(); /// /// Set the font configuration for all characters. will be called. /// /// The font configuration. void SetFont(const FontProperties& value); /// /// Get the password mode displaying character. /// /// The password mode displaying character. Returns L'\0' means the password mode is not activated. wchar_t GetPasswordChar(); /// /// Set the password mode displaying character. /// /// The password mode displaying character. Set to L'\0' to deactivate the password mode. void SetPasswordChar(wchar_t value); /// /// Get the left-top position of the visible bounds of characters. /// /// The left-top position of the visible bounds of characters. Point GetViewPosition(); /// /// Set the left-top position of the visible bounds of characters. /// /// The left-top position of the visible bounds of characters. void SetViewPosition(Point value); /// /// Get the enabling state. /// /// Returns true if the element will be rendered as an enabled element. bool GetVisuallyEnabled(); /// /// Set the enabling state. /// /// True if the element will be rendered as an enabled element. void SetVisuallyEnabled(bool value); /// /// Get the focused state. /// /// Returns true if the element will be rendered as a focused element. bool GetFocused(); /// /// Set the focused state. /// /// True if the element will be rendered as a focused element. void SetFocused(bool value); /// /// Get the begin position of the selection area. /// /// The begin position of the selection area. TextPos GetCaretBegin(); /// /// Set the begin position of the selection area. /// /// The begin position of the selection area. void SetCaretBegin(TextPos value); /// /// Get the end position of the selection area. /// /// The end position of the selection area. TextPos GetCaretEnd(); /// /// Set the end position of the selection area. /// /// The end position of the selection area. void SetCaretEnd(TextPos value); /// /// Get the caret visibility. /// /// Returns true if the caret will be rendered. bool GetCaretVisible(); /// /// Set the caret visibility. /// /// True if the caret will be rendered. void SetCaretVisible(bool value); /// /// Get the color of the caret. /// /// The color of the caret. Color GetCaretColor(); /// /// Set the color of the caret. /// /// The color of the caret. void SetCaretColor(Color value); }; } } } #endif /*********************************************************************** .\CONTROLS\TEMPLATES\GUICONTROLTEMPLATES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Template System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_TEMPLATES_GUICONTROLTEMPLATES #define VCZH_PRESENTATION_CONTROLS_TEMPLATES_GUICONTROLTEMPLATES namespace vl { namespace presentation { namespace controls { class GuiButton; class GuiSelectableButton; class GuiListControl; class GuiComboBoxListControl; class GuiTextList; class GuiTabPage; class GuiScroll; } namespace templates { #define GUI_TEMPLATE_PROPERTY_DECL(CLASS, TYPE, NAME, VALUE)\ private:\ TYPE NAME##_ = VALUE;\ public:\ TYPE Get##NAME();\ void Set##NAME(TYPE const& value);\ compositions::GuiNotifyEvent NAME##Changed;\ #define GUI_TEMPLATE_PROPERTY_IMPL(CLASS, TYPE, NAME, VALUE)\ TYPE CLASS::Get##NAME()\ {\ return NAME##_;\ }\ void CLASS::Set##NAME(TYPE const& value)\ {\ if (NAME##_ != value)\ {\ NAME##_ = value;\ NAME##Changed.Execute(compositions::GuiEventArgs(this));\ }\ }\ #define GUI_TEMPLATE_PROPERTY_EVENT_INIT(CLASS, TYPE, NAME, VALUE)\ NAME##Changed.SetAssociatedComposition(this); #define GUI_TEMPLATE_CLASS_DECL(CLASS, BASE)\ class CLASS : public BASE, public AggregatableDescription\ {\ public:\ CLASS();\ ~CLASS();\ CLASS ## _PROPERTIES(GUI_TEMPLATE_PROPERTY_DECL)\ };\ #define GUI_TEMPLATE_CLASS_IMPL(CLASS, BASE)\ CLASS ## _PROPERTIES(GUI_TEMPLATE_PROPERTY_IMPL)\ CLASS::CLASS()\ {\ CLASS ## _PROPERTIES(GUI_TEMPLATE_PROPERTY_EVENT_INIT)\ }\ CLASS::~CLASS()\ {\ FinalizeAggregation();\ }\ #define GUI_CONTROL_TEMPLATE_DECL(F)\ F(GuiControlTemplate, GuiTemplate) \ F(GuiLabelTemplate, GuiControlTemplate) \ F(GuiSinglelineTextBoxTemplate, GuiControlTemplate) \ F(GuiDocumentLabelTemplate, GuiControlTemplate) \ F(GuiWindowTemplate, GuiControlTemplate) \ F(GuiMenuTemplate, GuiWindowTemplate) \ F(GuiButtonTemplate, GuiControlTemplate) \ F(GuiSelectableButtonTemplate, GuiButtonTemplate) \ F(GuiToolstripButtonTemplate, GuiSelectableButtonTemplate)\ F(GuiListViewColumnHeaderTemplate, GuiToolstripButtonTemplate) \ F(GuiComboBoxTemplate, GuiToolstripButtonTemplate) \ F(GuiScrollTemplate, GuiControlTemplate) \ F(GuiScrollViewTemplate, GuiControlTemplate) \ F(GuiMultilineTextBoxTemplate, GuiScrollViewTemplate) \ F(GuiDocumentViewerTemplate, GuiScrollViewTemplate) \ F(GuiListControlTemplate, GuiScrollViewTemplate) \ F(GuiTextListTemplate, GuiListControlTemplate) \ F(GuiListViewTemplate, GuiListControlTemplate) \ F(GuiTreeViewTemplate, GuiListControlTemplate) \ F(GuiTabTemplate, GuiControlTemplate) \ F(GuiDatePickerTemplate, GuiControlTemplate) \ F(GuiDateComboBoxTemplate, GuiComboBoxTemplate) \ F(GuiRibbonTabTemplate, GuiTabTemplate) \ F(GuiRibbonGroupTemplate, GuiControlTemplate) \ F(GuiRibbonIconLabelTemplate, GuiControlTemplate) \ F(GuiRibbonButtonsTemplate, GuiControlTemplate) \ F(GuiRibbonToolstripsTemplate, GuiControlTemplate) \ F(GuiRibbonToolstripMenuTemplate, GuiMenuTemplate) \ F(GuiRibbonGalleryTemplate, GuiControlTemplate) \ F(GuiRibbonGalleryListTemplate, GuiRibbonGalleryTemplate) \ #define GUI_ITEM_TEMPLATE_DECL(F)\ F(GuiTextListItemTemplate, GuiListItemTemplate) \ F(GuiTreeItemTemplate, GuiTextListItemTemplate) \ F(GuiGridCellTemplate, GuiControlTemplate) \ F(GuiGridVisualizerTemplate, GuiGridCellTemplate) \ F(GuiGridEditorTemplate, GuiGridCellTemplate) \ /*********************************************************************** GuiTemplate ***********************************************************************/ /// Represents a user customizable template. class GuiTemplate : public compositions::GuiBoundsComposition, public controls::GuiInstanceRootObject, public Description { protected: controls::GuiControlHost* GetControlHostForInstance()override; void OnParentLineChanged()override; public: /// Create a template. GuiTemplate(); ~GuiTemplate(); #define GuiTemplate_PROPERTIES(F)\ F(GuiTemplate, FontProperties, Font, {} )\ F(GuiTemplate, description::Value, Context, {} )\ F(GuiTemplate, WString, Text, {} )\ F(GuiTemplate, bool, VisuallyEnabled, true)\ GuiTemplate_PROPERTIES(GUI_TEMPLATE_PROPERTY_DECL) }; /*********************************************************************** GuiListItemTemplate ***********************************************************************/ class GuiListItemTemplate : public GuiTemplate, public AggregatableDescription { protected: controls::GuiListControl* listControl = nullptr; virtual void OnInitialize(); public: GuiListItemTemplate(); ~GuiListItemTemplate(); #define GuiListItemTemplate_PROPERTIES(F)\ F(GuiListItemTemplate, bool, Selected, false)\ F(GuiListItemTemplate, vint, Index, 0)\ GuiListItemTemplate_PROPERTIES(GUI_TEMPLATE_PROPERTY_DECL) void BeginEditListItem(); void EndEditListItem(); void Initialize(controls::GuiListControl* _listControl); }; /*********************************************************************** Control Template ***********************************************************************/ enum class BoolOption { AlwaysTrue, AlwaysFalse, Customizable, }; #define GuiControlTemplate_PROPERTIES(F)\ F(GuiControlTemplate, compositions::GuiGraphicsComposition*, ContainerComposition, this)\ F(GuiControlTemplate, compositions::GuiGraphicsComposition*, FocusableComposition, nullptr)\ F(GuiControlTemplate, bool, Focused, false)\ #define GuiLabelTemplate_PROPERTIES(F)\ F(GuiLabelTemplate, Color, DefaultTextColor, {})\ F(GuiLabelTemplate, Color, TextColor, {})\ #define GuiSinglelineTextBoxTemplate_PROPERTIES(F)\ F(GuiSinglelineTextBoxTemplate, elements::text::ColorEntry, TextColor, {})\ F(GuiSinglelineTextBoxTemplate, Color, CaretColor, {})\ #define GuiDocumentLabelTemplate_PROPERTIES(F)\ F(GuiDocumentLabelTemplate, Ptr, BaselineDocument, {})\ F(GuiDocumentLabelTemplate, Color, CaretColor, {})\ #define GuiWindowTemplate_PROPERTIES(F)\ F(GuiWindowTemplate, BoolOption, MaximizedBoxOption, BoolOption::Customizable)\ F(GuiWindowTemplate, BoolOption, MinimizedBoxOption, BoolOption::Customizable)\ F(GuiWindowTemplate, BoolOption, BorderOption, BoolOption::Customizable)\ F(GuiWindowTemplate, BoolOption, SizeBoxOption, BoolOption::Customizable)\ F(GuiWindowTemplate, BoolOption, IconVisibleOption, BoolOption::Customizable)\ F(GuiWindowTemplate, BoolOption, TitleBarOption, BoolOption::Customizable)\ F(GuiWindowTemplate, bool, MaximizedBox, true)\ F(GuiWindowTemplate, bool, MinimizedBox, true)\ F(GuiWindowTemplate, bool, Border, true)\ F(GuiWindowTemplate, bool, SizeBox, true)\ F(GuiWindowTemplate, bool, IconVisible, true)\ F(GuiWindowTemplate, bool, TitleBar, true)\ F(GuiWindowTemplate, bool, Maximized, false)\ F(GuiWindowTemplate, bool, Activated, false)\ F(GuiWindowTemplate, TemplateProperty, TooltipTemplate, {})\ F(GuiWindowTemplate, TemplateProperty, ShortcutKeyTemplate, {})\ F(GuiWindowTemplate, bool, CustomFrameEnabled, true)\ F(GuiWindowTemplate, Margin, CustomFramePadding, {})\ F(GuiWindowTemplate, Ptr, Icon, {})\ #define GuiMenuTemplate_PROPERTIES(F) #define GuiButtonTemplate_PROPERTIES(F)\ F(GuiButtonTemplate, controls::ButtonState, State, controls::ButtonState::Normal)\ #define GuiSelectableButtonTemplate_PROPERTIES(F)\ F(GuiSelectableButtonTemplate, bool, Selected, false)\ #define GuiToolstripButtonTemplate_PROPERTIES(F)\ F(GuiToolstripButtonTemplate, TemplateProperty, SubMenuTemplate, {})\ F(GuiToolstripButtonTemplate, bool, SubMenuExisting, false)\ F(GuiToolstripButtonTemplate, bool, SubMenuOpening, false)\ F(GuiToolstripButtonTemplate, controls::GuiButton*, SubMenuHost, nullptr)\ F(GuiToolstripButtonTemplate, Ptr, LargeImage, {})\ F(GuiToolstripButtonTemplate, Ptr, Image, {})\ F(GuiToolstripButtonTemplate, WString, ShortcutText, {})\ #define GuiListViewColumnHeaderTemplate_PROPERTIES(F)\ F(GuiListViewColumnHeaderTemplate, controls::ColumnSortingState, SortingState, controls::ColumnSortingState::NotSorted)\ #define GuiComboBoxTemplate_PROPERTIES(F)\ F(GuiComboBoxTemplate, bool, TextVisible, true)\ #define GuiScrollTemplate_PROPERTIES(F)\ F(GuiScrollTemplate, controls::IScrollCommandExecutor*, Commands, nullptr)\ F(GuiScrollTemplate, vint, TotalSize, 100)\ F(GuiScrollTemplate, vint, PageSize, 10)\ F(GuiScrollTemplate, vint, Position, 0)\ #define GuiScrollViewTemplate_PROPERTIES(F)\ F(GuiScrollViewTemplate, controls::GuiScroll*, HorizontalScroll, nullptr)\ F(GuiScrollViewTemplate, controls::GuiScroll*, VerticalScroll, nullptr)\ #define GuiMultilineTextBoxTemplate_PROPERTIES(F)\ F(GuiMultilineTextBoxTemplate, controls::ITextBoxCommandExecutor*, Commands, nullptr)\ F(GuiMultilineTextBoxTemplate, elements::text::ColorEntry, TextColor, {})\ F(GuiMultilineTextBoxTemplate, Color, CaretColor, {})\ #define GuiDocumentViewerTemplate_PROPERTIES(F)\ F(GuiDocumentViewerTemplate, Ptr, BaselineDocument, {})\ F(GuiDocumentViewerTemplate, Color, CaretColor, {})\ #define GuiListControlTemplate_PROPERTIES(F)\ F(GuiListControlTemplate, TemplateProperty, BackgroundTemplate, {})\ #define GuiTextListTemplate_PROPERTIES(F)\ F(GuiTextListTemplate, Color, TextColor, {})\ F(GuiTextListTemplate, TemplateProperty, CheckBulletTemplate, {})\ F(GuiTextListTemplate, TemplateProperty, RadioBulletTemplate, {})\ #define GuiListViewTemplate_PROPERTIES(F)\ F(GuiListViewTemplate, TemplateProperty, ColumnHeaderTemplate, {})\ F(GuiListViewTemplate, Color, PrimaryTextColor, {})\ F(GuiListViewTemplate, Color, SecondaryTextColor, {})\ F(GuiListViewTemplate, Color, ItemSeparatorColor, {})\ #define GuiTreeViewTemplate_PROPERTIES(F)\ F(GuiTreeViewTemplate, TemplateProperty, ExpandingDecoratorTemplate, {})\ F(GuiTreeViewTemplate, Color, TextColor, {})\ #define GuiTabTemplate_PROPERTIES(F)\ F(GuiTabTemplate, controls::ITabCommandExecutor*, Commands, nullptr)\ F(GuiTabTemplate, Ptr, TabPages, {})\ F(GuiTabTemplate, controls::GuiTabPage*, SelectedTabPage, nullptr)\ F(GuiTabTemplate, controls::TabPageOrder, TabOrder, controls::TabPageOrder::Unknown)\ #define GuiDatePickerTemplate_PROPERTIES(F)\ F(GuiDatePickerTemplate, controls::IDatePickerCommandExecutor*, Commands, nullptr)\ F(GuiDatePickerTemplate, Locale, DateLocale, {})\ F(GuiDatePickerTemplate, DateTime, Date, {})\ #define GuiDateComboBoxTemplate_PROPERTIES(F)\ F(GuiDateComboBoxTemplate, TemplateProperty, DatePickerTemplate, {})\ #define GuiRibbonTabTemplate_PROPERTIES(F)\ F(GuiRibbonTabTemplate, compositions::GuiGraphicsComposition*, BeforeHeadersContainer, nullptr)\ F(GuiRibbonTabTemplate, compositions::GuiGraphicsComposition*, AfterHeadersContainer, nullptr)\ #define GuiRibbonGroupTemplate_PROPERTIES(F)\ F(GuiRibbonGroupTemplate, controls::IRibbonGroupCommandExecutor*, Commands, nullptr)\ F(GuiRibbonGroupTemplate, bool, Expandable, false)\ F(GuiRibbonGroupTemplate, bool, Collapsed, false)\ F(GuiRibbonGroupTemplate, TemplateProperty, LargeDropdownButtonTemplate, {})\ F(GuiRibbonGroupTemplate, TemplateProperty, SubMenuTemplate, {})\ #define GuiRibbonIconLabelTemplate_PROPERTIES(F)\ F(GuiRibbonIconLabelTemplate, Ptr, Image, {})\ #define GuiRibbonButtonsTemplate_PROPERTIES(F)\ F(GuiRibbonButtonsTemplate, TemplateProperty, LargeButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, LargeDropdownButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, LargeSplitButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, SmallButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, SmallDropdownButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, SmallSplitButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, SmallIconLabelTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, IconButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, IconDropdownButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, IconSplitButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty, IconLabelTemplate, {})\ #define GuiRibbonToolstripsTemplate_PROPERTIES(F)\ F(GuiRibbonToolstripsTemplate, TemplateProperty, ToolbarTemplate, {})\ #define GuiRibbonToolstripMenuTemplate_PROPERTIES(F)\ F(GuiRibbonToolstripMenuTemplate, compositions::GuiGraphicsComposition*, ContentComposition, nullptr)\ #define GuiRibbonGalleryTemplate_PROPERTIES(F)\ F(GuiRibbonGalleryTemplate, controls::IRibbonGalleryCommandExecutor*, Commands, nullptr)\ F(GuiRibbonGalleryTemplate, bool, ScrollUpEnabled, true)\ F(GuiRibbonGalleryTemplate, bool, ScrollDownEnabled, true)\ #define GuiRibbonGalleryListTemplate_PROPERTIES(F)\ F(GuiRibbonGalleryListTemplate, TemplateProperty, ItemListTemplate, {})\ F(GuiRibbonGalleryListTemplate, TemplateProperty, MenuTemplate, {})\ F(GuiRibbonGalleryListTemplate, TemplateProperty, HeaderTemplate, {})\ F(GuiRibbonGalleryListTemplate, TemplateProperty, BackgroundTemplate, {})\ F(GuiRibbonGalleryListTemplate, TemplateProperty, GroupContainerTemplate, {})\ /*********************************************************************** Item Template ***********************************************************************/ #define GuiListItemTemplate_PROPERTIES(F)\ F(GuiListItemTemplate, bool, Selected, false)\ F(GuiListItemTemplate, vint, Index, 0)\ #define GuiTextListItemTemplate_PROPERTIES(F)\ F(GuiTextListItemTemplate, Color, TextColor, {})\ F(GuiTextListItemTemplate, bool, Checked, false)\ #define GuiTreeItemTemplate_PROPERTIES(F)\ F(GuiTreeItemTemplate, bool, Expanding, false)\ F(GuiTreeItemTemplate, bool, Expandable, false)\ F(GuiTreeItemTemplate, vint, Level, 0)\ F(GuiTreeItemTemplate, Ptr, Image, {})\ #define GuiGridCellTemplate_PROPERTIES(F)\ F(GuiGridCellTemplate, Color, PrimaryTextColor, {})\ F(GuiGridCellTemplate, Color, SecondaryTextColor, {})\ F(GuiGridCellTemplate, Color, ItemSeparatorColor, {})\ F(GuiGridCellTemplate, Ptr, LargeImage, {})\ F(GuiGridCellTemplate, Ptr, SmallImage, {})\ #define GuiGridVisualizerTemplate_PROPERTIES(F)\ F(GuiGridVisualizerTemplate, description::Value, RowValue, {})\ F(GuiGridVisualizerTemplate, description::Value, CellValue, {})\ F(GuiGridVisualizerTemplate, bool, Selected, false)\ #define GuiGridEditorTemplate_PROPERTIES(F)\ F(GuiGridEditorTemplate, description::Value, RowValue, {})\ F(GuiGridEditorTemplate, description::Value, CellValue, {})\ F(GuiGridEditorTemplate, bool, CellValueSaved, true)\ F(GuiGridEditorTemplate, controls::GuiControl*, FocusControl, nullptr)\ /*********************************************************************** Template Declarations ***********************************************************************/ GUI_CONTROL_TEMPLATE_DECL(GUI_TEMPLATE_CLASS_DECL) GUI_ITEM_TEMPLATE_DECL(GUI_TEMPLATE_CLASS_DECL) } } } #endif /*********************************************************************** .\CONTROLS\GUIBASICCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIBASICCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIBASICCONTROLS namespace vl { namespace presentation { namespace theme { enum class ThemeName; } namespace controls { template struct QueryServiceHelper; template struct QueryServiceHelper>> { static WString GetIdentifier() { return WString::Unmanaged(T::Identifier); } }; template struct QueryServiceHelper>> { static WString GetIdentifier() { return MoveValue(T::GetIdentifier()); } }; /*********************************************************************** Basic Construction ***********************************************************************/ /// /// A helper object to test if a control has been deleted or not. /// class GuiDisposedFlag : public Object, public Description { friend class GuiControl; protected: GuiControl* owner = nullptr; bool disposed = false; void SetDisposed(); public: GuiDisposedFlag(GuiControl* _owner); ~GuiDisposedFlag(); bool IsDisposed(); }; /// /// The base class of all controls. /// When the control is destroyed, it automatically destroys sub controls, and the bounds composition from the style controller. /// If you want to manually destroy a control, you should first remove it from its parent. /// The only way to remove a control from a parent control, is to remove the bounds composition from its parent composition. The same to inserting a control. /// class GuiControl : public Object , protected compositions::IGuiAltAction , protected compositions::IGuiTabAction , public Description { friend class compositions::GuiGraphicsComposition; protected: using ControlList = collections::List; using ControlServiceMap = collections::Dictionary>; using ControlTemplatePropertyType = TemplateProperty; using IGuiGraphicsEventHandler = compositions::IGuiGraphicsEventHandler; private: theme::ThemeName controlThemeName; ControlTemplatePropertyType controlTemplate; templates::GuiControlTemplate* controlTemplateObject = nullptr; Ptr disposedFlag; public: Ptr GetDisposedFlag(); protected: compositions::GuiBoundsComposition* boundsComposition = nullptr; compositions::GuiBoundsComposition* containerComposition = nullptr; compositions::GuiGraphicsComposition* focusableComposition = nullptr; compositions::GuiGraphicsEventReceiver* eventReceiver = nullptr; bool isFocused = false; Ptr gotFocusHandler; Ptr lostFocusHandler; bool acceptTabInput = false; vint tabPriority = -1; bool isEnabled = true; bool isVisuallyEnabled = true; bool isVisible = true; WString alt; WString text; Nullable font; FontProperties displayFont; description::Value context; compositions::IGuiAltActionHost* activatingAltHost = nullptr; ControlServiceMap controlServices; GuiControl* parent = nullptr; ControlList children; description::Value tag; GuiControl* tooltipControl = nullptr; vint tooltipWidth = 0; virtual void BeforeControlTemplateUninstalled(); virtual void AfterControlTemplateInstalled(bool initialize); virtual void CheckAndStoreControlTemplate(templates::GuiControlTemplate* value); virtual void EnsureControlTemplateExists(); virtual void RebuildControlTemplate(); virtual void OnChildInserted(GuiControl* control); virtual void OnChildRemoved(GuiControl* control); virtual void OnParentChanged(GuiControl* oldParent, GuiControl* newParent); virtual void OnParentLineChanged(); virtual void OnServiceAdded(); virtual void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget); virtual void OnBeforeReleaseGraphicsHost(); virtual void UpdateVisuallyEnabled(); virtual void UpdateDisplayFont(); void OnGotFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void SetFocusableComposition(compositions::GuiGraphicsComposition* value); bool IsControlVisibleAndEnabled(); bool IsAltEnabled()override; bool IsAltAvailable()override; compositions::GuiGraphicsComposition* GetAltComposition()override; compositions::IGuiAltActionHost* GetActivatingAltHost()override; void OnActiveAlt()override; bool IsTabEnabled()override; bool IsTabAvailable()override; static bool SharedPtrDestructorProc(DescriptableObject* obj, bool forceDisposing); public: using ControlTemplateType = templates::GuiControlTemplate; /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiControl(theme::ThemeName themeName); ~GuiControl(); /// Theme name changed event. This event raises when the theme name is changed. compositions::GuiNotifyEvent ControlThemeNameChanged; /// Control template changed event. This event raises when the control template is changed. compositions::GuiNotifyEvent ControlTemplateChanged; /// Control signal trigerred. This raises be raised because of multiple reason specified in the argument. compositions::GuiControlSignalEvent ControlSignalTrigerred; /// Visible event. This event raises when the visibility state of the control is changed. compositions::GuiNotifyEvent VisibleChanged; /// Enabled event. This event raises when the enabling state of the control is changed. compositions::GuiNotifyEvent EnabledChanged; /// Focused event. This event raises when the focusing state of the control is changed. compositions::GuiNotifyEvent FocusedChanged; /// /// Enabled event. This event raises when the visually enabling state of the control is changed. A visually enabling is combined by the enabling state and the parent's visually enabling state. /// A control is rendered as disabled, not only when the control itself is disabled, but also when the parent control is rendered as disabled. /// compositions::GuiNotifyEvent VisuallyEnabledChanged; /// Alt changed event. This event raises when the associated Alt-combined shortcut key of the control is changed. compositions::GuiNotifyEvent AltChanged; /// Text changed event. This event raises when the text of the control is changed. compositions::GuiNotifyEvent TextChanged; /// Font changed event. This event raises when the font of the control is changed. compositions::GuiNotifyEvent FontChanged; /// Display font changed event. This event raises when the display font of the control is changed. compositions::GuiNotifyEvent DisplayFontChanged; /// Context changed event. This event raises when the font of the control is changed. compositions::GuiNotifyEvent ContextChanged; void InvokeOrDelayIfRendering(Func proc); /// A function to create the argument for notify events that raised by itself. /// The created argument. compositions::GuiEventArgs GetNotifyEventArguments(); /// Get the associated theme name. /// The theme name. theme::ThemeName GetControlThemeName(); /// Set the associated control theme name. /// The theme name. void SetControlThemeName(theme::ThemeName value); /// Get the associated control template. /// The control template. ControlTemplatePropertyType GetControlTemplate(); /// Set the associated control template. /// The control template. void SetControlTemplate(const ControlTemplatePropertyType& value); /// Set the associated control theme name and template and the same time. /// The theme name. /// The control template. void SetControlThemeNameAndTemplate(theme::ThemeName themeNameValue, const ControlTemplatePropertyType& controlTemplateValue); /// Get the associated style controller. /// The associated style controller. templates::GuiControlTemplate* GetControlTemplateObject(); /// Get the bounds composition for the control. /// The bounds composition. compositions::GuiBoundsComposition* GetBoundsComposition(); /// Get the container composition for the control. /// The container composition. compositions::GuiGraphicsComposition* GetContainerComposition(); /// Get the focusable composition for the control. A focusable composition is the composition to be focused when the control is focused. /// The focusable composition. compositions::GuiGraphicsComposition* GetFocusableComposition(); /// Get the parent control. /// The parent control. GuiControl* GetParent(); /// Get the number of child controls. /// The number of child controls. vint GetChildrenCount(); /// Get the child control using a specified index. /// The child control. /// The specified index. GuiControl* GetChild(vint index); /// Put another control in the container composition of this control. /// Returns true if this operation succeeded. /// The control to put in this control. bool AddChild(GuiControl* control); /// Test if a control owned by this control. /// Returns true if the control is owned by this control. /// The control to test. bool HasChild(GuiControl* control); /// Get the that contains this control. /// The that contains this control. virtual GuiControlHost* GetRelatedControlHost(); /// Test if this control is rendered as enabled. /// Returns true if this control is rendered as enabled. virtual bool GetVisuallyEnabled(); /// Test if this control is focused. /// Returns true if this control is focused. virtual bool GetFocused(); /// Test if this control accepts tab character input. /// Returns true if this control accepts tab character input. virtual bool GetAcceptTabInput()override; /// Set if this control accepts tab character input. /// Set to true to make this control accept tab character input. void SetAcceptTabInput(bool value); /// Get the tab priority associated with this control. /// Returns he tab priority associated with this control. virtual vint GetTabPriority()override; /// Associate a tab priority with this control. /// The tab priority to associate. TAB key will go through controls in the order of priority: 0, 1, 2, ..., -1. All negative numbers will be converted to -1. The priority of containers affects all children if it is not -1. void SetTabPriority(vint value); /// Test if this control is enabled. /// Returns true if this control is enabled. virtual bool GetEnabled(); /// Make the control enabled or disabled. /// Set to true to make the control enabled. virtual void SetEnabled(bool value); /// Test if this visible or invisible. /// Returns true if this control is visible. virtual bool GetVisible(); /// Make the control visible or invisible. /// Set to true to make the visible enabled. virtual void SetVisible(bool value); /// Get the Alt-combined shortcut key associated with this control. /// The Alt-combined shortcut key associated with this control. virtual const WString& GetAlt()override; /// Associate a Alt-combined shortcut key with this control. /// Returns true if this operation succeeded. /// The Alt-combined shortcut key to associate. The key should contain only upper-case letters or digits. virtual bool SetAlt(const WString& value); /// Make the control as the parent of multiple Alt-combined shortcut key activatable controls. /// The alt action host object. void SetActivatingAltHost(compositions::IGuiAltActionHost* host); /// Get the text to display on the control. /// The text to display on the control. virtual const WString& GetText(); /// Set the text to display on the control. /// The text to display on the control. virtual void SetText(const WString& value); /// Get the font of this control. /// The font of this control. virtual const Nullable& GetFont(); /// Set the font of this control. /// The font of this control. virtual void SetFont(const Nullable& value); /// Get the font to render the text. If the font of this control is null, then the display font is either the parent control's display font, or the system's default font when there is no parent control. /// The font to render the text. virtual const FontProperties& GetDisplayFont(); /// Get the context of this control. The control template and all item templates (if it has) will see this context property. /// The context of this context. virtual description::Value GetContext(); /// Set the context of this control. /// The context of this control. virtual void SetContext(const description::Value& value); /// Focus this control. virtual void SetFocus(); /// Get the tag object of the control. /// The tag object of the control. description::Value GetTag(); /// Set the tag object of the control. /// The tag object of the control. void SetTag(const description::Value& value); /// Get the tooltip control of the control. /// The tooltip control of the control. GuiControl* GetTooltipControl(); /// Set the tooltip control of the control. The tooltip control will be released when this control is released. If you set a new tooltip control to replace the old one, the old one will not be owned by this control anymore, therefore user should release the old tooltip control manually. /// The old tooltip control. /// The tooltip control of the control. GuiControl* SetTooltipControl(GuiControl* value); /// Get the tooltip width of the control. /// The tooltip width of the control. vint GetTooltipWidth(); /// Set the tooltip width of the control. /// The tooltip width of the control. void SetTooltipWidth(vint value); /// Display the tooltip. /// Returns true if this operation succeeded. /// The relative location to specify the left-top position of the tooltip. bool DisplayTooltip(Point location); /// Close the tooltip that owned by this control. void CloseTooltip(); /// Query a service using an identifier. If you want to get a service of type IXXX, use IXXX::Identifier as the identifier. /// The requested service. If the control doesn't support this service, it will be null. /// The identifier. virtual IDescriptable* QueryService(const WString& identifier); template T* QueryTypedService() { return dynamic_cast(QueryService(QueryServiceHelper::GetIdentifier())); } templates::GuiControlTemplate* TypedControlTemplateObject(bool ensureExists) { if (ensureExists) { EnsureControlTemplateExists(); } return controlTemplateObject; } /// Add a service to this control dynamically. The added service cannot override existing services. /// Returns true if this operation succeeded. /// The identifier. You are suggested to fill this parameter using the value from the interface's GetIdentifier function, or will not work on this service. /// The service. bool AddService(const WString& identifier, Ptr value); }; /// Represnets a user customizable control. class GuiCustomControl : public GuiControl, public GuiInstanceRootObject, public AggregatableDescription { protected: controls::GuiControlHost* GetControlHostForInstance()override; void OnParentLineChanged()override; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiCustomControl(theme::ThemeName themeName); ~GuiCustomControl(); }; template class GuiObjectComponent : public GuiComponent { public: Ptr object; GuiObjectComponent() { } GuiObjectComponent(Ptr _object) :object(_object) { } }; #define GUI_GENERATE_CONTROL_TEMPLATE_OBJECT_NAME_3(UNIQUE) controlTemplateObject ## UNIQUE #define GUI_GENERATE_CONTROL_TEMPLATE_OBJECT_NAME_2(UNIQUE) GUI_GENERATE_CONTROL_TEMPLATE_OBJECT_NAME_3(UNIQUE) #define GUI_GENERATE_CONTROL_TEMPLATE_OBJECT_NAME GUI_GENERATE_CONTROL_TEMPLATE_OBJECT_NAME_2(__LINE__) #define GUI_SPECIFY_CONTROL_TEMPLATE_TYPE_2(TEMPLATE, BASE_TYPE, NAME) \ public: \ using ControlTemplateType = templates::Gui##TEMPLATE; \ private: \ templates::Gui##TEMPLATE* NAME = nullptr; \ void BeforeControlTemplateUninstalled_(); \ void AfterControlTemplateInstalled_(bool initialize); \ protected: \ void BeforeControlTemplateUninstalled()override \ {\ BeforeControlTemplateUninstalled_(); \ BASE_TYPE::BeforeControlTemplateUninstalled(); \ }\ void AfterControlTemplateInstalled(bool initialize)override \ {\ BASE_TYPE::AfterControlTemplateInstalled(initialize); \ AfterControlTemplateInstalled_(initialize); \ }\ void CheckAndStoreControlTemplate(templates::GuiControlTemplate* value)override \ { \ auto ct = dynamic_cast(value); \ CHECK_ERROR(ct, L"The assigned control template is not vl::presentation::templates::Gui" L ## # TEMPLATE L"."); \ NAME = ct; \ BASE_TYPE::CheckAndStoreControlTemplate(value); \ } \ public: \ templates::Gui##TEMPLATE* TypedControlTemplateObject(bool ensureExists) \ { \ if (ensureExists) \ { \ EnsureControlTemplateExists(); \ } \ return NAME; \ } \ private: \ #define GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(TEMPLATE, BASE_TYPE) GUI_SPECIFY_CONTROL_TEMPLATE_TYPE_2(TEMPLATE, BASE_TYPE, GUI_GENERATE_CONTROL_TEMPLATE_OBJECT_NAME) } } } #endif /*********************************************************************** .\CONTROLS\GUIBUTTONCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIBUTTONCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIBUTTONCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Buttons ***********************************************************************/ /// A control with 3 phases state transffering when mouse click happens. class GuiButton : public GuiControl, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ButtonTemplate, GuiControl) protected: bool clickOnMouseUp = true; bool ignoreChildControlMouseEvents = true; bool autoFocus = true; bool keyPressing = false; bool mousePressing = false; bool mouseHoving = false; ButtonState controlState = ButtonState::Normal; void OnParentLineChanged()override; void OnActiveAlt()override; bool IsTabAvailable()override; void UpdateControlState(); void CheckAndClick(compositions::GuiEventArgs& arguments); void OnLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); void OnKeyUp(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); void OnLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiButton(theme::ThemeName themeName); ~GuiButton(); /// Mouse click event. compositions::GuiNotifyEvent Clicked; /// Test is the event raised when left mouse button up. /// Returns true if this event is raised when left mouse button up bool GetClickOnMouseUp(); /// Set is the event raised when left mouse button up or not. /// Set to true to make this event raised when left mouse button up void SetClickOnMouseUp(bool value); /// Test if the button gets focus when it is clicked. /// Returns true if the button gets focus when it is clicked. bool GetAutoFocus(); /// Set if the button gets focus when it is clicked. /// Set to true to make this button get focus when it is clicked. void SetAutoFocus(bool value); /// /// Test if the button ignores mouse events raised in child controls. /// When this property is false, /// the button reacts to mouse operations even when it happens on contained child controls. /// /// Returns true if the button ignores mouse events raised in child controls. bool GetIgnoreChildControlMouseEvents(); /// Set if the button ignores mouse events raised in child controls. /// Set to true to make this button ignore mouse events raised in child controls. void SetIgnoreChildControlMouseEvents(bool value); }; /// A with a selection state. class GuiSelectableButton : public GuiButton, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(SelectableButtonTemplate, GuiButton) public: /// Selection group controller. Control the selection state of all attached button. class GroupController : public GuiComponent, public Description { protected: collections::List buttons; public: GroupController(); ~GroupController(); /// Called when the group controller is attached to a . use [M:vl.presentation.controls.GuiSelectableButton.SetGroupController] to attach or detach a group controller to or from a selectable button. /// The button to attach. virtual void Attach(GuiSelectableButton* button); /// Called when the group controller is deteched to a . use [M:vl.presentation.controls.GuiSelectableButton.SetGroupController] to attach or detach a group controller to or from a selectable button. /// The button to detach. virtual void Detach(GuiSelectableButton* button); /// Called when the selection state of any changed. /// The button that changed the selection state. virtual void OnSelectedChanged(GuiSelectableButton* button) = 0; }; /// A mutex group controller, usually for radio buttons. class MutexGroupController : public GroupController, public Description { protected: bool suppress; public: MutexGroupController(); ~MutexGroupController(); void OnSelectedChanged(GuiSelectableButton* button)override; }; protected: GroupController* groupController = nullptr; bool autoSelection = true; bool isSelected = false; void OnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiSelectableButton(theme::ThemeName themeName); ~GuiSelectableButton(); /// Group controller changed event. compositions::GuiNotifyEvent GroupControllerChanged; /// Auto selection changed event. compositions::GuiNotifyEvent AutoSelectionChanged; /// Selected changed event. compositions::GuiNotifyEvent SelectedChanged; /// Get the attached group controller. /// The attached group controller. virtual GroupController* GetGroupController(); /// Set the attached group controller. /// The attached group controller. virtual void SetGroupController(GroupController* value); /// Get the auto selection state. True if the button is automatically selected or unselected when the button is clicked. /// The auto selection state. virtual bool GetAutoSelection(); /// Set the auto selection state. True if the button is automatically selected or unselected when the button is clicked. /// The auto selection state. virtual void SetAutoSelection(bool value); /// Get the selected state. /// The selected state. virtual bool GetSelected(); /// Set the selected state. /// The selected state. virtual void SetSelected(bool value); }; } } } #endif /*********************************************************************** .\CONTROLS\GUIDIALOGS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDIALOGS #define VCZH_PRESENTATION_CONTROLS_GUIDIALOGS namespace vl { namespace presentation { namespace controls { class GuiWindow; /*********************************************************************** Dialogs ***********************************************************************/ /// Base class for dialogs. class GuiDialogBase abstract : public GuiComponent, public Description { protected: GuiInstanceRootObject* rootObject = nullptr; GuiWindow* GetHostWindow(); public: GuiDialogBase(); ~GuiDialogBase(); void Attach(GuiInstanceRootObject* _rootObject); void Detach(GuiInstanceRootObject* _rootObject); }; /// Message dialog. class GuiMessageDialog : public GuiDialogBase, public Description { protected: INativeDialogService::MessageBoxButtonsInput input = INativeDialogService::DisplayOK; INativeDialogService::MessageBoxDefaultButton defaultButton = INativeDialogService::DefaultFirst; INativeDialogService::MessageBoxIcons icon = INativeDialogService::IconNone; INativeDialogService::MessageBoxModalOptions modalOption = INativeDialogService::ModalWindow; WString text; WString title; public: /// Create a message dialog. GuiMessageDialog(); ~GuiMessageDialog(); /// Get the button combination that appear on the dialog. /// The button combination. INativeDialogService::MessageBoxButtonsInput GetInput(); /// Set the button combination that appear on the dialog. /// The button combination. void SetInput(INativeDialogService::MessageBoxButtonsInput value); /// Get the default button for the selected button combination. /// The default button. INativeDialogService::MessageBoxDefaultButton GetDefaultButton(); /// Set the default button for the selected button combination. /// The default button. void SetDefaultButton(INativeDialogService::MessageBoxDefaultButton value); /// Get the icon that appears on the dialog. /// The icon. INativeDialogService::MessageBoxIcons GetIcon(); /// Set the icon that appears on the dialog. /// The icon. void SetIcon(INativeDialogService::MessageBoxIcons value); /// Get the way that how this dialog disable windows of the current process. /// The way that how this dialog disable windows of the current process. INativeDialogService::MessageBoxModalOptions GetModalOption(); /// Set the way that how this dialog disable windows of the current process. /// The way that how this dialog disable windows of the current process. void SetModalOption(INativeDialogService::MessageBoxModalOptions value); /// Get the text for the dialog. /// The text. const WString& GetText(); /// Set the text for the dialog. /// The text. void SetText(const WString& value); /// Get the title for the dialog. /// The title. const WString& GetTitle(); /// Set the title for the dialog. If the title is empty, the dialog will use the title of the window that host this dialog. /// The title. void SetTitle(const WString& value); /// Show the dialog. /// Returns the clicked button. INativeDialogService::MessageBoxButtonsOutput ShowDialog(); }; /// Color dialog. class GuiColorDialog : public GuiDialogBase, public Description { protected: bool enabledCustomColor = true; bool openedCustomColor = false; Color selectedColor; bool showSelection = true; collections::List customColors; public: /// Create a color dialog. GuiColorDialog(); ~GuiColorDialog(); /// Selected color changed event. compositions::GuiNotifyEvent SelectedColorChanged; /// Get if the custom color panel is enabled for the dialog. /// Returns true if the color panel is enabled for the dialog. bool GetEnabledCustomColor(); /// Set if custom color panel is enabled for the dialog. /// Set to true to enable the custom color panel for the dialog. void SetEnabledCustomColor(bool value); /// Get if the custom color panel is opened by default when it is enabled. /// Returns true if the custom color panel is opened by default. bool GetOpenedCustomColor(); /// Set if the custom color panel is opened by default when it is enabled. /// Set to true to open custom color panel by default if it is enabled. void SetOpenedCustomColor(bool value); /// Get the selected color. /// The selected color. Color GetSelectedColor(); /// Set the selected color. /// The selected color. void SetSelectedColor(Color value); /// Get the list to access 16 selected custom colors on the palette. Colors in the list is guaranteed to have exactly 16 items after the dialog is closed. /// The list to access custom colors on the palette. collections::List& GetCustomColors(); /// Show the dialog. /// Returns true if the "OK" button is clicked. bool ShowDialog(); }; /// Font dialog. class GuiFontDialog : public GuiDialogBase, public Description { protected: FontProperties selectedFont; Color selectedColor; bool showSelection = true; bool showEffect = true; bool forceFontExist = true; public: /// Create a font dialog. GuiFontDialog(); ~GuiFontDialog(); /// Selected font changed event. compositions::GuiNotifyEvent SelectedFontChanged; /// Selected color changed event. compositions::GuiNotifyEvent SelectedColorChanged; /// Get the selected font. /// The selected font. const FontProperties& GetSelectedFont(); /// Set the selected font. /// The selected font. void SetSelectedFont(const FontProperties& value); /// Get the selected color. /// The selected color. Color GetSelectedColor(); /// Set the selected color. /// The selected color. void SetSelectedColor(Color value); /// Get if the selected font is already selected on the dialog when it is opened. /// Returns true if the selected font is already selected on the dialog when it is opened. bool GetShowSelection(); /// Set if the selected font is already selected on the dialog when it is opened. /// Set to true to select the selected font when the dialog is opened. void SetShowSelection(bool value); /// Get if the font preview is enabled. /// Returns true if the font preview is enabled. bool GetShowEffect(); /// Set if the font preview is enabled. /// Set to true to enable the font preview. void SetShowEffect(bool value); /// Get if the dialog only accepts an existing font. /// Returns true if the dialog only accepts an existing font. bool GetForceFontExist(); /// Set if the dialog only accepts an existing font. /// Set to true to let the dialog only accept an existing font. void SetForceFontExist(bool value); /// Show the dialog. /// Returns true if the "OK" button is clicked. bool ShowDialog(); }; /// Base class for file dialogs. class GuiFileDialogBase abstract : public GuiDialogBase, public Description { protected: WString filter = L"All Files (*.*)|*.*"; vint filterIndex = 0; bool enabledPreview = false; WString title; WString fileName; WString directory; WString defaultExtension; INativeDialogService::FileDialogOptions options; public: GuiFileDialogBase(); ~GuiFileDialogBase(); /// File name changed event. compositions::GuiNotifyEvent FileNameChanged; /// Filter index changed event. compositions::GuiNotifyEvent FilterIndexChanged; /// Get the filter. /// The filter. const WString& GetFilter(); /// Set the filter. The filter is formed by pairs of filter name and wildcard concatenated by "|", like "Text Files (*.txt)|*.txt|All Files (*.*)|*.*". /// The filter. void SetFilter(const WString& value); /// Get the filter index. /// The filter index. vint GetFilterIndex(); /// Set the filter index. /// The filter index. void SetFilterIndex(vint value); /// Get if the file preview is enabled. /// Returns true if the file preview is enabled. bool GetEnabledPreview(); /// Set if the file preview is enabled. /// Set to true to enable the file preview. void SetEnabledPreview(bool value); /// Get the title. /// The title. WString GetTitle(); /// Set the title. /// The title. void SetTitle(const WString& value); /// Get the selected file name. /// The selected file name. WString GetFileName(); /// Set the selected file name. /// The selected file name. void SetFileName(const WString& value); /// Get the default folder. /// The default folder. WString GetDirectory(); /// Set the default folder. /// The default folder. void SetDirectory(const WString& value); /// Get the default file extension. /// The default file extension. WString GetDefaultExtension(); /// Set the default file extension like "txt". If the user does not specify a file extension, the default file extension will be appended using "." after the file name. /// The default file extension. void SetDefaultExtension(const WString& value); /// Get the dialog options. /// The dialog options. INativeDialogService::FileDialogOptions GetOptions(); /// Set the dialog options. /// The dialog options. void SetOptions(INativeDialogService::FileDialogOptions value); }; /// Open file dialog. class GuiOpenFileDialog : public GuiFileDialogBase, public Description { protected: collections::List fileNames; public: /// Create a open file dialog. GuiOpenFileDialog(); ~GuiOpenFileDialog(); /// Get the list to access multiple selected file names. /// The list to access multiple selected file names. collections::List& GetFileNames(); /// Show the dialog. /// Returns true if the "Open" button is clicked. bool ShowDialog(); }; /// Save file dialog. class GuiSaveFileDialog : public GuiFileDialogBase, public Description { public: /// Create a save file dialog. GuiSaveFileDialog(); ~GuiSaveFileDialog(); /// Show the dialog. /// Returns true if the "Save" button is clicked. bool ShowDialog(); }; } } } #endif /*********************************************************************** .\CONTROLS\GUILABELCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILABELCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUILABELCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Label ***********************************************************************/ /// A control to display a text. class GuiLabel : public GuiControl, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(LabelTemplate, GuiControl) protected: Color textColor; bool textColorConsisted = true; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiLabel(theme::ThemeName themeName); ~GuiLabel(); /// Get the text color. /// The text color. Color GetTextColor(); /// Set the text color. /// The text color. void SetTextColor(Color value); }; } } } #endif /*********************************************************************** .\CONTROLS\GUISCROLLCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUISCROLLCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUISCROLLCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Scrolls ***********************************************************************/ /// A scroll control, which represents a one dimension sub range of a whole range. class GuiScroll : public GuiControl, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ScrollTemplate, GuiControl) protected: class CommandExecutor : public Object, public IScrollCommandExecutor { protected: GuiScroll* scroll; public: CommandExecutor(GuiScroll* _scroll); ~CommandExecutor(); void SmallDecrease()override; void SmallIncrease()override; void BigDecrease()override; void BigIncrease()override; void SetTotalSize(vint value)override; void SetPageSize(vint value)override; void SetPosition(vint value)override; }; Ptr commandExecutor; vint totalSize = 100; vint pageSize = 10; vint position = 0; vint smallMove = 1; vint bigMove = 10; bool autoFocus = true; void OnActiveAlt()override; bool IsTabAvailable()override; void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); void OnMouseDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiScroll(theme::ThemeName themeName); ~GuiScroll(); /// Total size changed event. compositions::GuiNotifyEvent TotalSizeChanged; /// Page size changed event. compositions::GuiNotifyEvent PageSizeChanged; /// Position changed event. compositions::GuiNotifyEvent PositionChanged; /// Small move changed event. compositions::GuiNotifyEvent SmallMoveChanged; /// Big move changed event. compositions::GuiNotifyEvent BigMoveChanged; /// Get the total size. /// The total size. virtual vint GetTotalSize(); /// Set the total size. /// The total size. virtual void SetTotalSize(vint value); /// Get the page size. /// The page size. virtual vint GetPageSize(); /// Set the page size. /// The page size. virtual void SetPageSize(vint value); /// Get the position. /// The position. virtual vint GetPosition(); /// Set the position. /// The position. virtual void SetPosition(vint value); /// Get the small move. /// The small move. virtual vint GetSmallMove(); /// Set the small move. /// The small move. virtual void SetSmallMove(vint value); /// Get the big move. /// The big move. virtual vint GetBigMove(); /// Set the big move. /// The big move. virtual void SetBigMove(vint value); /// Get the minimum possible position. /// The minimum possible position. vint GetMinPosition(); /// Get the maximum possible position. /// The maximum possible position. vint GetMaxPosition(); /// Test if the scroll gets focus when it is clicked. /// Returns true if the scroll gets focus when it is clicked bool GetAutoFocus(); /// Set if the scroll gets focus when it is clicked. /// Set to true to make this scroll get focus when it is clicked. void SetAutoFocus(bool value); }; } } } #endif /*********************************************************************** .\CONTROLS\GUICONTAINERCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUICONTAINERCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUICONTAINERCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Tab Control ***********************************************************************/ class GuiTabPageList; class GuiTab; /// Represnets a tab page control. class GuiTabPage : public GuiCustomControl, public AggregatableDescription { friend class GuiTabPageList; protected: GuiTab* tab = nullptr; bool IsAltAvailable()override; public: /// Create a tab page control with a specified style controller. /// The theme name for retriving a default control template. GuiTabPage(theme::ThemeName themeName); ~GuiTabPage(); GuiTab* GetOwnerTab(); }; class GuiTabPageList : public collections::ObservableList { protected: GuiTab* tab; bool QueryInsert(vint index, GuiTabPage* const& value)override; void AfterInsert(vint index, GuiTabPage* const& value)override; void BeforeRemove(vint index, GuiTabPage* const& value)override; public: GuiTabPageList(GuiTab* _tab); ~GuiTabPageList(); }; /// Represents a container with multiple named tabs. class GuiTab : public GuiControl, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(TabTemplate, GuiControl) friend class GuiTabPageList; protected: class CommandExecutor : public Object, public ITabCommandExecutor { protected: GuiTab* tab; public: CommandExecutor(GuiTab* _tab); ~CommandExecutor(); void ShowTab(vint index, bool setFocus)override; }; Ptr commandExecutor; GuiTabPageList tabPages; GuiTabPage* selectedPage = nullptr; void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiTab(theme::ThemeName themeName); ~GuiTab(); /// Selected page changed event. compositions::GuiNotifyEvent SelectedPageChanged; /// Get all pages. /// All pages. collections::ObservableList& GetPages(); /// Get the selected page. /// The selected page. GuiTabPage* GetSelectedPage(); /// Set the selected page. /// Returns true if this operation succeeded. /// The selected page. bool SetSelectedPage(GuiTabPage* value); }; /*********************************************************************** Scroll View ***********************************************************************/ /// A control with a vertical scroll bar and a horizontal scroll bar to perform partial viewing. class GuiScrollView : public GuiControl, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ScrollViewTemplate, GuiControl) using IEventHandler = compositions::IGuiGraphicsEventHandler; protected: bool supressScrolling = false; Ptr hScrollHandler; Ptr vScrollHandler; Ptr hWheelHandler; Ptr vWheelHandler; Ptr containerBoundsChangedHandler; bool horizontalAlwaysVisible = true; bool verticalAlwaysVisible = true; void UpdateDisplayFont()override; void OnContainerBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnHorizontalScroll(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnVerticalScroll(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnHorizontalWheel(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnVerticalWheel(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void CallUpdateView(); bool AdjustView(Size fullSize); /// Calculate the full size of the content. /// The full size of the content. virtual Size QueryFullSize()=0; /// Update the visible content using a view bounds. The view bounds is in the space from (0,0) to full size. /// The view bounds. virtual void UpdateView(Rect viewBounds)=0; /// Calculate the small move of the scroll bar. /// The small move of the scroll bar. virtual vint GetSmallMove(); /// Calculate the big move of the scroll bar. /// The big move of the scroll bar. virtual Size GetBigMove(); public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. GuiScrollView(theme::ThemeName themeName); ~GuiScrollView(); /// Force to update contents and scroll bars. void CalculateView(); /// Get the view size. /// The view size. Size GetViewSize(); /// Get the view bounds. /// The view bounds. Rect GetViewBounds(); /// Get the position of the left-top corner of the view bounds. /// The view position. Point GetViewPosition(); /// Set the position of the left-top corner of the view bounds. /// The position. void SetViewPosition(Point value); /// Get the horizontal scroll control. /// The horizontal scroll control. GuiScroll* GetHorizontalScroll(); /// Get the vertical scroll control. /// The vertical scroll control. GuiScroll* GetVerticalScroll(); /// Test is the horizontal scroll bar always visible even the content doesn't exceed the view bounds. /// Returns true if the horizontal scroll bar always visible even the content doesn't exceed the view bounds bool GetHorizontalAlwaysVisible(); /// Set is the horizontal scroll bar always visible even the content doesn't exceed the view bounds. /// Set to true if the horizontal scroll bar always visible even the content doesn't exceed the view bounds void SetHorizontalAlwaysVisible(bool value); /// Test is the vertical scroll bar always visible even the content doesn't exceed the view bounds. /// Returns true if the vertical scroll bar always visible even the content doesn't exceed the view bounds bool GetVerticalAlwaysVisible(); /// Set is the vertical scroll bar always visible even the content doesn't exceed the view bounds. /// Set to true if the vertical scroll bar always visible even the content doesn't exceed the view bounds void SetVerticalAlwaysVisible(bool value); }; /// A control container with a vertical scroll bar and a horizontal scroll bar to perform partial viewing. When controls are added, removed, moved or resized, the scroll bars will adjust automatically. class GuiScrollContainer : public GuiScrollView, public Description { protected: bool extendToFullWidth = false; bool extendToFullHeight = false; Size QueryFullSize()override; void UpdateView(Rect viewBounds)override; public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. GuiScrollContainer(theme::ThemeName themeName); ~GuiScrollContainer(); /// Test does the content container always extend its width to fill the scroll container. /// Return true if the content container always extend its width to fill the scroll container. bool GetExtendToFullWidth(); /// Set does the content container always extend its width to fill the scroll container. /// Set to true if the content container always extend its width to fill the scroll container. void SetExtendToFullWidth(bool value); /// Test does the content container always extend its height to fill the scroll container. /// Return true if the content container always extend its height to fill the scroll container. bool GetExtendToFullHeight(); /// Set does the content container always extend its height to fill the scroll container. /// Set to true if the content container always extend its height to fill the scroll container. void SetExtendToFullHeight(bool value); }; } } } #endif /*********************************************************************** .\CONTROLS\GUIWINDOWCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIWINDOWCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIWINDOWCONTROLS namespace vl { namespace presentation { namespace compositions { class IGuiShortcutKeyManager; class GuiGraphicsTimerManager; } namespace controls { /*********************************************************************** Control Host ***********************************************************************/ /// /// Represents a control that host by a . /// class GuiControlHost : public GuiControl, public GuiInstanceRootObject, protected INativeWindowListener, public Description { friend class compositions::GuiGraphicsHost; protected: compositions::GuiGraphicsHost* host; INativeWindow::WindowMode windowMode = INativeWindow::Normal; virtual void OnNativeWindowChanged(); virtual void OnVisualStatusChanged(); protected: static const vint TooltipDelayOpenTime = 500; static const vint TooltipDelayCloseTime = 500; static const vint TooltipDelayLifeTime = 5000; Ptr tooltipOpenDelay; Ptr tooltipCloseDelay; Point tooltipLocation; bool calledDestroyed = false; bool deleteWhenDestroyed = false; controls::GuiControlHost* GetControlHostForInstance()override; GuiControl* GetTooltipOwner(Point location); void MoveIntoTooltipControl(GuiControl* tooltipControl, Point location); void MouseMoving(const NativeWindowMouseInfo& info)override; void MouseLeaved()override; void Moved()override; void Enabled()override; void Disabled()override; void GotFocus()override; void LostFocus()override; void Activated()override; void Deactivated()override; void Opened()override; void Closing(bool& cancel)override; void Closed()override; void Destroying()override; virtual void UpdateClientSizeAfterRendering(Size preferredSize, Size clientSize); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. /// The window mode. GuiControlHost(theme::ThemeName themeName, INativeWindow::WindowMode mode); ~GuiControlHost(); /// Window got focus event. compositions::GuiNotifyEvent WindowGotFocus; /// Window lost focus event. compositions::GuiNotifyEvent WindowLostFocus; /// Window activated event. compositions::GuiNotifyEvent WindowActivated; /// Window deactivated event. compositions::GuiNotifyEvent WindowDeactivated; /// Window opened event. compositions::GuiNotifyEvent WindowOpened; /// Window closing event. compositions::GuiRequestEvent WindowClosing; /// Window closed event. compositions::GuiNotifyEvent WindowClosed; /// Window destroying event. compositions::GuiNotifyEvent WindowDestroying; /// Delete this control host after processing all events. void DeleteAfterProcessingAllEvents(); /// Get the internal object to host the window content. /// The internal object to host the window content. compositions::GuiGraphicsHost* GetGraphicsHost(); /// Get the main composition to host the window content. /// The main composition to host the window content. compositions::GuiGraphicsComposition* GetMainComposition(); /// Get the internal object to host the content. /// The the internal object to host the content. INativeWindow* GetNativeWindow(); /// Set the internal object to host the content. /// The the internal object to host the content. void SetNativeWindow(INativeWindow* window); /// Force to calculate layout and size immediately void ForceCalculateSizeImmediately(); /// Test is the window enabled. /// Returns true if the window is enabled. bool GetEnabled()override; /// Enable or disable the window. /// Set to true to enable the window. void SetEnabled(bool value)override; /// Test is the window focused. /// Returns true if the window is focused. bool GetFocused()override; /// Focus the window. A window with activation disabled cannot receive focus. void SetFocused(); /// Test is the window activated. /// Returns true if the window is activated. bool GetActivated(); /// Activate the window. If the window disabled activation, this function enables it again. void SetActivated(); /// Test is the window icon shown in the task bar. /// Returns true if the window is icon shown in the task bar. bool GetShowInTaskBar(); /// Show or hide the window icon in the task bar. /// Set to true to show the window icon in the task bar. void SetShowInTaskBar(bool value); /// Test is the window allowed to be activated. /// Returns true if the window is allowed to be activated. bool GetEnabledActivate(); /// /// Allow or forbid the window to be activated. /// Clicking a window with activation disabled doesn't bring activation and focus. /// Activation will be automatically enabled by calling or . /// /// Set to true to allow the window to be activated. void SetEnabledActivate(bool value); /// /// Test is the window always on top of the desktop. /// /// Returns true if the window is always on top of the desktop. bool GetTopMost(); /// /// Make the window always or never on top of the desktop. /// /// True to make the window always on top of the desktop. void SetTopMost(bool topmost); /// Get the attached with this control host. /// The shortcut key manager. compositions::IGuiShortcutKeyManager* GetShortcutKeyManager(); /// Attach or detach the associated with this control host. When this control host is disposing, the associated shortcut key manager will be deleted if exists. /// The shortcut key manager. Set to null to detach the previous shortcut key manager from this control host. void SetShortcutKeyManager(compositions::IGuiShortcutKeyManager* value); /// Get the timer manager. /// The timer manager. compositions::GuiGraphicsTimerManager* GetTimerManager(); /// Get the client size of the window. /// The client size of the window. Size GetClientSize(); /// Set the client size of the window. /// The client size of the window. void SetClientSize(Size value); /// Get the location of the window in screen space. /// The location of the window. NativePoint GetLocation(); /// Set the location of the window in screen space. /// The location of the window. void SetLocation(NativePoint value); /// Set the location in screen space and the client size of the window. /// The location of the window. /// The client size of the window. void SetBounds(NativePoint location, Size size); GuiControlHost* GetRelatedControlHost()override; const WString& GetText()override; void SetText(const WString& value)override; /// Get the screen that contains the window. /// The screen that contains the window. INativeScreen* GetRelatedScreen(); /// /// Show the window. /// If the window disabled activation, this function enables it again. /// void Show(); /// /// Show the window without activation. /// void ShowDeactivated(); /// /// Restore the window. /// void ShowRestored(); /// /// Maximize the window. /// void ShowMaximized(); /// /// Minimize the window. /// void ShowMinimized(); /// /// Hide the window. /// void Hide(); /// /// Close the window and destroy the internal object. /// void Close(); /// Test is the window opened. /// Returns true if the window is opened. bool GetOpening(); }; /*********************************************************************** Window ***********************************************************************/ /// /// Represents a normal window. /// class GuiWindow : public GuiControlHost, protected compositions::GuiAltActionHostBase, public AggregatableDescription { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(WindowTemplate, GuiControlHost) friend class GuiApplication; protected: compositions::IGuiAltActionHost* previousAltHost = nullptr; bool hasMaximizedBox = true; bool hasMinimizedBox = true; bool hasBorder = true; bool hasSizeBox = true; bool isIconVisible = true; bool hasTitleBar = true; Ptr icon; void UpdateCustomFramePadding(INativeWindow* window, templates::GuiWindowTemplate* ct); void SyncNativeWindowProperties(); void Moved()override; void DpiChanged()override; void OnNativeWindowChanged()override; void OnVisualStatusChanged()override; void OnWindowActivated(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnWindowDeactivated(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); /// Create a control with a specified default theme and a window mode. /// The theme name for retriving a default control template. /// The window mode. GuiWindow(theme::ThemeName themeName, INativeWindow::WindowMode mode); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiWindow(theme::ThemeName themeName); ~GuiWindow(); IDescriptable* QueryService(const WString& identifier)override; /// Clipboard updated event. compositions::GuiNotifyEvent ClipboardUpdated; /// Move the window to the center of the screen. If multiple screens exist, the window move to the screen that contains the biggest part of the window. void MoveToScreenCenter(); /// Move the window to the center of the specified screen. /// The screen. void MoveToScreenCenter(INativeScreen* screen); /// /// Test is the maximize box visible. /// /// Returns true if the maximize box is visible. bool GetMaximizedBox(); /// /// Make the maximize box visible or invisible. /// /// True to make the maximize box visible. void SetMaximizedBox(bool visible); /// /// Test is the minimize box visible. /// /// Returns true if the minimize box is visible. bool GetMinimizedBox(); /// /// Make the minimize box visible or invisible. /// /// True to make the minimize box visible. void SetMinimizedBox(bool visible); /// /// Test is the border visible. /// /// Returns true if the border is visible. bool GetBorder(); /// /// Make the border visible or invisible. /// /// True to make the border visible. void SetBorder(bool visible); /// /// Test is the size box visible. /// /// Returns true if the size box is visible. bool GetSizeBox(); /// /// Make the size box visible or invisible. /// /// True to make the size box visible. void SetSizeBox(bool visible); /// /// Test is the icon visible. /// /// Returns true if the icon is visible. bool GetIconVisible(); /// /// Make the icon visible or invisible. /// /// True to make the icon visible. void SetIconVisible(bool visible); /// /// Get the icon which replaces the default one. /// /// Returns the icon that replaces the default one. Ptr GetIcon(); /// /// Set the icon that replaces the default one. /// /// The icon that replaces the default one. void SetIcon(Ptr value); /// /// Test is the title bar visible. /// /// Returns true if the title bar is visible. bool GetTitleBar(); /// /// Make the title bar visible or invisible. /// /// True to make the title bar visible. void SetTitleBar(bool visible); /// /// Show a model window, get a callback when the window is closed. /// /// The window to disable as a parent window. /// The callback to call after the window is closed. void ShowModal(GuiWindow* owner, const Func& callback); /// /// Show a model window, get a callback when the window is closed, and then delete itself. /// /// The window to disable as a parent window. /// The callback to call after the window is closed. void ShowModalAndDelete(GuiWindow* owner, const Func& callback); /// /// Show a model window as an async operation, which ends when the window is closed. /// /// Returns true if the size box is visible. /// The window to disable as a parent window. Ptr ShowModalAsync(GuiWindow* owner); }; /// /// Represents a popup window. When the mouse click on other window or the desktop, the popup window will be closed automatically. /// class GuiPopup : public GuiWindow, public Description { protected: union PopupInfo { struct _s1 { NativePoint location; INativeScreen* screen; }; struct _s2 { GuiControl* control; INativeWindow* controlWindow; Rect bounds; bool preferredTopBottomSide; }; struct _s3 { GuiControl* control; INativeWindow* controlWindow; Point location; }; struct _s4 { GuiControl* control; INativeWindow* controlWindow; bool preferredTopBottomSide; }; _s1 _1; _s2 _2; _s3 _3; _s4 _4; PopupInfo() {} }; protected: vint popupType = -1; PopupInfo popupInfo; void UpdateClientSizeAfterRendering(Size preferredSize, Size clientSize)override; void PopupOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void PopupClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); static bool IsClippedByScreen(NativeSize size, NativePoint location, INativeScreen* screen); static NativePoint CalculatePopupPosition(NativeSize windowSize, NativePoint location, INativeScreen* screen); static NativePoint CalculatePopupPosition(NativeSize windowSize, GuiControl* control, INativeWindow* controlWindow, Rect bounds, bool preferredTopBottomSide); static NativePoint CalculatePopupPosition(NativeSize windowSize, GuiControl* control, INativeWindow* controlWindow, Point location); static NativePoint CalculatePopupPosition(NativeSize windowSize, GuiControl* control, INativeWindow* controlWindow, bool preferredTopBottomSide); static NativePoint CalculatePopupPosition(NativeSize windowSize, vint popupType, const PopupInfo& popupInfo); void ShowPopupInternal(); /// Create a control with a specified default theme and a window mode. /// The theme name for retriving a default control template. /// The window mode. GuiPopup(theme::ThemeName themeName, INativeWindow::WindowMode mode); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiPopup(theme::ThemeName themeName); ~GuiPopup(); /// Test will the whole popup window be in the screen if the popup's left-top position is set to a specified value. /// Returns true if the whole popup window will be in the screen. /// The specified left-top position. bool IsClippedByScreen(Point location); /// Show the popup window with the left-top position set to a specified value. The position of the popup window will be adjusted to make it totally inside the screen if possible. /// The specified left-top position. /// The expected screen. If you don't want to specify any screen, don't set this parameter. void ShowPopup(NativePoint location, INativeScreen* screen = 0); /// Show the popup window with the bounds set to a specified control-relative value. The position of the popup window will be adjusted to make it totally inside the screen if possible. /// The control that owns this popup temporary. And the location is relative to this control. /// The specified bounds. /// Set to true if the popup window is expected to be opened at the top or bottom side of that bounds. void ShowPopup(GuiControl* control, Rect bounds, bool preferredTopBottomSide); /// Show the popup window with the left-top position set to a specified control-relative value. The position of the popup window will be adjusted to make it totally inside the screen if possible. /// The control that owns this popup temporary. And the location is relative to this control. /// The specified left-top position. void ShowPopup(GuiControl* control, Point location); /// Show the popup window aligned with a specified control. The position of the popup window will be adjusted to make it totally inside the screen if possible. /// The control that owns this popup temporary. /// Set to true if the popup window is expected to be opened at the top or bottom side of that control. void ShowPopup(GuiControl* control, bool preferredTopBottomSide); }; /// Represents a tooltip window. class GuiTooltip : public GuiPopup, private INativeControllerListener, public Description { protected: GuiControl* temporaryContentControl = nullptr; void GlobalTimer()override; void TooltipOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void TooltipClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiTooltip(theme::ThemeName themeName); ~GuiTooltip(); /// Get the preferred content width. /// The preferred content width. vint GetPreferredContentWidth(); /// Set the preferred content width. /// The preferred content width. void SetPreferredContentWidth(vint value); /// Get the temporary content control. /// The temporary content control. GuiControl* GetTemporaryContentControl(); /// Set the temporary content control. /// The temporary content control. void SetTemporaryContentControl(GuiControl* control); }; } } } #endif /*********************************************************************** .\CONTROLS\GUIAPPLICATION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Application Framework Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIAPPLICATION #define VCZH_PRESENTATION_CONTROLS_GUIAPPLICATION namespace vl { namespace presentation { namespace controls { /*********************************************************************** Application ***********************************************************************/ /// Represents an GacUI application, for window management and asynchronized operation supporting. Use [M:vl.presentation.controls.GetApplication] to access the instance of this class. class GuiApplication : public Object, private INativeControllerListener, public Description { friend void GuiApplicationInitialize(); friend class GuiWindow; friend class GuiPopup; friend class Ptr; private: void InvokeClipboardNotify(compositions::GuiGraphicsComposition* composition, compositions::GuiEventArgs& arguments); void ClipboardUpdated()override; protected: Locale locale; GuiWindow* mainWindow = nullptr; GuiWindow* sharedTooltipOwnerWindow = nullptr; GuiControl* sharedTooltipOwner = nullptr; GuiTooltip* sharedTooltipControl = nullptr; bool sharedTooltipHovering = false; bool sharedTooltipClosing = false; collections::List windows; collections::SortedList openingPopups; GuiApplication(); ~GuiApplication(); INativeWindow* GetThreadContextNativeWindow(GuiControlHost* controlHost); void RegisterWindow(GuiWindow* window); void UnregisterWindow(GuiWindow* window); void RegisterPopupOpened(GuiPopup* popup); void RegisterPopupClosed(GuiPopup* popup); void TooltipMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void TooltipMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Locale changed event. Event LocaleChanged; /// Returns the selected locale for all windows. /// The selected locale. Locale GetLocale(); /// Set the locale for all windows. /// The selected locale. void SetLocale(Locale value); /// Run a as the main window and show it. This function can only be called once in the entry point. When the main window is closed or hiden, the Run function will finished, and the application should prepare for finalization. /// The main window. void Run(GuiWindow* _mainWindow); /// Get the main window. /// The main window. GuiWindow* GetMainWindow(); /// Get all created instances. This contains normal windows, popup windows, menus, or other types of windows that inherits from . /// All created instances. const collections::List& GetWindows(); /// Get the instance that the mouse cursor are directly in. /// The instance that the mouse cursor are directly in. /// The mouse cursor. GuiWindow* GetWindow(NativePoint location); /// Show a tooltip. /// The control that owns this tooltip temporary. /// The control as the tooltip content. This control is not owned by the tooltip. User should manually release this control if no longer needed (usually when the application exit). /// The preferred content width for this tooltip. /// The relative location to specify the left-top position of the tooltip. void ShowTooltip(GuiControl* owner, GuiControl* tooltip, vint preferredContentWidth, Point location); /// Close the tooltip void CloseTooltip(); /// Get the tooltip owner. When the tooltip closed, it returns null. /// The tooltip owner. GuiControl* GetTooltipOwner(); /// Get the file path of the current executable. /// The file path of the current executable. WString GetExecutablePath(); /// Get the folder of the current executable. /// The folder of the current executable. WString GetExecutableFolder(); /// Test is the current thread the main thread for GUI. /// Returns true if the current thread is the main thread for GUI. /// A control host to access the corressponding main thread. bool IsInMainThread(GuiControlHost* controlHost); /// Invoke a specified function asynchronously. /// The specified function. void InvokeAsync(const Func& proc); /// Invoke a specified function in the main thread. /// A control host to access the corressponding main thread. /// The specified function. void InvokeInMainThread(GuiControlHost* controlHost, const Func& proc); /// Invoke a specified function in the main thread and wait for the function to complete or timeout. /// Return true if the function complete. Return false if the function has not completed during a specified period of time. /// A control host to access the corressponding main thread. /// The specified function. /// The specified period of time to wait. Set to -1 (default value) to wait forever until the function completed. bool InvokeInMainThreadAndWait(GuiControlHost* controlHost, const Func& proc, vint milliseconds=-1); /// Delay execute a specified function with an specified argument asynchronisly. /// The Delay execution controller for this task. /// The specified function. /// Time to delay. Ptr DelayExecute(const Func& proc, vint milliseconds); /// Delay execute a specified function with an specified argument in the main thread. /// The Delay execution controller for this task. /// The specified function. /// Time to delay. Ptr DelayExecuteInMainThread(const Func& proc, vint milliseconds); /// Run the specified function in the main thread. If the caller is in the main thread, then run the specified function directly. /// A control host to access the corressponding main thread. /// The specified function. void RunGuiTask(GuiControlHost* controlHost, const Func& proc); template T RunGuiValue(GuiControlHost* controlHost, const Func& proc) { T result; RunGuiTask(controlHost, [&result, &proc]() { result=proc(); }); return result; } template void InvokeLambdaInMainThread(GuiControlHost* controlHost, const T& proc) { InvokeInMainThread(controlHost, Func(proc)); } template bool InvokeLambdaInMainThreadAndWait(GuiControlHost* controlHost, const T& proc, vint milliseconds=-1) { return InvokeInMainThreadAndWait(controlHost, Func(proc), milliseconds); } }; /*********************************************************************** Plugin ***********************************************************************/ /// Represents a plugin for the gui. class IGuiPlugin : public IDescriptable, public Description { public: /// Get the name of this plugin. /// Returns the name of the plugin. virtual WString GetName() = 0; /// Get all dependencies of this plugin. /// To receive all dependencies. virtual void GetDependencies(collections::List& dependencies) = 0; /// Called when the plugin manager want to load this plugin. virtual void Load()=0; /// Called when the plugin manager want to unload this plugin. virtual void Unload()=0; }; /// Represents a plugin manager. class IGuiPluginManager : public IDescriptable, public Description { public: /// Add a plugin before [F:vl.presentation.controls.IGuiPluginManager.Load] is called. /// The plugin. virtual void AddPlugin(Ptr plugin)=0; /// Load all plugins, and check if dependencies of all plugins are ready. virtual void Load()=0; /// Unload all plugins. virtual void Unload()=0; /// Returns true if all plugins are loaded. virtual bool IsLoaded()=0; }; /*********************************************************************** Helper Functions ***********************************************************************/ /// Get the global object. /// The global object. extern GuiApplication* GetApplication(); /// Get the global object. /// The global object. extern IGuiPluginManager* GetPluginManager(); /// Destroy the global object. extern void DestroyPluginManager(); } } } extern void GuiApplicationMain(); #define GUI_VALUE(x) vl::presentation::controls::GetApplication()->RunGuiValue(LAMBDA([&](){return (x);})) #define GUI_RUN(x) vl::presentation::controls::GetApplication()->RunGuiTask([=](){x}) #define GUI_REGISTER_PLUGIN(TYPE)\ class GuiRegisterPluginClass_##TYPE\ {\ public:\ GuiRegisterPluginClass_##TYPE()\ {\ vl::presentation::controls::GetPluginManager()->AddPlugin(new TYPE);\ }\ } instance_GuiRegisterPluginClass_##TYPE;\ #define GUI_PLUGIN_NAME(NAME)\ vl::WString GetName()override { return L ## #NAME; }\ void GetDependencies(vl::collections::List& dependencies)override\ #define GUI_PLUGIN_DEPEND(NAME) dependencies.Add(L ## #NAME) #endif /*********************************************************************** .\CONTROLS\INCLUDEFORWARD.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Application Framework Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_INCLUDEFORWARD #define VCZH_PRESENTATION_CONTROLS_INCLUDEFORWARD namespace vl { namespace presentation { namespace controls { class GuiControl; class GuiCustomControl; class GuiLabel; class GuiButton; class GuiSelectableButton; class GuiScroll; class GuiTabPage; class GuiTab; class GuiScrollView; class GuiScrollContainer; class GuiControlHost; class GuiWindow; class GuiPopup; class GuiTooltip; class GuiListControl; class GuiSelectableListControl; class GuiVirtualTextList; class GuiTextList; class GuiListViewColumnHeader; class GuiListViewBase; class GuiVirtualListView; class GuiListView; class GuiMenu; class GuiMenuBar; class GuiMenuButton; class GuiVirtualTreeListControl; class GuiVirtualTreeView; class GuiTreeView; class GuiComboBoxBase; class GuiComboBoxListControl; class GuiToolstripMenu; class GuiToolstripMenuBar; class GuiToolstripToolBar; class GuiToolstripButton; class GuiToolstripNestedContainer; class GuiToolstripGroupContainer; class GuiToolstripGroup; class GuiRibbonTab; class GuiRibbonTabPage; class GuiRibbonGroup; class GuiRibbonIconLabel; class GuiRibbonButtons; class GuiRibbonToolstrips; class GuiRibbonGallery; class GuiRibbonToolstripMenu; class GuiBindableRibbonGalleryList; class GuiDocumentViewer; class GuiDocumentLabel; class GuiMultilineTextBox; class GuiSinglelineTextBox; class GuiVirtualDataGrid; class GuiDatePicker; class GuiDateComboBox; class GuiBindableTextList; class GuiBindableListView; class GuiBindableTreeView; class GuiBindableDataGrid; } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUILISTCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILISTCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUILISTCONTROLS namespace vl { namespace presentation { namespace templates { class GuiListItemTemplate; } namespace controls { /*********************************************************************** List Control ***********************************************************************/ /// Represents a list control. A list control automatically read data sources and creates corresponding data item control from the item template. class GuiListControl : public GuiScrollView, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ListControlTemplate, GuiScrollView) public: class IItemProvider; using ItemStyle = templates::GuiListItemTemplate; using ItemStyleProperty = TemplateProperty; //----------------------------------------------------------- // Callback Interfaces //----------------------------------------------------------- /// Item provider callback. Item providers use this interface to notify item modification. class IItemProviderCallback : public virtual IDescriptable, public Description { public: /// Called when an item provider callback object is attached to an item provider. /// The item provider. virtual void OnAttached(IItemProvider* provider)=0; /// Called when items in the item provider is modified. /// The index of the first modified item. /// The number of all modified items. /// The number of new items. If items are inserted or removed, newCount may not equals to count. virtual void OnItemModified(vint start, vint count, vint newCount)=0; }; /// Item arranger callback. Item arrangers use this interface to communicate with the list control. When setting positions for item controls, functions in this callback object is suggested to call because they use the result from the [T:vl.presentation.controls.compositions.IGuiAxis]. class IItemArrangerCallback : public virtual IDescriptable, public Description { public: /// Request an item control representing an item in the item provider. This function is suggested to call when an item control gets into the visible area. /// The item control. /// The index of the item in the item provider. /// The composition that represents the item. Set to null if the item style is expected to be put directly into the list control. virtual ItemStyle* RequestItem(vint itemIndex, compositions::GuiBoundsComposition* itemComposition)=0; /// Release an item control. This function is suggested to call when an item control gets out of the visible area. /// The item control. virtual void ReleaseItem(ItemStyle* style)=0; /// Update the view location. The view location is the left-top position in the logic space of the list control. /// The new view location. virtual void SetViewLocation(Point value)=0; /// Get the preferred size of an item control. /// The preferred size of an item control. /// The item control. virtual Size GetStylePreferredSize(compositions::GuiBoundsComposition* style)=0; /// Set the alignment of an item control. /// The item control. /// The new alignment. virtual void SetStyleAlignmentToParent(compositions::GuiBoundsComposition* style, Margin margin)=0; /// Get the bounds of an item control. /// The bounds of an item control. /// The item control. virtual Rect GetStyleBounds(compositions::GuiBoundsComposition* style)=0; /// Set the bounds of an item control. /// The item control. /// The new bounds. virtual void SetStyleBounds(compositions::GuiBoundsComposition* style, Rect bounds)=0; /// Get the that directly contains item controls. /// The that directly contains item controls. virtual compositions::GuiGraphicsComposition* GetContainerComposition()=0; /// Notify the list control that the total size of all item controls are changed. virtual void OnTotalSizeChanged()=0; }; //----------------------------------------------------------- // Data Source Interfaces //----------------------------------------------------------- /// Item provider for a . class IItemProvider : public virtual IDescriptable, public Description { public: /// Attach an item provider callback to this item provider. /// Returns true if this operation succeeded. /// The item provider callback. virtual bool AttachCallback(IItemProviderCallback* value) = 0; /// Detach an item provider callback from this item provider. /// Returns true if this operation succeeded. /// The item provider callback. virtual bool DetachCallback(IItemProviderCallback* value) = 0; /// Increase the editing counter indicating that an [T:vl.presentation.templates.GuiListItemTemplate] is editing an item. virtual void PushEditing() = 0; /// Decrease the editing counter indicating that an [T:vl.presentation.templates.GuiListItemTemplate] has stopped editing an item. /// Returns false if there is no supression before calling this function. virtual bool PopEditing() = 0; /// Test if an [T:vl.presentation.templates.GuiListItemTemplate] is editing an item. /// Returns false if there is no editing. virtual bool IsEditing() = 0; /// Get the number of items in this item proivder. /// The number of items in this item proivder. virtual vint Count() = 0; /// Get the text representation of an item. /// The text representation of an item. /// The index of the item. virtual WString GetTextValue(vint itemIndex) = 0; /// Get the binding value of an item. /// The binding value of an item. /// The index of the item. virtual description::Value GetBindingValue(vint itemIndex) = 0; /// Request a view for this item provider. If the specified view is not supported, it returns null. If you want to get a view of type IXXX, use IXXX::Identifier as the identifier. /// The view object. /// The identifier for the requested view. virtual IDescriptable* RequestView(const WString& identifier) = 0; }; //----------------------------------------------------------- // Item Layout Interfaces //----------------------------------------------------------- /// EnsureItemVisible result for item arranger. enum class EnsureItemVisibleResult { /// The requested item does not exist. ItemNotExists, /// The view location is moved. Moved, /// The view location is not moved. NotMoved, }; /// Item arranger for a . Item arranger decides how to arrange and item controls. When implementing an item arranger, is suggested to use when calculating locations and sizes for item controls. class IItemArranger : public virtual IItemProviderCallback, public Description { public: /// Called when an item arranger in installed to a . /// The list control. virtual void AttachListControl(GuiListControl* value) = 0; /// Called when an item arranger in uninstalled from a . virtual void DetachListControl() = 0; /// Get the binded item arranger callback object. /// The binded item arranger callback object. virtual IItemArrangerCallback* GetCallback() = 0; /// Bind the item arranger callback object. /// The item arranger callback object to bind. virtual void SetCallback(IItemArrangerCallback* value) = 0; /// Get the total size of all data controls. /// The total size. virtual Size GetTotalSize() = 0; /// Get the item style controller for an visible item index. If an item is not visible, it returns null. /// The item style controller. /// The item index. virtual ItemStyle* GetVisibleStyle(vint itemIndex) = 0; /// Get the item index for an visible item style controller. If an item is not visible, it returns -1. /// The item index. /// The item style controller. virtual vint GetVisibleIndex(ItemStyle* style) = 0; /// Reload all visible items. virtual void ReloadVisibleStyles() = 0; /// Called when the visible area of item container is changed. /// The new visible area. virtual void OnViewChanged(Rect bounds) = 0; /// Find the item by an base item and a key direction. /// The item index that is found. Returns -1 if this operation failed. /// The base item index. /// The key direction. virtual vint FindItem(vint itemIndex, compositions::KeyDirection key) = 0; /// Adjust the view location to make an item visible. /// Returns the result of this operation. /// The item index of the item to be made visible. virtual EnsureItemVisibleResult EnsureItemVisible(vint itemIndex) = 0; /// Get the adopted size for the view bounds. /// The adopted size, making the vids bounds just enough to display several items. /// The expected size, to provide a guidance. virtual Size GetAdoptedSize(Size expectedSize) = 0; }; protected: //----------------------------------------------------------- // ItemCallback //----------------------------------------------------------- class ItemCallback : public IItemProviderCallback, public IItemArrangerCallback { typedef compositions::IGuiGraphicsEventHandler BoundsChangedHandler; typedef collections::List StyleList; typedef collections::Dictionary> InstalledStyleMap; protected: GuiListControl* listControl = nullptr; IItemProvider* itemProvider = nullptr; InstalledStyleMap installedStyles; Ptr InstallStyle(ItemStyle* style, vint itemIndex, compositions::GuiBoundsComposition* itemComposition); ItemStyle* UninstallStyle(vint index); void OnStyleBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: ItemCallback(GuiListControl* _listControl); ~ItemCallback(); void ClearCache(); void OnAttached(IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; ItemStyle* RequestItem(vint itemIndex, compositions::GuiBoundsComposition* itemComposition)override; void ReleaseItem(ItemStyle* style)override; void SetViewLocation(Point value)override; Size GetStylePreferredSize(compositions::GuiBoundsComposition* style)override; void SetStyleAlignmentToParent(compositions::GuiBoundsComposition* style, Margin margin)override; Rect GetStyleBounds(compositions::GuiBoundsComposition* style)override; void SetStyleBounds(compositions::GuiBoundsComposition* style, Rect bounds)override; compositions::GuiGraphicsComposition* GetContainerComposition()override; void OnTotalSizeChanged()override; }; //----------------------------------------------------------- // State management //----------------------------------------------------------- Ptr callback; Ptr itemProvider; ItemStyleProperty itemStyleProperty; Ptr itemArranger; Ptr axis; Size fullSize; bool displayItemBackground = true; virtual void OnItemModified(vint start, vint count, vint newCount); virtual void OnStyleInstalled(vint itemIndex, ItemStyle* style); virtual void OnStyleUninstalled(ItemStyle* style); void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)override; void OnBeforeReleaseGraphicsHost()override; Size QueryFullSize()override; void UpdateView(Rect viewBounds)override; void OnBoundsMouseButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void SetStyleAndArranger(ItemStyleProperty styleProperty, Ptr arranger); //----------------------------------------------------------- // Item event management //----------------------------------------------------------- class VisibleStyleHelper { public: Ptr leftButtonDownHandler; Ptr leftButtonUpHandler; Ptr leftButtonDoubleClickHandler; Ptr middleButtonDownHandler; Ptr middleButtonUpHandler; Ptr middleButtonDoubleClickHandler; Ptr rightButtonDownHandler; Ptr rightButtonUpHandler; Ptr rightButtonDoubleClickHandler; Ptr mouseMoveHandler; Ptr mouseEnterHandler; Ptr mouseLeaveHandler; }; friend class collections::ArrayBase>; collections::Dictionary> visibleStyles; void UpdateDisplayFont()override; void OnClientBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnVisuallyEnabledChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnContextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnItemMouseEvent(compositions::GuiItemMouseEvent& itemEvent, ItemStyle* style, compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnItemNotifyEvent(compositions::GuiItemNotifyEvent& itemEvent, ItemStyle* style, compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void AttachItemEvents(ItemStyle* style); void DetachItemEvents(ItemStyle* style); public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. /// The item provider as a data source. /// Set to true if the list control is allowed to have a keyboard focus. GuiListControl(theme::ThemeName themeName, IItemProvider* _itemProvider, bool acceptFocus=false); ~GuiListControl(); /// Style provider changed event. compositions::GuiNotifyEvent ItemTemplateChanged; /// Arranger changed event. compositions::GuiNotifyEvent ArrangerChanged; /// Coordinate transformer changed event. compositions::GuiNotifyEvent AxisChanged; /// Adopted size invalidated. compositions::GuiNotifyEvent AdoptedSizeInvalidated; /// Item left mouse button down event. compositions::GuiItemMouseEvent ItemLeftButtonDown; /// Item left mouse button up event. compositions::GuiItemMouseEvent ItemLeftButtonUp; /// Item left mouse button double click event. compositions::GuiItemMouseEvent ItemLeftButtonDoubleClick; /// Item middle mouse button down event. compositions::GuiItemMouseEvent ItemMiddleButtonDown; /// Item middle mouse button up event. compositions::GuiItemMouseEvent ItemMiddleButtonUp; /// Item middle mouse button double click event. compositions::GuiItemMouseEvent ItemMiddleButtonDoubleClick; /// Item right mouse button down event. compositions::GuiItemMouseEvent ItemRightButtonDown; /// Item right mouse button up event. compositions::GuiItemMouseEvent ItemRightButtonUp; /// Item right mouse button double click event. compositions::GuiItemMouseEvent ItemRightButtonDoubleClick; /// Item mouse move event. compositions::GuiItemMouseEvent ItemMouseMove; /// Item mouse enter event. compositions::GuiItemNotifyEvent ItemMouseEnter; /// Item mouse leave event. compositions::GuiItemNotifyEvent ItemMouseLeave; /// Get the item provider. /// The item provider. virtual IItemProvider* GetItemProvider(); /// Get the item style provider. /// The item style provider. virtual ItemStyleProperty GetItemTemplate(); /// Set the item style provider /// The new item style provider virtual void SetItemTemplate(ItemStyleProperty value); /// Get the item arranger. /// The item arranger. virtual IItemArranger* GetArranger(); /// Set the item arranger /// The new item arranger virtual void SetArranger(Ptr value); /// Get the item coordinate transformer. /// The item coordinate transformer. virtual compositions::IGuiAxis* GetAxis(); /// Set the item coordinate transformer /// The new item coordinate transformer virtual void SetAxis(Ptr value); /// Adjust the view location to make an item visible. /// Returns true if this operation succeeded. /// The item index of the item to be made visible. virtual bool EnsureItemVisible(vint itemIndex); /// Get the adopted size for the list control. /// The adopted size, making the list control just enough to display several items. /// The expected size, to provide a guidance. virtual Size GetAdoptedSize(Size expectedSize); /// Test if the list control displays predefined item background. /// Returns true if the list control displays predefined item background. bool GetDisplayItemBackground(); /// Set if the list control displays predefined item background. /// Set to true to display item background. void SetDisplayItemBackground(bool value); }; /*********************************************************************** Selectable List Control ***********************************************************************/ /// Represents a list control that each item is selectable. class GuiSelectableListControl : public GuiListControl, public Description { protected: collections::SortedList selectedItems; bool multiSelect; vint selectedItemIndexStart; vint selectedItemIndexEnd; void NotifySelectionChanged(); void OnItemModified(vint start, vint count, vint newCount)override; void OnStyleInstalled(vint itemIndex, ItemStyle* style)override; virtual void OnItemSelectionChanged(vint itemIndex, bool value); virtual void OnItemSelectionCleared(); void OnItemLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiItemMouseEventArgs& arguments); void OnItemRightButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiItemMouseEventArgs& arguments); void NormalizeSelectedItemIndexStartEnd(); void SetMultipleItemsSelectedSilently(vint start, vint end, bool selected); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. /// The item provider as a data source. GuiSelectableListControl(theme::ThemeName themeName, IItemProvider* _itemProvider); ~GuiSelectableListControl(); /// Selection changed event. compositions::GuiNotifyEvent SelectionChanged; /// Get the multiple selection mode. /// Returns true if multiple selection is enabled. bool GetMultiSelect(); /// Set the multiple selection mode. /// Set to true to enable multiple selection. void SetMultiSelect(bool value); /// Get indices of all selected items. /// Indices of all selected items. const collections::SortedList& GetSelectedItems(); /// Get the index of the selected item. /// Returns the index of the selected item. If there are multiple selected items, or there is no selected item, -1 will be returned. vint GetSelectedItemIndex(); /// Get the text of the selected item. /// Returns the text of the selected item. If there are multiple selected items, or there is no selected item, an empty string will be returned. WString GetSelectedItemText(); /// Get the selection status of an item. /// The selection status of an item. /// The index of the item. bool GetSelected(vint itemIndex); /// Set the selection status of an item. /// The index of the item. /// Set to true to select the item. void SetSelected(vint itemIndex, bool value); /// Set the selection status of an item, and affect other selected item according to key status. /// Returns true if this operation succeeded. /// The index of the item. /// Set to true if the control key is pressing. /// Set to true if the shift key is pressing. /// Set to true if clicked by left mouse button, otherwise right mouse button. bool SelectItemsByClick(vint itemIndex, bool ctrl, bool shift, bool leftButton); /// Set the selection status using keys. /// Returns true if this operation succeeded. /// The key code that is pressing. /// Set to true if the control key is pressing. /// Set to true if the shift key is pressing. bool SelectItemsByKey(VKEY code, bool ctrl, bool shift); /// Unselect all items. void ClearSelection(); }; /*********************************************************************** Predefined ItemProvider ***********************************************************************/ namespace list { /// Item provider base. This class provider common functionalities for item providers. class ItemProviderBase : public Object, public virtual GuiListControl::IItemProvider, public Description { protected: collections::List callbacks; vint editingCounter = 0; bool callingOnItemModified = false; virtual void InvokeOnItemModified(vint start, vint count, vint newCount); public: /// Create the item provider. ItemProviderBase(); ~ItemProviderBase(); bool AttachCallback(GuiListControl::IItemProviderCallback* value)override; bool DetachCallback(GuiListControl::IItemProviderCallback* value)override; void PushEditing()override; bool PopEditing()override; bool IsEditing()override; }; template class ListProvider : public ItemProviderBase, public collections::ObservableListBase { protected: void NotifyUpdateInternal(vint start, vint count, vint newCount)override { InvokeOnItemModified(start, count, newCount); } public: vint Count()override { return this->items.Count(); } }; } } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUILISTCONTROLITEMARRANGERS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILISTCONTROLITEMARRANGERS #define VCZH_PRESENTATION_CONTROLS_GUILISTCONTROLITEMARRANGERS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Predefined ItemArranger ***********************************************************************/ namespace list { /// Ranged item arranger. This arranger implements most of the common functionality for those arrangers that display a continuing subset of item at a time. class RangedItemArrangerBase : public Object, virtual public GuiListControl::IItemArranger, public Description { protected: using ItemStyleRecord = collections::Pair; typedef collections::List StyleList; GuiListControl* listControl = nullptr; GuiListControl::IItemArrangerCallback* callback = nullptr; GuiListControl::IItemProvider* itemProvider = nullptr; bool suppressOnViewChanged = false; Rect viewBounds; vint startIndex = 0; StyleList visibleStyles; protected: void InvalidateAdoptedSize(); vint CalculateAdoptedSize(vint expectedSize, vint count, vint itemSize); ItemStyleRecord CreateStyle(vint index); void DeleteStyle(ItemStyleRecord style); compositions::GuiBoundsComposition* GetStyleBounds(ItemStyleRecord style); void ClearStyles(); void OnViewChangedInternal(Rect oldBounds, Rect newBounds); virtual void RearrangeItemBounds(); virtual void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex) = 0; virtual void PlaceItem(bool forMoving, bool newCreatedStyle, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent) = 0; virtual bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds) = 0; virtual bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex) = 0; virtual void InvalidateItemSizeCache() = 0; virtual Size OnCalculateTotalSize() = 0; public: /// Create the arranger. RangedItemArrangerBase(); ~RangedItemArrangerBase(); void OnAttached(GuiListControl::IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; GuiListControl::IItemArrangerCallback* GetCallback()override; void SetCallback(GuiListControl::IItemArrangerCallback* value)override; Size GetTotalSize()override; GuiListControl::ItemStyle* GetVisibleStyle(vint itemIndex)override; vint GetVisibleIndex(GuiListControl::ItemStyle* style)override; void ReloadVisibleStyles()override; void OnViewChanged(Rect bounds)override; }; /// Free height item arranger. This arranger will cache heights of all items. class FreeHeightItemArranger : public RangedItemArrangerBase, public Description { private: bool pim_heightUpdated = false; protected: collections::Array heights; collections::Array offsets; vint availableOffsetCount = 0; void EnsureOffsetForItem(vint itemIndex); void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex)override; void PlaceItem(bool forMoving, bool newCreatedStyle, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent)override; bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds)override; bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex)override; void InvalidateItemSizeCache()override; Size OnCalculateTotalSize()override; public: /// Create the arranger. FreeHeightItemArranger(); ~FreeHeightItemArranger(); void OnAttached(GuiListControl::IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; vint FindItem(vint itemIndex, compositions::KeyDirection key)override; GuiListControl::EnsureItemVisibleResult EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; /// Fixed height item arranger. This arranger lists all item with the same height value. This value is the maximum height of all minimum heights of displayed items. class FixedHeightItemArranger : public RangedItemArrangerBase, public Description { private: vint pi_width = 0; vint pim_rowHeight = 0; protected: vint rowHeight = 1; virtual vint GetWidth(); virtual vint GetYOffset(); void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex)override; void PlaceItem(bool forMoving, bool newCreatedStyle, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent)override; bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds)override; bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex)override; void InvalidateItemSizeCache()override; Size OnCalculateTotalSize()override; public: /// Create the arranger. FixedHeightItemArranger(); ~FixedHeightItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; GuiListControl::EnsureItemVisibleResult EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; /// Fixed size multiple columns item arranger. This arranger adjust all items in multiple lines with the same size. The width is the maximum width of all minimum widths of displayed items. The same to height. class FixedSizeMultiColumnItemArranger : public RangedItemArrangerBase, public Description { private: Size pim_itemSize; protected: Size itemSize{ 1,1 }; void CalculateRange(Size itemSize, Rect bounds, vint count, vint& start, vint& end); void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex)override; void PlaceItem(bool forMoving, bool newCreatedStyle, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent)override; bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds)override; bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex)override; void InvalidateItemSizeCache()override; Size OnCalculateTotalSize()override; public: /// Create the arranger. FixedSizeMultiColumnItemArranger(); ~FixedSizeMultiColumnItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; GuiListControl::EnsureItemVisibleResult EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; /// Fixed size multiple columns item arranger. This arranger adjust all items in multiple columns with the same height. The height is the maximum width of all minimum height of displayed items. Each item will displayed using its minimum width. class FixedHeightMultiColumnItemArranger : public RangedItemArrangerBase, public Description { private: vint pi_currentWidth = 0; vint pi_totalWidth = 0; vint pim_itemHeight = 0; protected: vint itemHeight; void CalculateRange(vint itemHeight, Rect bounds, vint& rows, vint& startColumn); void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex)override; void PlaceItem(bool forMoving, bool newCreatedStyle, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent)override; bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds)override; bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex)override; void InvalidateItemSizeCache()override; Size OnCalculateTotalSize()override; public: /// Create the arranger. FixedHeightMultiColumnItemArranger(); ~FixedHeightMultiColumnItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; GuiListControl::EnsureItemVisibleResult EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; } } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUITEXTLISTCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTLISTCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUITEXTLISTCONTROLS namespace vl { namespace presentation { namespace controls { class GuiVirtualTextList; class GuiTextList; namespace list { /*********************************************************************** DefaultTextListItemTemplate ***********************************************************************/ /// The required view for . class ITextItemView : public virtual IDescriptable, public Description { public: /// The identifier for this view. static const wchar_t* const Identifier; /// Get the check state of an item. /// The check state of an item. /// The index of an item. virtual bool GetChecked(vint itemIndex) = 0; /// Set the check state of an item without invoving any UI action. /// The index of an item. /// The new check state. virtual void SetChecked(vint itemIndex, bool value) = 0; }; class DefaultTextListItemTemplate : public templates::GuiTextListItemTemplate { protected: using BulletStyle = templates::GuiControlTemplate; GuiSelectableButton* bulletButton = nullptr; elements::GuiSolidLabelElement* textElement = nullptr; bool supressEdit = false; virtual TemplateProperty CreateBulletStyle(); void OnInitialize()override; void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextColorChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnCheckedChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBulletSelectedChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: DefaultTextListItemTemplate(); ~DefaultTextListItemTemplate(); }; class DefaultCheckTextListItemTemplate : public DefaultTextListItemTemplate { protected: TemplateProperty CreateBulletStyle()override; public: }; class DefaultRadioTextListItemTemplate : public DefaultTextListItemTemplate { protected: TemplateProperty CreateBulletStyle()override; public: }; /*********************************************************************** TextItemProvider ***********************************************************************/ class TextItemProvider; /// Text item. This is the item data structure for [T:vl.presentation.controls.list.TextItemProvider]. class TextItem : public Object, public Description { friend class TextItemProvider; protected: TextItemProvider* owner; WString text; bool checked; public: /// Create an empty text item. TextItem(); /// Create a text item with specified text and check state. /// The text. /// The check state. TextItem(const WString& _text, bool _checked=false); ~TextItem(); bool operator==(const TextItem& value)const; bool operator!=(const TextItem& value)const; /// Get the text of this item. /// The text of this item. const WString& GetText(); /// Set the text of this item. /// The text of this item. void SetText(const WString& value); /// Get the check state of this item. /// The check state of this item. bool GetChecked(); /// Set the check state of this item. /// The check state of this item. void SetChecked(bool value); }; /// Item provider for or . class TextItemProvider : public ListProvider> , protected ITextItemView , public Description { friend class TextItem; friend class vl::presentation::controls::GuiTextList; protected: GuiTextList* listControl; void AfterInsert(vint item, const Ptr& value)override; void BeforeRemove(vint item, const Ptr& value)override; WString GetTextValue(vint itemIndex)override; description::Value GetBindingValue(vint itemIndex)override; bool GetChecked(vint itemIndex)override; void SetChecked(vint itemIndex, bool value)override; public: TextItemProvider(); ~TextItemProvider(); IDescriptable* RequestView(const WString& identifier)override; }; } /*********************************************************************** GuiVirtualTextList ***********************************************************************/ enum class TextListView { Text, Check, Radio, Unknown, }; /// Text list control in virtual mode. class GuiVirtualTextList : public GuiSelectableListControl, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(TextListTemplate, GuiSelectableListControl) protected: TextListView view = TextListView::Unknown; void OnStyleInstalled(vint itemIndex, ItemStyle* style)override; void OnItemTemplateChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a Text list control in virtual mode. /// The theme name for retriving a default control template. /// The item provider for this control. GuiVirtualTextList(theme::ThemeName themeName, GuiListControl::IItemProvider* _itemProvider); ~GuiVirtualTextList(); /// Item checked changed event. compositions::GuiItemNotifyEvent ItemChecked; /// Get the current view. /// The current view. After [M:vl.presentation.controls.GuiListControl.SetItemTemplate] is called, the current view is reset to Unknown. TextListView GetView(); /// Set the current view. /// The current view. void SetView(TextListView _view); }; /*********************************************************************** GuiTextList ***********************************************************************/ /// Text list control. class GuiTextList : public GuiVirtualTextList, public Description { protected: list::TextItemProvider* items; public: /// Create a Text list control. /// The theme name for retriving a default control template. GuiTextList(theme::ThemeName themeName); ~GuiTextList(); /// Get all text items. /// All text items. list::TextItemProvider& GetItems(); /// Get the selected item. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. Ptr GetSelectedItem(); }; } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUITREEVIEWCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITREEVIEWCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUITREEVIEWCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** NodeItemProvider ***********************************************************************/ namespace tree { class INodeProvider; class INodeRootProvider; //----------------------------------------------------------- // Callback Interfaces //----------------------------------------------------------- /// Callback object for . A node will invoke this callback to notify any content modification. class INodeProviderCallback : public virtual IDescriptable, public Description { public: /// Called when this callback is attached to a node root. /// The root node. virtual void OnAttached(INodeRootProvider* provider)=0; /// Called before sub items of a node are modified. /// The node containing modified sub items. /// The index of the first sub item. /// The number of sub items to be modified. /// The new number of modified sub items. virtual void OnBeforeItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)=0; /// Called after sub items of a node are modified. /// The node containing modified sub items. /// The index of the first sub item. /// The number of sub items to be modified. /// The new number of modified sub items. virtual void OnAfterItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)=0; /// Called when a node is expanded. /// The node. virtual void OnItemExpanded(INodeProvider* node)=0; /// Called when a node is collapsed. /// The node. virtual void OnItemCollapsed(INodeProvider* node)=0; }; //----------------------------------------------------------- // Provider Interfaces //----------------------------------------------------------- /// Represents a node. class INodeProvider : public virtual IDescriptable, public Description { public: /// Get the expanding state of this node. /// Returns true if this node is expanded. virtual bool GetExpanding()=0; /// Set the expanding state of this node. /// Set to true to expand this node. virtual void SetExpanding(bool value)=0; /// Calculate the number of total visible nodes of this node. The number of total visible nodes includes the node itself, and all total visible nodes of all visible sub nodes. If this node is collapsed, this number will be 1. /// The number of total visible nodes. virtual vint CalculateTotalVisibleNodes()=0; /// Get the number of all sub nodes. /// The number of all sub nodes. virtual vint GetChildCount()=0; /// Get the parent node. /// The parent node. virtual Ptr GetParent()=0; /// Get the instance of a specified sub node. /// The instance of a specified sub node. /// The index of the sub node. virtual Ptr GetChild(vint index)=0; }; /// Represents a root node provider. class INodeRootProvider : public virtual IDescriptable, public Description { public: /// Get the instance of the root node. /// Returns the instance of the root node. virtual Ptr GetRootNode()=0; /// Test does the provider provided an optimized algorithm to get an instance of a node by the index of all visible nodes. If this function returns true, [M:vl.presentation.controls.tree.INodeRootProvider.GetNodeByVisibleIndex] can be used. /// Returns true if such an algorithm is provided. virtual bool CanGetNodeByVisibleIndex()=0; /// Get a node by the index in all visible nodes. This requires [M:vl.presentation.controls.tree.INodeRootProvider.CanGetNodeByVisibleIndex] returning true. /// The node for the index in all visible nodes. /// The index in all visible nodes. virtual Ptr GetNodeByVisibleIndex(vint index)=0; /// Attach an node provider callback to this node provider. /// Returns true if this operation succeeded. /// The node provider callback. virtual bool AttachCallback(INodeProviderCallback* value)=0; /// Detach an node provider callback from this node provider. /// Returns true if this operation succeeded. /// The node provider callback. virtual bool DetachCallback(INodeProviderCallback* value)=0; /// Get the primary text of a node. /// The primary text of a node. /// The node. virtual WString GetTextValue(INodeProvider* node) = 0; /// Get the binding value of a node. /// The binding value of a node. /// The node. virtual description::Value GetBindingValue(INodeProvider* node) = 0; /// Request a view for this node provider. If the specified view is not supported, it returns null. If you want to get a view of type IXXX, use IXXX::Identifier as the identifier. /// The view object. /// The identifier for the requested view. virtual IDescriptable* RequestView(const WString& identifier)=0; }; } namespace tree { //----------------------------------------------------------- // Tree to ListControl (IItemProvider) //----------------------------------------------------------- /// The required view for [T:vl.presentation.controls.tree.GuiVirtualTreeView]. [T:vl.presentation.controls.tree.NodeItemProvider] provides this view. In most of the cases, the NodeItemProvider class and this view is not required users to create, or even to touch. [T:vl.presentation.controls.GuiVirtualTreeListControl] already handled all of this. class INodeItemView : public virtual IDescriptable, public Description { public: /// The identifier of this view. static const wchar_t* const Identifier; /// Get an instance of a node by the index in all visible nodes. /// The instance of a node by the index in all visible nodes. /// The index in all visible nodes. virtual Ptr RequestNode(vint index)=0; /// Get the index in all visible nodes of a node. /// The index in all visible nodes of a node. /// The node to calculate the index. virtual vint CalculateNodeVisibilityIndex(INodeProvider* node)=0; }; /// This is a general implementation to convert an to a . class NodeItemProvider : public list::ItemProviderBase , protected virtual INodeProviderCallback , public virtual INodeItemView , public Description { typedef collections::Dictionary NodeIntMap; protected: Ptr root; NodeIntMap offsetBeforeChildModifieds; Ptr GetNodeByOffset(Ptr provider, vint offset); void OnAttached(INodeRootProvider* provider)override; void OnBeforeItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnAfterItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnItemExpanded(INodeProvider* node)override; void OnItemCollapsed(INodeProvider* node)override; vint CalculateNodeVisibilityIndexInternal(INodeProvider* node); vint CalculateNodeVisibilityIndex(INodeProvider* node)override; Ptr RequestNode(vint index)override; public: /// Create an item provider using a node root provider. /// The node root provider. NodeItemProvider(Ptr _root); ~NodeItemProvider(); /// Get the owned node root provider. /// The node root provider. Ptr GetRoot(); vint Count()override; WString GetTextValue(vint itemIndex)override; description::Value GetBindingValue(vint itemIndex)override; IDescriptable* RequestView(const WString& identifier)override; }; } /*********************************************************************** MemoryNodeProvider ***********************************************************************/ namespace tree { /// An in-memory implementation. class MemoryNodeProvider : public Object , public virtual INodeProvider , public Description { typedef collections::List> ChildList; typedef collections::IEnumerator> ChildListEnumerator; public: class NodeCollection : public collections::ObservableListBase> { friend class MemoryNodeProvider; protected: vint offsetBeforeChildModified = 0; MemoryNodeProvider* ownerProvider; void OnBeforeChildModified(vint start, vint count, vint newCount); void OnAfterChildModified(vint start, vint count, vint newCount); bool QueryInsert(vint index, Ptr const& child)override; bool QueryRemove(vint index, Ptr const& child)override; void BeforeInsert(vint index, Ptr const& child)override; void BeforeRemove(vint index, Ptr const& child)override; void AfterInsert(vint index, Ptr const& child)override; void AfterRemove(vint index, vint count)override; NodeCollection(); public: }; protected: MemoryNodeProvider* parent = nullptr; bool expanding = false; vint childCount = 0; vint totalVisibleNodeCount = 1; Ptr data; NodeCollection children; virtual INodeProviderCallback* GetCallbackProxyInternal(); void OnChildTotalVisibleNodesChanged(vint offset); public: /// Create a node provider with a data object. /// The data object. MemoryNodeProvider(Ptr _data = nullptr); ~MemoryNodeProvider(); /// Get the data object. /// The data object. Ptr GetData(); /// Set the data object. /// The data object. void SetData(const Ptr& value); /// Notify that the state in the binded data object is modified. void NotifyDataModified(); /// Get all sub nodes. /// All sub nodes. NodeCollection& Children(); bool GetExpanding()override; void SetExpanding(bool value)override; vint CalculateTotalVisibleNodes()override; vint GetChildCount()override; Ptr GetParent()override; Ptr GetChild(vint index)override; }; /// A general implementation for . class NodeRootProviderBase : public virtual INodeRootProvider, protected virtual INodeProviderCallback, public Description { collections::List callbacks; protected: void OnAttached(INodeRootProvider* provider)override; void OnBeforeItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnAfterItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnItemExpanded(INodeProvider* node)override; void OnItemCollapsed(INodeProvider* node)override; public: /// Create a node root provider. NodeRootProviderBase(); ~NodeRootProviderBase(); bool CanGetNodeByVisibleIndex()override; Ptr GetNodeByVisibleIndex(vint index)override; bool AttachCallback(INodeProviderCallback* value)override; bool DetachCallback(INodeProviderCallback* value)override; IDescriptable* RequestView(const WString& identifier)override; }; /// An in-memory implementation. class MemoryNodeRootProvider : public MemoryNodeProvider , public NodeRootProviderBase , public Description { protected: INodeProviderCallback* GetCallbackProxyInternal()override; public: /// Create a node root provider. MemoryNodeRootProvider(); ~MemoryNodeRootProvider(); Ptr GetRootNode()override; /// Get the object from an object. /// The corresponding object. /// The node to get the memory node. MemoryNodeProvider* GetMemoryNode(INodeProvider* node); }; } /*********************************************************************** GuiVirtualTreeListControl ***********************************************************************/ /// Tree list control in virtual node. class GuiVirtualTreeListControl : public GuiSelectableListControl, protected virtual tree::INodeProviderCallback, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(TreeViewTemplate, GuiSelectableListControl) protected: void OnAttached(tree::INodeRootProvider* provider)override; void OnBeforeItemModified(tree::INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnAfterItemModified(tree::INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnItemExpanded(tree::INodeProvider* node)override; void OnItemCollapsed(tree::INodeProvider* node)override; protected: tree::NodeItemProvider* nodeItemProvider; tree::INodeItemView* nodeItemView; void OnItemMouseEvent(compositions::GuiNodeMouseEvent& nodeEvent, compositions::GuiGraphicsComposition* sender, compositions::GuiItemMouseEventArgs& arguments); void OnItemNotifyEvent(compositions::GuiNodeNotifyEvent& nodeEvent, compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); void OnNodeLeftButtonDoubleClick(compositions::GuiGraphicsComposition* sender, compositions::GuiNodeMouseEventArgs& arguments); public: /// Create a tree list control in virtual mode. /// The theme name for retriving a default control template. /// The node root provider for this control. GuiVirtualTreeListControl(theme::ThemeName themeName, Ptr _nodeRootProvider); ~GuiVirtualTreeListControl(); /// Node left mouse button down event. compositions::GuiNodeMouseEvent NodeLeftButtonDown; /// Node left mouse button up event. compositions::GuiNodeMouseEvent NodeLeftButtonUp; /// Node left mouse button double click event. compositions::GuiNodeMouseEvent NodeLeftButtonDoubleClick; /// Node middle mouse button down event. compositions::GuiNodeMouseEvent NodeMiddleButtonDown; /// Node middle mouse button up event. compositions::GuiNodeMouseEvent NodeMiddleButtonUp; /// Node middle mouse button double click event. compositions::GuiNodeMouseEvent NodeMiddleButtonDoubleClick; /// Node right mouse button down event. compositions::GuiNodeMouseEvent NodeRightButtonDown; /// Node right mouse button up event. compositions::GuiNodeMouseEvent NodeRightButtonUp; /// Node right mouse button double click event. compositions::GuiNodeMouseEvent NodeRightButtonDoubleClick; /// Node mouse move event. compositions::GuiNodeMouseEvent NodeMouseMove; /// Node mouse enter event. compositions::GuiNodeNotifyEvent NodeMouseEnter; /// Node mouse leave event. compositions::GuiNodeNotifyEvent NodeMouseLeave; /// Node expanded event. compositions::GuiNodeNotifyEvent NodeExpanded; /// Node collapsed event. compositions::GuiNodeNotifyEvent NodeCollapsed; /// Get the from the item provider. /// The from the item provider. tree::INodeItemView* GetNodeItemView(); /// Get the binded node root provider. /// The binded node root provider. tree::INodeRootProvider* GetNodeRootProvider(); }; /*********************************************************************** TreeViewItemRootProvider ***********************************************************************/ namespace tree { /// The required view for [T:vl.presentation.controls.GuiVirtualTreeView]. class ITreeViewItemView : public virtual IDescriptable, public Description { public: /// The identifier of this view. static const wchar_t* const Identifier; /// Get the image of a node. /// Get the image of a node. /// The node. virtual Ptr GetNodeImage(INodeProvider* node)=0; }; /// A tree view item. This data structure is used in [T:vl.presentation.controls.tree.TreeViewItemRootProvider]. class TreeViewItem : public Object, public Description { public: /// The image of this item. Ptr image; /// The text of this item. WString text; /// Tag object. description::Value tag; /// Create a tree view item. TreeViewItem(); /// Create a tree view item with specified image and text. /// The specified image. /// The specified text. TreeViewItem(const Ptr& _image, const WString& _text); }; /// The default implementation of for [T:vl.presentation.controls.GuiVirtualTreeView]. class TreeViewItemRootProvider : public MemoryNodeRootProvider , public virtual ITreeViewItemView , public Description { protected: Ptr GetNodeImage(INodeProvider* node)override; WString GetTextValue(INodeProvider* node)override; description::Value GetBindingValue(INodeProvider* node)override; public: /// Create a item root provider. TreeViewItemRootProvider(); ~TreeViewItemRootProvider(); IDescriptable* RequestView(const WString& identifier)override; /// Get the object from a node. /// The object. /// The node to get the tree view item. Ptr GetTreeViewData(INodeProvider* node); /// Set the object to a node. /// The node. /// The object. void SetTreeViewData(INodeProvider* node, Ptr value); /// Notify the tree view control that the node is changed. This is required when content in a is modified, but both or [M:vl.presentation.controls.tree.MemoryNodeProvider.SetData] are not called. /// The node. void UpdateTreeViewData(INodeProvider* node); }; } /*********************************************************************** GuiVirtualTreeView ***********************************************************************/ /// Tree view control in virtual mode. class GuiVirtualTreeView : public GuiVirtualTreeListControl, public Description { protected: tree::ITreeViewItemView* treeViewItemView = nullptr; templates::GuiTreeItemTemplate* GetStyleFromNode(tree::INodeProvider* node); void SetStyleExpanding(tree::INodeProvider* node, bool expanding); void SetStyleExpandable(tree::INodeProvider* node, bool expandable); void OnAfterItemModified(tree::INodeProvider* parentNode, vint start, vint count, vint newCount)override; void OnItemExpanded(tree::INodeProvider* node)override; void OnItemCollapsed(tree::INodeProvider* node)override; void OnStyleInstalled(vint itemIndex, ItemStyle* style)override; public: /// Create a tree view control in virtual mode. /// The theme name for retriving a default control template. /// The node root provider for this control. GuiVirtualTreeView(theme::ThemeName themeName, Ptr _nodeRootProvider); ~GuiVirtualTreeView(); }; /*********************************************************************** GuiTreeView ***********************************************************************/ /// Tree view control. class GuiTreeView : public GuiVirtualTreeView, public Description { protected: Ptr nodes; public: /// Create a tree view control. /// The theme name for retriving a default control template. GuiTreeView(theme::ThemeName themeName); ~GuiTreeView(); /// Get the as a node root providerl. /// The as a node root provider. Ptr Nodes(); /// Get the selected item. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. Ptr GetSelectedItem(); }; /*********************************************************************** DefaultTreeItemTemplate ***********************************************************************/ namespace tree { class DefaultTreeItemTemplate : public templates::GuiTreeItemTemplate { protected: GuiSelectableButton* expandingButton = nullptr; compositions::GuiTableComposition* table = nullptr; elements::GuiImageFrameElement* imageElement = nullptr; elements::GuiSolidLabelElement* textElement = nullptr; void OnInitialize()override; void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextColorChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnExpandingChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnExpandableChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnLevelChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnImageChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnExpandingButtonDoubleClick(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnExpandingButtonClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: DefaultTreeItemTemplate(); ~DefaultTreeItemTemplate(); }; } } } namespace collections { namespace randomaccess_internal { template<> struct RandomAccessable { static const bool CanRead = true; static const bool CanResize = false; }; } } } #endif /*********************************************************************** .\CONTROLS\TEMPLATES\GUICOMMONTEMPLATES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Template System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_TEMPLATES_GUICOMMONTEMPLATES #define VCZH_PRESENTATION_CONTROLS_TEMPLATES_GUICOMMONTEMPLATES namespace vl { namespace presentation { namespace templates { /*********************************************************************** GuiCommonDatePickerLook ***********************************************************************/ class GuiCommonDatePickerLook : public GuiTemplate, public Description { protected: static const vint DaysOfWeek = 7; static const vint DayRows = 6; static const vint DayRowStart = 2; static const vint YearFirst = 1900; static const vint YearLast = 2099; Color backgroundColor; Color primaryTextColor; Color secondaryTextColor; DateTime currentDate; Locale dateLocale; FontProperties font; TemplateProperty dateButtonTemplate; TemplateProperty dateTextListTemplate; TemplateProperty dateComboBoxTemplate; controls::IDatePickerCommandExecutor* commands = nullptr; bool preventComboEvent = false; bool preventButtonEvent = false; controls::GuiComboBoxListControl* comboYear; controls::GuiTextList* listYears; controls::GuiComboBoxListControl* comboMonth; controls::GuiTextList* listMonths; collections::Array labelDaysOfWeek; collections::Array buttonDays; collections::Array labelDays; collections::Array dateDays; void SetDay(const DateTime& day, vint& index, vint monthOffset); void DisplayMonth(vint year, vint month); void SelectDay(vint day); void comboYearMonth_SelectedIndexChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void buttonDay_SelectedChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiCommonDatePickerLook(Color _backgroundColor, Color _primaryTextColor, Color _secondaryTextColor); ~GuiCommonDatePickerLook(); compositions::GuiNotifyEvent DateChanged; controls::IDatePickerCommandExecutor* GetCommands(); void SetCommands(controls::IDatePickerCommandExecutor* value); TemplateProperty GetDateButtonTemplate(); void SetDateButtonTemplate(const TemplateProperty& value); TemplateProperty GetDateTextListTemplate(); void SetDateTextListTemplate(const TemplateProperty& value); TemplateProperty GetDateComboBoxTemplate(); void SetDateComboBoxTemplate(const TemplateProperty& value); const Locale& GetDateLocale(); void SetDateLocale(const Locale& value); const DateTime& GetDate(); void SetDate(const DateTime& value); const FontProperties& GetFont(); void SetFont(const FontProperties& value); }; /*********************************************************************** GuiCommonScrollViewLook ***********************************************************************/ class GuiCommonScrollViewLook : public GuiTemplate, public Description { protected: controls::GuiScroll* horizontalScroll = nullptr; controls::GuiScroll* verticalScroll = nullptr; compositions::GuiTableComposition* tableComposition = nullptr; compositions::GuiCellComposition* containerCellComposition = nullptr; compositions::GuiBoundsComposition* containerComposition = nullptr; vint defaultScrollSize = 12; TemplateProperty hScrollTemplate; TemplateProperty vScrollTemplate; void UpdateTable(); void hScroll_OnVisibleChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void vScroll_OnVisibleChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: GuiCommonScrollViewLook(vint _defaultScrollSize); ~GuiCommonScrollViewLook(); controls::GuiScroll* GetHScroll(); controls::GuiScroll* GetVScroll(); compositions::GuiGraphicsComposition* GetContainerComposition(); TemplateProperty GetHScrollTemplate(); void SetHScrollTemplate(const TemplateProperty& value); TemplateProperty GetVScrollTemplate(); void SetVScrollTemplate(const TemplateProperty& value); }; /*********************************************************************** GuiCommonScrollBehavior ***********************************************************************/ class GuiCommonScrollBehavior : public controls::GuiComponent, public Description { protected: bool dragging = false; Point location = { 0,0 }; GuiScrollTemplate* scrollTemplate = nullptr; void SetScroll(vint totalPixels, vint newOffset); void AttachHandle(compositions::GuiGraphicsComposition* handle); public: GuiCommonScrollBehavior(); ~GuiCommonScrollBehavior(); void AttachScrollTemplate(GuiScrollTemplate* value); void AttachDecreaseButton(controls::GuiButton* button); void AttachIncreaseButton(controls::GuiButton* button); void AttachHorizontalScrollHandle(compositions::GuiPartialViewComposition* partialView); void AttachVerticalScrollHandle(compositions::GuiPartialViewComposition* partialView); void AttachHorizontalTrackerHandle(compositions::GuiPartialViewComposition* partialView); void AttachVerticalTrackerHandle(compositions::GuiPartialViewComposition* partialView); vint GetHorizontalTrackerHandlerPosition(compositions::GuiBoundsComposition* handle, vint totalSize, vint pageSize, vint position); vint GetVerticalTrackerHandlerPosition(compositions::GuiBoundsComposition* handle, vint totalSize, vint pageSize, vint position); }; } } } #endif /*********************************************************************** .\CONTROLS\TEMPLATES\GUITHEMESTYLEFACTORY.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control Styles::Common Style Helpers Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITHEMESTYLEFACTORY #define VCZH_PRESENTATION_CONTROLS_GUITHEMESTYLEFACTORY namespace vl { namespace presentation { namespace theme { #define GUI_CONTROL_TEMPLATE_TYPES(F) \ F(WindowTemplate, Window) \ F(ControlTemplate, CustomControl) \ F(WindowTemplate, Tooltip) \ F(LabelTemplate, Label) \ F(LabelTemplate, ShortcutKey) \ F(ScrollViewTemplate, ScrollView) \ F(ControlTemplate, GroupBox) \ F(TabTemplate, Tab) \ F(ComboBoxTemplate, ComboBox) \ F(MultilineTextBoxTemplate, MultilineTextBox) \ F(SinglelineTextBoxTemplate, SinglelineTextBox) \ F(DocumentViewerTemplate, DocumentViewer) \ F(DocumentLabelTemplate, DocumentLabel) \ F(DocumentLabelTemplate, DocumentTextBox) \ F(ListViewTemplate, ListView) \ F(TreeViewTemplate, TreeView) \ F(TextListTemplate, TextList) \ F(SelectableButtonTemplate, ListItemBackground) \ F(SelectableButtonTemplate, TreeItemExpander) \ F(SelectableButtonTemplate, CheckTextListItem) \ F(SelectableButtonTemplate, RadioTextListItem) \ F(MenuTemplate, Menu) \ F(ControlTemplate, MenuBar) \ F(ControlTemplate, MenuSplitter) \ F(ToolstripButtonTemplate, MenuBarButton) \ F(ToolstripButtonTemplate, MenuItemButton) \ F(ControlTemplate, ToolstripToolBar) \ F(ToolstripButtonTemplate, ToolstripButton) \ F(ToolstripButtonTemplate, ToolstripDropdownButton) \ F(ToolstripButtonTemplate, ToolstripSplitButton) \ F(ControlTemplate, ToolstripSplitter) \ F(RibbonTabTemplate, RibbonTab) \ F(RibbonGroupTemplate, RibbonGroup) \ F(RibbonIconLabelTemplate, RibbonIconLabel) \ F(RibbonIconLabelTemplate, RibbonSmallIconLabel) \ F(RibbonButtonsTemplate, RibbonButtons) \ F(RibbonToolstripsTemplate, RibbonToolstrips) \ F(RibbonGalleryTemplate, RibbonGallery) \ F(RibbonToolstripMenuTemplate, RibbonToolstripMenu) \ F(RibbonGalleryListTemplate, RibbonGalleryList) \ F(TextListTemplate, RibbonGalleryItemList) \ F(ToolstripButtonTemplate, RibbonSmallButton) \ F(ToolstripButtonTemplate, RibbonSmallDropdownButton) \ F(ToolstripButtonTemplate, RibbonSmallSplitButton) \ F(ToolstripButtonTemplate, RibbonLargeButton) \ F(ToolstripButtonTemplate, RibbonLargeDropdownButton) \ F(ToolstripButtonTemplate, RibbonLargeSplitButton) \ F(ControlTemplate, RibbonSplitter) \ F(ControlTemplate, RibbonToolstripHeader) \ F(ButtonTemplate, Button) \ F(SelectableButtonTemplate, CheckBox) \ F(SelectableButtonTemplate, RadioButton) \ F(DatePickerTemplate, DatePicker) \ F(DateComboBoxTemplate, DateComboBox) \ F(ScrollTemplate, HScroll) \ F(ScrollTemplate, VScroll) \ F(ScrollTemplate, HTracker) \ F(ScrollTemplate, VTracker) \ F(ScrollTemplate, ProgressBar) \ enum class ThemeName { Unknown, #define GUI_DEFINE_THEME_NAME(TEMPLATE, CONTROL) CONTROL, GUI_CONTROL_TEMPLATE_TYPES(GUI_DEFINE_THEME_NAME) #undef GUI_DEFINE_THEME_NAME }; /// Theme interface. A theme creates appropriate style controllers or style providers for default controls. Call [M:vl.presentation.theme.GetCurrentTheme] to access this interface. class ITheme : public virtual IDescriptable, public Description { public: virtual TemplateProperty CreateStyle(ThemeName themeName) = 0; }; class Theme; /// Partial control template collections. [F:vl.presentation.theme.GetCurrentTheme] will returns an object, which walks through multiple registered [T:vl.presentation.theme.ThemeTemplates] to create a correct template object for a control. class ThemeTemplates : public controls::GuiInstanceRootObject, public AggregatableDescription { friend class Theme; protected: ThemeTemplates* previous = nullptr; ThemeTemplates* next = nullptr; controls::GuiControlHost* GetControlHostForInstance()override; public: ~ThemeTemplates(); WString Name; #define GUI_DEFINE_ITEM_PROPERTY(TEMPLATE, CONTROL) TemplateProperty CONTROL; GUI_CONTROL_TEMPLATE_TYPES(GUI_DEFINE_ITEM_PROPERTY) #undef GUI_DEFINE_ITEM_PROPERTY }; /// Get the current theme style factory object. Call or to change the default theme. /// The current theme style factory object. extern ITheme* GetCurrentTheme(); extern void InitializeTheme(); extern void FinalizeTheme(); /// Register a control template collection object. /// Returns true if this operation succeeded. /// The control template collection object. extern bool RegisterTheme(Ptr theme); /// Unregister a control template collection object. /// The registered object. Returns null if it does not exist. /// The name of the theme. extern Ptr UnregisterTheme(const WString& name); } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\EDITORCALLBACK\GUITEXTGENERALOPERATIONS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTGENERALOPERATIONS #define VCZH_PRESENTATION_CONTROLS_GUITEXTGENERALOPERATIONS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Common Operations ***********************************************************************/ /// An text edit callback for text box controls. class ICommonTextEditCallback : public virtual IDescriptable, public Description { public: /// Callback data for text editing preview. struct TextEditPreviewStruct { /// The start position of the selection before replacing. This field can be modified. TextPos originalStart; /// The end position of the selection before replacing. This field can be modified. TextPos originalEnd; /// The text of the selection before replacing. WString originalText; /// The text of the selection after replacing. This field can be modified. WString inputText; /// The base edit version. vuint editVersion = 0; /// True if this modification is raised by the keyboard. bool keyInput = false; }; /// Callback data for text editing. struct TextEditNotifyStruct { /// The start position of the selection before replacing. TextPos originalStart; /// The end position of the selection before replacing. TextPos originalEnd; /// The text of the selection before replacing. WString originalText; /// The start position of the selection after replacing. TextPos inputStart; /// The end position of the selection after replacing. TextPos inputEnd; /// The text of the selection after replacing. WString inputText; /// The created edit version. vuint editVersion = 0; /// True if this modification is raised by the keyboard. bool keyInput = false; }; /// Callback data for text caret changing. struct TextCaretChangedStruct { /// The start position of the selection before caret changing. TextPos oldBegin; /// The end position of the selection before caret changing. TextPos oldEnd; /// The start position of the selection after caret changing. TextPos newBegin; /// The end position of the selection after caret changing. TextPos newEnd; /// The current edit version. vuint editVersion = 0; }; /// Called when the callback is attached to a text box control. /// The element that used in the text box control. /// The lock that pretect the element. /// The owner composition of this element. /// The current edit version. virtual void Attach(elements::GuiColorizedTextElement* element, SpinLock& elementModifyLock, compositions::GuiGraphicsComposition* ownerComposition, vuint editVersion)=0; /// Called when the callback is detached from a text box control. virtual void Detach()=0; /// Called before the text is edited. /// The data for this callback. virtual void TextEditPreview(TextEditPreviewStruct& arguments)=0; /// Called after the text is edited and before the caret is changed. /// The data for this callback. virtual void TextEditNotify(const TextEditNotifyStruct& arguments)=0; /// Called after the caret is changed. /// The data for this callback. virtual void TextCaretChanged(const TextCaretChangedStruct& arguments)=0; /// Called after the text is edited and after the caret is changed. /// The current edit version. virtual void TextEditFinished(vuint editVersion)=0; }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\EDITORCALLBACK\GUITEXTAUTOCOMPLETE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTAUTOCOMPLETE #define VCZH_PRESENTATION_CONTROLS_GUITEXTAUTOCOMPLETE namespace vl { namespace presentation { namespace controls { /*********************************************************************** GuiTextBoxAutoCompleteBase ***********************************************************************/ /// The base class of text box auto complete controller. class GuiTextBoxAutoCompleteBase : public Object, public virtual ICommonTextEditCallback { public: /// Represents an auto complete candidate item. struct AutoCompleteItem { /// Tag object for any purpose, e.g., data binding. description::Value tag; /// Display text for the item. WString text; }; /// Auto complete control provider. class IAutoCompleteControlProvider : public virtual Interface { public: /// Get the auto complete control that will be installed in a popup to show candidate items. /// The auto complete control. virtual GuiControl* GetAutoCompleteControl() = 0; /// Get the list control storing candidate items. /// The list control. It should be inside the auto complete control, or the auto complete control itself. virtual GuiSelectableListControl* GetListControl() = 0; /// Store candidate items in the list control. /// Candidate items. virtual void SetSortedContent(const collections::List& items) = 0; /// Get the numbers of all stored candidate items. /// The number of all stored candidate items. virtual vint GetItemCount() = 0; /// Get the text of a specified item. /// The index of the item. /// The text of the item. virtual WString GetItemText(vint index) = 0; }; class TextListControlProvider : public Object, public virtual IAutoCompleteControlProvider { protected: GuiTextList* autoCompleteList; public: TextListControlProvider(TemplateProperty controlTemplate = {}); ~TextListControlProvider(); GuiControl* GetAutoCompleteControl()override; GuiSelectableListControl* GetListControl()override; void SetSortedContent(const collections::List& items)override; vint GetItemCount()override; WString GetItemText(vint index)override; }; protected: elements::GuiColorizedTextElement* element; SpinLock* elementModifyLock; compositions::GuiGraphicsComposition* ownerComposition; GuiPopup* autoCompletePopup; Ptr autoCompleteControlProvider; TextPos autoCompleteStartPosition; bool IsPrefix(const WString& prefix, const WString& candidate); public: /// Create an auto complete. /// A auto complete control provider. Set to null to use a default one. GuiTextBoxAutoCompleteBase(Ptr _autoCompleteControlProvider = nullptr); ~GuiTextBoxAutoCompleteBase(); void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; /// Get the list state. /// Returns true if the list is visible. bool IsListOpening(); /// Notify the list to be visible. /// The text position to show the list. void OpenList(TextPos startPosition); /// Notify the list to be invisible. void CloseList(); /// Set the content of the list. /// The content of the list. void SetListContent(const collections::List& items); /// Get the last start position when the list is opened. /// The start position. TextPos GetListStartPosition(); /// Select the previous item. /// Returns true if this operation succeeded. bool SelectPreviousListItem(); /// Select the next item. /// Returns true if this operation succeeded. bool SelectNextListItem(); /// Apply the selected item into the text box. /// Returns true if this operation succeeded. bool ApplySelectedListItem(); /// Get the selected item. /// The text of the selected item. Returns empty if there is no selected item. WString GetSelectedListItem(); /// Highlight a candidate item in the list. /// The text to match an item. void HighlightList(const WString& editingText); }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\EDITORCALLBACK\GUITEXTCOLORIZER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTCOLORIZER #define VCZH_PRESENTATION_CONTROLS_GUITEXTCOLORIZER namespace vl { namespace presentation { namespace controls { /*********************************************************************** GuiTextBoxColorizerBase ***********************************************************************/ /// The base class of text box colorizer. class GuiTextBoxColorizerBase : public Object, public virtual ICommonTextEditCallback { public: typedef collections::Array ColorArray; protected: elements::GuiColorizedTextElement* element; SpinLock* elementModifyLock; volatile vint colorizedLineCount; volatile bool isColorizerRunning; volatile bool isFinalizing; SpinLock colorizerRunningEvent; static void ColorizerThreadProc(void* argument); void StartColorizer(); void StopColorizer(bool forever); void StopColorizerForever(); public: /// Create a colorrizer. GuiTextBoxColorizerBase(); ~GuiTextBoxColorizerBase(); void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; void RestartColorizer(); /// Get the lexical analyzer start state for the first line. /// The lexical analyzer start state for the first line. virtual vint GetLexerStartState()=0; /// Get the context sensitive start state for the first line. /// The context sensitive start state for the first line. virtual vint GetContextStartState()=0; /// Colorizer one line with a start state. /// Line index. /// Text buffer. /// Color index buffer. The index should be in [0 .. [M:vl.presentation.controls.GuiTextBoxColorizerBase.GetColors]()-1]. /// The length of the buffer. /// The lexical analyzer state for this line. After executing this function, the new value of this argument indicates the new state. /// The context sensitive state for this line. After executing this function, the new value of this argument indicates the new state. virtual void ColorizeLineWithCRLF(vint lineIndex, const wchar_t* text, vuint32_t* colors, vint length, vint& lexerState, vint& contextState)=0; /// Get the supported colors ordered by their indices. /// The supported colors ordered by their indices. virtual const ColorArray& GetColors()=0; }; /*********************************************************************** GuiTextBoxRegexColorizer ***********************************************************************/ /// Regex based colorizer. class GuiTextBoxRegexColorizer : public GuiTextBoxColorizerBase { protected: Ptr lexer; Ptr colorizer; void* colorizerArgument[1] { nullptr }; ColorArray colors; elements::text::ColorEntry defaultColor; collections::List tokenRegexes; collections::List tokenColors; collections::List extraTokenColors; static void ColorizerProc(void* argument, vint start, vint length, vint token); public: /// Create the colorizer. GuiTextBoxRegexColorizer(); ~GuiTextBoxRegexColorizer(); /// Get the default color. /// The default color. elements::text::ColorEntry GetDefaultColor(); /// Get all regular expressions for tokens. /// All regular expressions for tokens. collections::List& GetTokenRegexes(); /// Get all colors for tokens. /// All colors for tokens. collections::List& GetTokenColors(); /// Get all colors for extra tokens. /// All colors for extra tokens. collections::List& GetExtraTokenColors(); /// Get the first token index for the first extra token. /// The first token index for the first extra token. Returns -1 if this operation failed. vint GetExtraTokenIndexStart(); /// Set the default color. Call [M:vl.presentation.controls.GuiTextBoxRegexColorizer.Setup] after finishing all configuration. /// Returns the token index of this token. Returns -1 if this operation failed. /// The default color. bool SetDefaultColor(elements::text::ColorEntry value); /// Add a token type. Call [M:vl.presentation.controls.GuiTextBoxRegexColorizer.Setup] after finishing all configuration. /// Returns the token index of this token. Returns -1 if this operation failed. /// The regular expression for this token type. /// The color for this token type. vint AddToken(const WString& regex, elements::text::ColorEntry color); /// Add an extra token type. Call [M:vl.presentation.controls.GuiTextBoxRegexColorizer.Setup] after finishing all configuration. /// Returns the extra token index of this token. The token index for this token is regex-token-count + extra-token-index Returns -1 if this operation failed. /// The color for this token type. vint AddExtraToken(elements::text::ColorEntry color); /// Clear all token color settings. void ClearTokens(); /// Setup the colorizer. After that, the colorizer cannot be changed. void Setup(); /// Callback function to set context sensitive state and change token accordingly. /// Line index. /// Text buffer. /// The start position of the token. /// The length of the token. /// The token type. After executing this function, the new value of this argument indicates the new token type. /// The context sensitive state. After executing this function, the new value of this argument indicates the new state. virtual void ColorizeTokenContextSensitive(vint lineIndex, const wchar_t* text, vint start, vint length, vint& token, vint& contextState); vint GetLexerStartState()override; vint GetContextStartState()override; void ColorizeLineWithCRLF(vint lineIndex, const wchar_t* text, vuint32_t* colors, vint length, vint& lexerState, vint& contextState)override; const ColorArray& GetColors()override; }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\EDITORCALLBACK\GUITEXTUNDOREDO.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTUNDOREDO #define VCZH_PRESENTATION_CONTROLS_GUITEXTUNDOREDO namespace vl { namespace presentation { namespace controls { class GuiTextBoxCommonInterface; /*********************************************************************** Undo Redo ***********************************************************************/ class GuiGeneralUndoRedoProcessor : public Object { protected: class IEditStep : public Interface { public: virtual void Undo()=0; virtual void Redo()=0; }; friend class collections::ArrayBase>; protected: collections::List> steps; vint firstFutureStep; vint savedStep; bool performingUndoRedo; void PushStep(Ptr step); public: GuiGeneralUndoRedoProcessor(); ~GuiGeneralUndoRedoProcessor(); Event UndoRedoChanged; Event ModifiedChanged; bool CanUndo(); bool CanRedo(); void ClearUndoRedo(); bool GetModified(); void NotifyModificationSaved(); bool Undo(); bool Redo(); }; /*********************************************************************** Undo Redo (Text) ***********************************************************************/ class GuiTextBoxUndoRedoProcessor : public GuiGeneralUndoRedoProcessor, public ICommonTextEditCallback { protected: class EditStep : public Object, public IEditStep { public: GuiTextBoxUndoRedoProcessor* processor; TextEditNotifyStruct arguments; void Undo(); void Redo(); }; compositions::GuiGraphicsComposition* ownerComposition; public: GuiTextBoxUndoRedoProcessor(); ~GuiTextBoxUndoRedoProcessor(); void Attach(elements::GuiColorizedTextElement* element, SpinLock& elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; }; /*********************************************************************** Undo Redo (Document) ***********************************************************************/ class GuiDocumentUndoRedoProcessor : public GuiGeneralUndoRedoProcessor { public: struct ReplaceModelStruct { TextPos originalStart; TextPos originalEnd; Ptr originalModel; TextPos inputStart; TextPos inputEnd; Ptr inputModel; ReplaceModelStruct() { } }; struct RenameStyleStruct { WString oldStyleName; WString newStyleName; RenameStyleStruct() { } }; struct SetAlignmentStruct { vint start; vint end; collections::Array> originalAlignments; collections::Array> inputAlignments; }; protected: elements::GuiDocumentElement* element; compositions::GuiGraphicsComposition* ownerComposition; class ReplaceModelStep : public Object, public IEditStep { public: GuiDocumentUndoRedoProcessor* processor; ReplaceModelStruct arguments; void Undo(); void Redo(); }; class RenameStyleStep : public Object, public IEditStep { public: GuiDocumentUndoRedoProcessor* processor; RenameStyleStruct arguments; void Undo(); void Redo(); }; class SetAlignmentStep : public Object, public IEditStep { public: GuiDocumentUndoRedoProcessor* processor; Ptr arguments; void Undo(); void Redo(); }; public: GuiDocumentUndoRedoProcessor(); ~GuiDocumentUndoRedoProcessor(); void Setup(elements::GuiDocumentElement* _element, compositions::GuiGraphicsComposition* _ownerComposition); void OnReplaceModel(const ReplaceModelStruct& arguments); void OnRenameStyle(const RenameStyleStruct& arguments); void OnSetAlignment(Ptr arguments); }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\GUIDOCUMENTVIEWER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDOCUMENTVIEWER #define VCZH_PRESENTATION_CONTROLS_GUIDOCUMENTVIEWER namespace vl { namespace presentation { namespace compositions { class GuiShortcutKeyManager; } namespace controls { /*********************************************************************** GuiDocumentCommonInterface ***********************************************************************/ class GuiDocumentCommonInterface; /// Embedded object in a document. class GuiDocumentItem : public Object, public Description { friend class GuiDocumentCommonInterface; protected: bool visible = false; WString name; compositions::GuiBoundsComposition* container; bool owned = false; public: GuiDocumentItem(const WString& _name); ~GuiDocumentItem(); /// Get the container for all embedded controls and compositions in this item. /// The container. compositions::GuiGraphicsComposition* GetContainer(); /// Get the name of the document item. /// The name. WString GetName(); }; /// Document displayer control common interface for displaying . class GuiDocumentCommonInterface abstract : protected virtual elements::GuiDocumentElement::ICallback , public Description { typedef collections::Dictionary> DocumentItemMap; public: /// Represents the edit mode. enum EditMode { /// View the rich text only. ViewOnly, /// The rich text is selectable. Selectable, /// The rich text is editable. Editable, }; protected: Ptr baselineDocument; DocumentItemMap documentItems; GuiControl* documentControl = nullptr; elements::GuiDocumentElement* documentElement = nullptr; compositions::GuiBoundsComposition* documentComposition = nullptr; compositions::GuiGraphicsComposition* documentMouseArea = nullptr; Ptr onMouseMoveHandler; Ptr onMouseDownHandler; Ptr onMouseUpHandler; Ptr onMouseLeaveHandler; Ptr activeHyperlinks; bool dragging = false; EditMode editMode = EditMode::ViewOnly; Ptr undoRedoProcessor; Ptr internalShortcutKeyManager; protected: void InvokeUndoRedoChanged(); void InvokeModifiedChanged(); void UpdateCaretPoint(); void EnsureDocumentRectVisible(Rect bounds); void Move(TextPos caret, bool shift, bool frontSide); bool ProcessKey(VKEY code, bool shift, bool ctrl); void InstallDocumentViewer( GuiControl* _sender, compositions::GuiGraphicsComposition* _mouseArea, compositions::GuiGraphicsComposition* _container, compositions::GuiGraphicsComposition* eventComposition, compositions::GuiGraphicsComposition* focusableComposition ); void ReplaceMouseArea(compositions::GuiGraphicsComposition* _mouseArea); void SetActiveHyperlink(Ptr package); void ActivateActiveHyperlink(bool activate); void AddShortcutCommand(VKEY key, const Func& eventHandler); void EditTextInternal(TextPos begin, TextPos end, const Func& editor); void EditStyleInternal(TextPos begin, TextPos end, const Func& editor); void MergeBaselineAndDefaultFont(Ptr document); void OnFontChanged(); void OnCaretNotify(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnGotFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); void OnCharInput(compositions::GuiGraphicsComposition* sender, compositions::GuiCharEventArgs& arguments); void UpdateCursor(INativeCursor* cursor); Point GetMouseOffset(); void OnMouseMove(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); virtual Point GetDocumentViewPosition(); virtual void EnsureRectVisible(Rect bounds); //================ callback void OnStartRender()override; void OnFinishRender()override; Size OnRenderEmbeddedObject(const WString& name, const Rect& location)override; public: GuiDocumentCommonInterface(); ~GuiDocumentCommonInterface(); /// Active hyperlink changed event. compositions::GuiNotifyEvent ActiveHyperlinkChanged; /// Active hyperlink executed event. compositions::GuiNotifyEvent ActiveHyperlinkExecuted; /// Selection changed event. compositions::GuiNotifyEvent SelectionChanged; /// Undo redo status changed event. compositions::GuiNotifyEvent UndoRedoChanged; /// Modified status changed event. compositions::GuiNotifyEvent ModifiedChanged; /// Get the document. /// The document. Ptr GetDocument(); /// Set the document. When a document is set to this element, modifying the document without invoking will lead to undefined behavior. /// The document. void SetDocument(Ptr value); //================ document items /// Add a document item. The name of the document item will display in the position of the <object> element with the same name in the document. /// The document item. /// Returns true if this operation succeeded. bool AddDocumentItem(Ptr value); /// Remove a document item. /// The document item. /// Returns true if this operation succeeded. bool RemoveDocumentItem(Ptr value); /// Get all document items. /// All document items. const DocumentItemMap& GetDocumentItems(); //================ caret operations /// /// Get the begin position of the selection area. /// /// The begin position of the selection area. TextPos GetCaretBegin(); /// /// Get the end position of the selection area. /// /// The end position of the selection area. TextPos GetCaretEnd(); /// /// Set the end position of the selection area. /// /// The begin position of the selection area. /// The end position of the selection area. void SetCaret(TextPos begin, TextPos end); /// Calculate a caret using a specified point. /// The calculated caret. /// The specified point. TextPos CalculateCaretFromPoint(Point point); /// Get the bounds of a caret. /// The bounds. /// The caret. /// Set to true to get the bounds for the character before it. Rect GetCaretBounds(TextPos caret, bool frontSide); //================ editing operations /// Notify that some paragraphs are updated. /// The start paragraph index. /// The number of paragraphs to be updated. /// The number of updated paragraphs. /// Set to true to notify that the text is updated. void NotifyParagraphUpdated(vint index, vint oldCount, vint newCount, bool updatedText); /// Edit run in a specified range. /// The begin position of the range. /// The end position of the range. /// The new run. /// Set to true to copy the model before editing. Otherwise, objects inside the model will be used directly void EditRun(TextPos begin, TextPos end, Ptr model, bool copy); /// Edit text in a specified range. /// The begin position of the range. /// The end position of the range. /// Set to true to use the text style in front of the specified range. /// The new text. void EditText(TextPos begin, TextPos end, bool frontSide, const collections::Array& text); /// Edit style in a specified range. /// The begin position of the range. /// The end position of the range. /// The new style. void EditStyle(TextPos begin, TextPos end, Ptr style); /// Edit image in a specified range. /// The begin position of the range. /// The end position of the range. /// The new image. void EditImage(TextPos begin, TextPos end, Ptr image); /// Set hyperlink in a specified range. /// The index of the paragraph to edit. /// The begin position of the range. /// The end position of the range. /// The reference of the hyperlink. /// The normal style name of the hyperlink. /// The active style name of the hyperlink. void EditHyperlink(vint paragraphIndex, vint begin, vint end, const WString& reference, const WString& normalStyleName=DocumentModel::NormalLinkStyleName, const WString& activeStyleName=DocumentModel::ActiveLinkStyleName); /// Remove hyperlink in a specified range. /// The index of the paragraph to edit. /// The begin position of the range. /// The end position of the range. void RemoveHyperlink(vint paragraphIndex, vint begin, vint end); /// Edit style name in a specified range. /// The begin position of the range. /// The end position of the range. /// The new style name. void EditStyleName(TextPos begin, TextPos end, const WString& styleName); /// Remove style name in a specified range. /// The begin position of the range. /// The end position of the range. void RemoveStyleName(TextPos begin, TextPos end); /// Rename a style. /// The name of the style. /// The new name. void RenameStyle(const WString& oldStyleName, const WString& newStyleName); /// Clear all styles in a specified range. /// The begin position of the range. /// The end position of the range. void ClearStyle(TextPos begin, TextPos end); /// Summarize the text style in a specified range. /// The text style summary. /// The begin position of the range. /// The end position of the range. Ptr SummarizeStyle(TextPos begin, TextPos end); /// Summarize the style name in a specified range. /// The style name summary. /// The begin position of the range. /// The end position of the range. Nullable SummarizeStyleName(TextPos begin, TextPos end); /// Set the alignment of paragraphs in a specified range. /// The begin position of the range. /// The end position of the range. /// The alignment for each paragraph. void SetParagraphAlignments(TextPos begin, TextPos end, const collections::Array>& alignments); /// Set the alignment of paragraphs in a specified range. /// The begin position of the range. /// The end position of the range. /// The alignment for each paragraph. void SetParagraphAlignment(TextPos begin, TextPos end, Nullable alignment); /// Summarize the text alignment in a specified range. /// The text alignment summary. /// The begin position of the range. /// The end position of the range. Nullable SummarizeParagraphAlignment(TextPos begin, TextPos end); //================ editing control /// Get the href attribute of the active hyperlink. /// The href attribute of the active hyperlink. WString GetActiveHyperlinkReference(); /// Get the edit mode of this control. /// The edit mode. EditMode GetEditMode(); /// Set the edit mode of this control. /// The edit mode. void SetEditMode(EditMode value); //================ selection operations /// Select all text. void SelectAll(); /// Get the selected text. /// The selected text. WString GetSelectionText(); /// Set the selected text. /// The selected text. void SetSelectionText(const WString& value); /// Get the selected model. /// The selected model. Ptr GetSelectionModel(); /// Set the selected model. /// The selected model. void SetSelectionModel(Ptr value); //================ clipboard operations /// Test can the selection be cut. /// Returns true if the selection can be cut. bool CanCut(); /// Test can the selection be copied. /// Returns true if the selection can be cut. bool CanCopy(); /// Test can the content in the clipboard be pasted. /// Returns true if the content in the clipboard can be pasted. bool CanPaste(); /// Cut the selection text. /// Returns true if this operation succeeded. bool Cut(); /// Copy the selection text. /// Returns true if this operation succeeded. bool Copy(); /// Paste the content from the clipboard and replace the selected text. /// Returns true if this operation succeeded. bool Paste(); //================ undo redo control /// Test can undo. /// Returns true if this action can be performed. bool CanUndo(); /// Test can redo. /// Returns true if this action can be performed. bool CanRedo(); /// Clear all undo and redo information. void ClearUndoRedo(); /// Test is the text box modified. /// Returns true if the text box is modified. bool GetModified(); /// Notify the text box that the current status is considered saved. void NotifyModificationSaved(); /// Perform the undo action. /// Returns true if this operation succeeded. bool Undo(); /// Perform the redo action. /// Returns true if this operation succeeded. bool Redo(); }; /*********************************************************************** GuiDocumentViewer ***********************************************************************/ /// Scrollable document viewer for displaying . class GuiDocumentViewer : public GuiScrollContainer, public GuiDocumentCommonInterface, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(DocumentViewerTemplate, GuiScrollContainer) protected: void UpdateDisplayFont()override; Point GetDocumentViewPosition()override; void EnsureRectVisible(Rect bounds)override; public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. GuiDocumentViewer(theme::ThemeName themeName); ~GuiDocumentViewer(); const WString& GetText()override; void SetText(const WString& value)override; }; /*********************************************************************** GuiDocumentViewer ***********************************************************************/ /// Static document viewer for displaying . class GuiDocumentLabel : public GuiControl, public GuiDocumentCommonInterface, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(DocumentLabelTemplate, GuiControl) protected: void UpdateDisplayFont()override; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiDocumentLabel(theme::ThemeName themeName); ~GuiDocumentLabel(); const WString& GetText()override; void SetText(const WString& value)override; }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\GUITEXTCOMMONINTERFACE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTCOMMONINTERFACE #define VCZH_PRESENTATION_CONTROLS_GUITEXTCOMMONINTERFACE namespace vl { namespace presentation { namespace compositions { class GuiShortcutKeyManager; } namespace controls { /*********************************************************************** Common Interface ***********************************************************************/ /// Common interface for text box controls. class GuiTextBoxCommonInterface abstract : public Description { typedef collections::Array ColorArray; protected: class ICallback : public virtual IDescriptable, public Description { public: virtual TextPos GetLeftWord(TextPos pos)=0; virtual TextPos GetRightWord(TextPos pos)=0; virtual void GetWord(TextPos pos, TextPos& begin, TextPos& end)=0; virtual vint GetPageRows()=0; virtual bool BeforeModify(TextPos start, TextPos end, const WString& originalText, WString& inputText)=0; virtual void AfterModify(TextPos originalStart, TextPos originalEnd, const WString& originalText, TextPos inputStart, TextPos inputEnd, const WString& inputText)=0; virtual void ScrollToView(Point point)=0; virtual vint GetTextMargin()=0; }; class DefaultCallback : public Object, public ICallback, public Description { protected: elements::GuiColorizedTextElement* textElement; compositions::GuiGraphicsComposition* textComposition; bool readonly; public: DefaultCallback(elements::GuiColorizedTextElement* _textElement, compositions::GuiGraphicsComposition* _textComposition); ~DefaultCallback(); TextPos GetLeftWord(TextPos pos)override; TextPos GetRightWord(TextPos pos)override; void GetWord(TextPos pos, TextPos& begin, TextPos& end)override; vint GetPageRows()override; bool BeforeModify(TextPos start, TextPos end, const WString& originalText, WString& inputText)override; }; private: elements::GuiColorizedTextElement* textElement; compositions::GuiGraphicsComposition* textComposition; vuint editVersion; GuiControl* textControl; ICallback* callback; bool dragging; bool readonly; Ptr colorizer; Ptr autoComplete; Ptr undoRedoProcessor; bool filledDefaultColors = false; ColorArray defaultColors; SpinLock elementModifyLock; collections::List> textEditCallbacks; Ptr internalShortcutKeyManager; bool preventEnterDueToAutoComplete; void InvokeUndoRedoChanged(); void InvokeModifiedChanged(); void UpdateCaretPoint(); void Move(TextPos pos, bool shift); void Modify(TextPos start, TextPos end, const WString& input, bool asKeyInput); bool ProcessKey(VKEY code, bool shift, bool ctrl); void OnGotFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnCaretNotify(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnMouseMove(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); void OnCharInput(compositions::GuiGraphicsComposition* sender, compositions::GuiCharEventArgs& arguments); protected: void Install(elements::GuiColorizedTextElement* _textElement, compositions::GuiGraphicsComposition* _textComposition, GuiControl* _textControl, compositions::GuiGraphicsComposition* eventComposition, compositions::GuiGraphicsComposition* focusableComposition); ICallback* GetCallback(); void SetCallback(ICallback* value); bool AttachTextEditCallback(Ptr value); bool DetachTextEditCallback(Ptr value); void AddShortcutCommand(VKEY key, const Func& eventHandler); elements::GuiColorizedTextElement* GetTextElement(); void UnsafeSetText(const WString& value); public: GuiTextBoxCommonInterface(); ~GuiTextBoxCommonInterface(); /// Selection changed event. compositions::GuiNotifyEvent SelectionChanged; /// Undo redo status changed event. compositions::GuiNotifyEvent UndoRedoChanged; /// Modified status changed event. compositions::GuiNotifyEvent ModifiedChanged; //================ clipboard operations /// Test can the selection be cut. /// Returns true if the selection can be cut. bool CanCut(); /// Test can the selection be copied. /// Returns true if the selection can be cut. bool CanCopy(); /// Test can the content in the clipboard be pasted. /// Returns true if the content in the clipboard can be pasted. bool CanPaste(); /// Cut the selection text. /// Returns true if this operation succeeded. bool Cut(); /// Copy the selection text. /// Returns true if this operation succeeded. bool Copy(); /// Paste the content from the clipboard and replace the selected text. /// Returns true if this operation succeeded. bool Paste(); //================ editing control /// Get the readonly mode. /// Returns true if the text box is readonly. bool GetReadonly(); /// Set the readonly mode. /// Set to true to make the texg box readonly. void SetReadonly(bool value); //================ text operations /// Select all text. void SelectAll(); /// Select (highlight) a part of text. /// The begin position. /// The end position. This is also the caret position. void Select(TextPos begin, TextPos end); /// Get the selected text. /// The selected text. WString GetSelectionText(); /// Set the selected text. /// The selected text. void SetSelectionText(const WString& value); /// Set the selected text and let to text box treat this changing as input by the keyboard. /// The selected text. void SetSelectionTextAsKeyInput(const WString& value); /// Get the text from a specified row number. /// The text from a specified row number. /// The specified row number. WString GetRowText(vint row); /// Get the number of rows. /// The number of rows. vint GetRowCount(); /// Get the text from a specified range. /// The text from a specified range. /// The specified start position. /// The specified end position. WString GetFragmentText(TextPos start, TextPos end); /// Get the begin text position of the selection. /// The begin text position of the selection. TextPos GetCaretBegin(); /// Get the end text position of the selection. /// The end text position of the selection. TextPos GetCaretEnd(); /// Get the left-top text position of the selection. /// The left-top text position of the selection. TextPos GetCaretSmall(); /// Get the right-bottom text position of the selection. /// The right-bottom text position of the selection. TextPos GetCaretLarge(); //================ position query /// Get the width of a row. /// The width of a row in pixel. /// The specified row number vint GetRowWidth(vint row); /// Get the height of a row. /// The height of a row in pixel. vint GetRowHeight(); /// Get the maximum width of all rows. /// The maximum width of all rows. vint GetMaxWidth(); /// Get the total height of all rows. /// The total height of all rows. vint GetMaxHeight(); /// Get the nearest position of a character from a specified display position. /// Get the nearest position of a character. /// The specified display position. TextPos GetTextPosFromPoint(Point point); /// Get the display position of a character from a specified text position. /// Get the display position of a character. /// The specified text position. Point GetPointFromTextPos(TextPos pos); /// Get the display bounds of a character from a specified text position. /// Get the display bounds of a character. /// The specified text position. Rect GetRectFromTextPos(TextPos pos); /// Get the nearest text position from a specified display position. /// Get the nearest text position. /// The specified display position. TextPos GetNearestTextPos(Point point); //================ colorizing /// Get the current colorizer. /// The current colorizer. Ptr GetColorizer(); /// Set the current colorizer. /// The current colorizer. void SetColorizer(Ptr value); //================ auto complete /// Get the current auto complete controller. /// The current auto complete controller. Ptr GetAutoComplete(); /// Set the current auto complete controller. /// The current auto complete controller. void SetAutoComplete(Ptr value); //================ undo redo control /// Get the current edit version. When the control is modified, the edit version increased. Calling will not reset the edit version. /// The current edit version. vuint GetEditVersion(); /// Test can undo. /// Returns true if this action can be performed. bool CanUndo(); /// Test can redo. /// Returns true if this action can be performed. bool CanRedo(); /// Clear all undo and redo information. void ClearUndoRedo(); /// Test is the text box modified. /// Returns true if the text box is modified. bool GetModified(); /// Notify the text box that the current status is considered saved. void NotifyModificationSaved(); /// Perform the undo action. /// Returns true if this operation succeeded. bool Undo(); /// Perform the redo action. /// Returns true if this operation succeeded. bool Redo(); }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\GUITEXTCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITEXTCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUITEXTCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** MultilineTextBox ***********************************************************************/ /// Multiline text box control. class GuiMultilineTextBox : public GuiScrollView, public GuiTextBoxCommonInterface, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(MultilineTextBoxTemplate, GuiScrollView) public: static const vint TextMargin=3; class CommandExecutor : public Object, public ITextBoxCommandExecutor { protected: GuiMultilineTextBox* textBox; public: CommandExecutor(GuiMultilineTextBox* _textBox); ~CommandExecutor(); void UnsafeSetText(const WString& value)override; }; protected: class TextElementOperatorCallback : public GuiTextBoxCommonInterface::DefaultCallback, public Description { protected: GuiMultilineTextBox* textControl; public: TextElementOperatorCallback(GuiMultilineTextBox* _textControl); void AfterModify(TextPos originalStart, TextPos originalEnd, const WString& originalText, TextPos inputStart, TextPos inputEnd, const WString& inputText)override; void ScrollToView(Point point)override; vint GetTextMargin()override; }; protected: Ptr callback; Ptr commandExecutor; elements::GuiColorizedTextElement* textElement = nullptr; compositions::GuiBoundsComposition* textComposition = nullptr; void UpdateVisuallyEnabled()override; void UpdateDisplayFont()override; void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)override; Size QueryFullSize()override; void UpdateView(Rect viewBounds)override; void CalculateViewAndSetScroll(); void OnBoundsMouseButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. GuiMultilineTextBox(theme::ThemeName themeName); ~GuiMultilineTextBox(); const WString& GetText()override; void SetText(const WString& value)override; }; /*********************************************************************** SinglelineTextBox ***********************************************************************/ /// Single text box control. class GuiSinglelineTextBox : public GuiControl, public GuiTextBoxCommonInterface, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(SinglelineTextBoxTemplate, GuiControl) public: static const vint TextMargin=2; protected: class TextElementOperatorCallback : public GuiTextBoxCommonInterface::DefaultCallback, public Description { public: TextElementOperatorCallback(GuiSinglelineTextBox* _textControl); bool BeforeModify(TextPos start, TextPos end, const WString& originalText, WString& inputText)override; void AfterModify(TextPos originalStart, TextPos originalEnd, const WString& originalText, TextPos inputStart, TextPos inputEnd, const WString& inputText)override; void ScrollToView(Point point)override; vint GetTextMargin()override; }; protected: Ptr callback; elements::GuiColorizedTextElement* textElement = nullptr; compositions::GuiTableComposition* textCompositionTable = nullptr; compositions::GuiCellComposition* textComposition = nullptr; void UpdateVisuallyEnabled()override; void UpdateDisplayFont()override; void RearrangeTextElement(); void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)override; void OnBoundsMouseButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. GuiSinglelineTextBox(theme::ThemeName themeName); ~GuiSinglelineTextBox(); const WString& GetText()override; void SetText(const WString& value)override; /// /// Get the password mode displaying character. /// /// The password mode displaying character. Returns L'\0' means the password mode is not activated. wchar_t GetPasswordChar(); /// /// Set the password mode displaying character. /// /// The password mode displaying character. Set to L'\0' to deactivate the password mode. void SetPasswordChar(wchar_t value); }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\LANGUAGESERVICE\GUILANGUAGEOPERATIONS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILANGUAGEOPERATIONS #define VCZH_PRESENTATION_CONTROLS_GUILANGUAGEOPERATIONS namespace vl { namespace presentation { namespace controls { /*********************************************************************** ParsingInput ***********************************************************************/ class RepeatingParsingExecutor; /// A data structure storing the parsing input for text box control. struct RepeatingParsingInput { /// The text box edit version of the code. vuint editVersion = 0; /// The code. WString code; }; /*********************************************************************** ParsingOutput ***********************************************************************/ /// A data structure storing the parsing result for text box control. struct RepeatingParsingOutput { /// The parsed syntax tree. Ptr node; /// The text box edit version of the code. vuint editVersion = 0; /// The code. WString code; /// The cache created from [T:vl.presentation.controls.RepeatingParsingExecutor.IParsingAnalyzer]. Ptr cache; }; /*********************************************************************** PartialParsingOutput ***********************************************************************/ /// A data structure storing the parsing result for partial updating when a text box control is modified. struct RepeatingPartialParsingOutput { /// The input data. RepeatingParsingOutput input; /// The rule name that can parse the code of the selected context. WString rule; /// Range of the original context in the input. parsing::ParsingTextRange originalRange; /// The original context in the syntax tree. Ptr originalNode; /// The modified context in the syntax tree. Ptr modifiedNode; /// The modified code of the selected context. WString modifiedCode; }; /*********************************************************************** PartialParsingOutput ***********************************************************************/ /// A data structure storing the information for a candidate item. struct ParsingCandidateItem { /// Semantic id. vint semanticId = -1; /// Display name. WString name; /// Tag object for any purpose, e.g., data binding. description::Value tag; }; /*********************************************************************** ParsingContext ***********************************************************************/ /// A data structure storing the context of a token. struct ParsingTokenContext { /// Token syntax tree for the selected token. parsing::ParsingTreeToken* foundToken = nullptr; /// The object syntax tree parent of the token. parsing::ParsingTreeObject* tokenParent = nullptr; /// Type of the parent. WString type; /// Field of the parent that contains the token. WString field; /// All acceptable semantic ids. Ptr> acceptableSemanticIds; static bool RetriveContext(ParsingTokenContext& output, parsing::ParsingTreeNode* foundNode, RepeatingParsingExecutor* executor); static bool RetriveContext(ParsingTokenContext& output, parsing::ParsingTextPos pos, parsing::ParsingTreeObject* rootNode, RepeatingParsingExecutor* executor); static bool RetriveContext(ParsingTokenContext& output, parsing::ParsingTextRange range, parsing::ParsingTreeObject* rootNode, RepeatingParsingExecutor* executor); }; /*********************************************************************** RepeatingParsingExecutor ***********************************************************************/ /// Repeating parsing executor. class RepeatingParsingExecutor : public RepeatingTaskExecutor, public Description { public: /// Callback. class ICallback : public virtual Interface { public: /// Callback when a parsing task is finished. /// the result of the parsing. virtual void OnParsingFinishedAsync(const RepeatingParsingOutput& output)=0; /// Callback when requires enabling or disabling automatically repeating calling to the SubmitTask function. /// Set to true to require an automatically repeating calling to the SubmitTask function virtual void RequireAutoSubmitTask(bool enabled)=0; }; /// Parsing analyzer. class IParsingAnalyzer : public virtual Interface { private: parsing::ParsingTreeNode* ToParent(parsing::ParsingTreeNode* node, const RepeatingPartialParsingOutput* output); parsing::ParsingTreeObject* ToChild(parsing::ParsingTreeObject* node, const RepeatingPartialParsingOutput* output); Ptr ToChild(Ptr node, const RepeatingPartialParsingOutput* output); protected: /// Get a syntax tree node's parent when the whole tree is in a partial modified state. You should use this function instead of ParsingTreeNode::GetParent when implementing this interface. /// Returns the parent node. /// The node. /// The partial parsing output, which describes how the whole tree is partial modified. parsing::ParsingTreeNode* GetParent(parsing::ParsingTreeNode* node, const RepeatingPartialParsingOutput* output); /// Get a syntax tree node's member when the whole tree is in a partial modified state. You should use this function instead of ParsingTreeObject::GetMember when implementing this interface. /// Returns the member node. /// The node. /// The name of the member. /// The partial parsing output, which describes how the whole tree is partial modified. Ptr GetMember(parsing::ParsingTreeObject* node, const WString& name, const RepeatingPartialParsingOutput* output); /// Get a syntax tree node's item when the whole tree is in a partial modified state. You should use this function instead of ParsingTreeArray::GetItem when implementing this interface. /// Returns the item node. /// The node. /// The index of the item. /// The partial parsing output, which describes how the whole tree is partial modified. Ptr GetItem(parsing::ParsingTreeArray* node, vint index, const RepeatingPartialParsingOutput* output); public: /// Called when a is created. /// The releated . virtual void Attach(RepeatingParsingExecutor* executor) = 0; /// Called when a is destroyed. /// The releated . virtual void Detach(RepeatingParsingExecutor* executor) = 0; /// Called when a new parsing result is produced. A parsing analyzer can create a cache to be attached to the output containing anything necessary. This function does not run in UI thread. /// The new parsing result. /// The created cache object, which can be null. virtual Ptr CreateCacheAsync(const RepeatingParsingOutput& output) = 0; /// Called when an semantic id for a token is needed. If an semantic id is returned, a context sensitive color can be assigned to this token. This functio does not run in UI thread, but it will only be called (for several times) after the cache object is initialized. /// The token context. /// The current parsing result. /// The semantic id. virtual vint GetSemanticIdForTokenAsync(const ParsingTokenContext& tokenContext, const RepeatingParsingOutput& output) = 0; /// Called when multiple auto complete candidate items for a token is needed. If nothing is written into the "candidateItems" parameter and the grammar also doesn't provide static candidate items, nothing will popup. This functio does not run in UI thread, but it will only be called (for several times) after the cache object is initialized. /// The token context. /// The partial parsing result. It contains the current parsing result, and an incremental parsing result. If the calculation of candidate items are is very context sensitive, then you should be very careful when traversing the syntax tree, by carefully looking at the "originalNode" and the "modifiedNode" in the "partialOutput" parameter. /// The candidate items. virtual void GetCandidateItemsAsync(const ParsingTokenContext& tokenContext, const RepeatingPartialParsingOutput& partialOutput, collections::List& candidateItems) = 0; /// Create a tag object for a candidate item without a tag object. An candidate item without a tag maybe created by calling or any token marked by a @Candidate attribute in the grammar. /// The candidate item. /// The tag object. In most of the case this object is used for data binding or any other purpose when you want to customize the auto complete control. Returns null if the specified [T.vl.presentation.controls.GuiTextBoxAutoCompleteBase.IAutoCompleteControlProvider] can handle null tag correctly. virtual description::Value CreateTagForCandidateItem(ParsingCandidateItem& item) = 0; }; /// A base class for implementing a callback. class CallbackBase : public virtual ICallback, public virtual ICommonTextEditCallback { private: bool callbackAutoPushing; elements::GuiColorizedTextElement* callbackElement; SpinLock* callbackElementModifyLock; protected: Ptr parsingExecutor; public: CallbackBase(Ptr _parsingExecutor); ~CallbackBase(); void RequireAutoSubmitTask(bool enabled)override; void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; }; struct TokenMetaData { vint tableTokenIndex; vint lexerTokenIndex; vint defaultColorIndex; bool hasContextColor; bool hasAutoComplete; bool isCandidate; WString unescapedRegexText; }; struct FieldMetaData { vint colorIndex; Ptr> semantics; }; private: Ptr grammarParser; WString grammarRule; Ptr analyzer; collections::List callbacks; collections::List activatedCallbacks; ICallback* autoPushingCallback; typedef collections::Pair FieldDesc; collections::Dictionary tokenIndexMap; collections::SortedList semanticIndexMap; collections::Dictionary tokenMetaDatas; collections::Dictionary fieldMetaDatas; protected: void Execute(const RepeatingParsingInput& input)override; void PrepareMetaData(); /// Called when semantic analyzing is needed. It is encouraged to set the "cache" fields in "context" argument. If there is an binded to the , this function can be automatically done. /// The parsing result. virtual void OnContextFinishedAsync(RepeatingParsingOutput& context); public: /// Initialize the parsing executor. /// Parser generated from a grammar. /// The rule name to parse a complete code. /// The parsing analyzer to create semantic metadatas, it can be null. RepeatingParsingExecutor(Ptr _grammarParser, const WString& _grammarRule, Ptr _analyzer = 0); ~RepeatingParsingExecutor(); /// Get the internal parser that parse the text. /// The internal parser. Ptr GetParser(); /// Detach callback. /// Returns true if this operation succeeded. /// The callback. bool AttachCallback(ICallback* value); /// Detach callback. /// Returns true if this operation succeeded. /// The callback. bool DetachCallback(ICallback* value); /// Activate a callback. Activating a callback means that the callback owner has an ability to watch a text box modification, e.g., an attached that is also an . The may require one of the activated callback to push code for parsing automatically via a call to . /// Returns true if this operation succeeded. /// The callback. bool ActivateCallback(ICallback* value); /// Deactivate a callback. See for deatils. /// Returns true if this operation succeeded. /// The callback. bool DeactivateCallback(ICallback* value); /// Get the parsing analyzer. /// The parsing analyzer. Ptr GetAnalyzer(); vint GetTokenIndex(const WString& tokenName); vint GetSemanticId(const WString& name); WString GetSemanticName(vint id); const TokenMetaData& GetTokenMetaData(vint regexTokenIndex); const FieldMetaData& GetFieldMetaData(const WString& type, const WString& field); Ptr GetAttribute(vint index, const WString& name, vint argumentCount); Ptr GetColorAttribute(vint index); Ptr GetContextColorAttribute(vint index); Ptr GetSemanticAttribute(vint index); Ptr GetCandidateAttribute(vint index); Ptr GetAutoCompleteAttribute(vint index); /* @Color(ColorName) field: color of the token field when the token type is marked with @ContextColor token: color of the token @ContextColor() token: the color of the token may be changed if the token field is marked with @Color or @Semantic @Semantic(Type1, Type2, ...) field: After resolved symbols for this field, only types of symbols that specified in the arguments are acceptable. @Candidate() token: when the token can be available after the editing caret, than it will be in the auto complete list. @AutoComplete() token: when the token is editing, an auto complete list will appear if possible */ }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\LANGUAGESERVICE\GUILANGUAGEAUTOCOMPLETE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILANGUAGEAUTOCOMPLETE #define VCZH_PRESENTATION_CONTROLS_GUILANGUAGEAUTOCOMPLETE namespace vl { namespace presentation { namespace controls { /*********************************************************************** GuiGrammarAutoComplete ***********************************************************************/ /// Grammar based auto complete controller. class GuiGrammarAutoComplete : public GuiTextBoxAutoCompleteBase , protected RepeatingParsingExecutor::CallbackBase , private RepeatingTaskExecutor { public: /// The auto complete list data. struct AutoCompleteData : ParsingTokenContext { /// Available candidate tokens (in lexer token index). collections::List candidates; /// Available candidate tokens (in lexer token index) that marked with @AutoCompleteCandidate(). collections::List shownCandidates; /// Candidate items. collections::List candidateItems; /// The start position of the editing token in global coordination. TextPos startPosition; }; /// The analysed data from an input code. struct AutoCompleteContext : RepeatingPartialParsingOutput { /// The edit version of modified code. vuint modifiedEditVersion = 0; /// The analysed auto complete list data. Ptr autoComplete; }; private: Ptr grammarParser; collections::SortedList leftRecursiveRules; bool editing; SpinLock editTraceLock; collections::List editTrace; SpinLock contextLock; AutoCompleteContext context; void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; void OnParsingFinishedAsync(const RepeatingParsingOutput& output)override; void CollectLeftRecursiveRules(); vint UnsafeGetEditTraceIndex(vuint editVersion); TextPos ChooseCorrectTextPos(TextPos pos, const regex::RegexTokens& tokens); void ExecuteRefresh(AutoCompleteContext& newContext); bool NormalizeTextPos(AutoCompleteContext& newContext, elements::text::TextLines& lines, TextPos& pos); void ExecuteEdit(AutoCompleteContext& newContext); void DeleteFutures(collections::List& futures); regex::RegexToken* TraverseTransitions( parsing::tabling::ParsingState& state, parsing::tabling::ParsingTransitionCollector& transitionCollector, TextPos stopPosition, collections::List& nonRecoveryFutures, collections::List& recoveryFutures ); regex::RegexToken* SearchValidInputToken( parsing::tabling::ParsingState& state, parsing::tabling::ParsingTransitionCollector& transitionCollector, TextPos stopPosition, AutoCompleteContext& newContext, collections::SortedList& tableTokenIndices ); TextPos GlobalTextPosToModifiedTextPos(AutoCompleteContext& newContext, TextPos pos); TextPos ModifiedTextPosToGlobalTextPos(AutoCompleteContext& newContext, TextPos pos); void ExecuteCalculateList(AutoCompleteContext& newContext); void Execute(const RepeatingParsingOutput& input)override; void PostList(const AutoCompleteContext& newContext, bool byGlobalCorrection); void Initialize(); protected: /// Called when the context of the code is selected. It is encouraged to set the "candidateItems" field in "context.autoComplete" during the call. If there is an binded to the , this function can be automatically done. /// The selected context. virtual void OnContextFinishedAsync(AutoCompleteContext& context); /// Call this function in the derived class's destructor when it overrided . void EnsureAutoCompleteFinished(); public: /// Create the auto complete controller with a created parsing executor. /// The parsing executor. GuiGrammarAutoComplete(Ptr _parsingExecutor); /// Create the auto complete controller with a specified grammar and start rule to create a . /// Parser generated from a grammar. /// GuiGrammarAutoComplete(Ptr _grammarParser, const WString& _grammarRule); ~GuiGrammarAutoComplete(); /// Get the internal parsing executor. /// The parsing executor. Ptr GetParsingExecutor(); }; } } } #endif /*********************************************************************** .\CONTROLS\TEXTEDITORPACKAGE\LANGUAGESERVICE\GUILANGUAGECOLORIZER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILANGUAGECOLORIZER #define VCZH_PRESENTATION_CONTROLS_GUILANGUAGECOLORIZER namespace vl { namespace presentation { namespace controls { /*********************************************************************** GuiGrammarColorizer ***********************************************************************/ /// Grammar based colorizer. class GuiGrammarColorizer : public GuiTextBoxRegexColorizer, protected RepeatingParsingExecutor::CallbackBase { typedef collections::Pair FieldDesc; typedef collections::Dictionary FieldContextColors; typedef collections::Dictionary FieldSemanticColors; typedef elements::text::ColorEntry ColorEntry; public: /// Context for doing semantic colorizing. struct SemanticColorizeContext : ParsingTokenContext { /// Output semantic id that comes from one the argument in the @Semantic attribute. vint semanticId; }; private: collections::Dictionary colorSettings; collections::Dictionary semanticColorMap; SpinLock contextLock; RepeatingParsingOutput context; void OnParsingFinishedAsync(const RepeatingParsingOutput& output)override; protected: /// Called when the node is parsed successfully before restarting colorizing. /// The result of the parsing. virtual void OnContextFinishedAsync(const RepeatingParsingOutput& context); void Attach(elements::GuiColorizedTextElement* _element, SpinLock& _elementModifyLock, compositions::GuiGraphicsComposition* _ownerComposition, vuint editVersion)override; void Detach()override; void TextEditPreview(TextEditPreviewStruct& arguments)override; void TextEditNotify(const TextEditNotifyStruct& arguments)override; void TextCaretChanged(const TextCaretChangedStruct& arguments)override; void TextEditFinished(vuint editVersion)override; /// Called when a @SemanticColor attribute in a grammar is activated during colorizing to determine a color for the token. If there is an binded to the , this function can be automatically done. /// Context for doing semantic colorizing. /// The corressponding result from the . virtual void OnSemanticColorize(SemanticColorizeContext& context, const RepeatingParsingOutput& input); /// Call this function in the derived class's destructor when it overrided . void EnsureColorizerFinished(); public: /// Create the colorizer with a created parsing executor. /// The parsing executor. GuiGrammarColorizer(Ptr _parsingExecutor); /// Create the colorizer with a specified grammar and start rule to create a . /// Parser generated from a grammar. /// GuiGrammarColorizer(Ptr _grammarParser, const WString& _grammarRule); ~GuiGrammarColorizer(); /// Reset all color settings. void BeginSetColors(); /// Get all color names. /// All color names. const collections::SortedList& GetColorNames(); /// Get the color for a token theme name (@Color or @ContextColor("theme-name") in the grammar). /// The color. /// The token theme name. ColorEntry GetColor(const WString& name); /// Set a color for a token theme name (@Color or @ContextColor("theme-name") in the grammar). /// The token theme name. /// The color. void SetColor(const WString& name, const ColorEntry& entry); /// Set a color for a token theme name (@Color or @ContextColor("theme-name") in the grammar). /// The token theme name. /// The color. void SetColor(const WString& name, const Color& color); /// Submit all color settings. void EndSetColors(); void ColorizeTokenContextSensitive(vint lineIndex, const wchar_t* text, vint start, vint length, vint& token, vint& contextState)override; /// Get the internal parsing executor. /// The parsing executor. Ptr GetParsingExecutor(); }; } } } #endif /*********************************************************************** .\CONTROLS\TOOLSTRIPPACKAGE\GUIMENUCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIMENUCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIMENUCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Menu Service ***********************************************************************/ class GuiMenu; /// IGuiMenuService is a required service for menu item container. class IGuiMenuService : public virtual IDescriptable, public Description { public: /// The identifier for this service. static const wchar_t* const Identifier; /// Direction to decide the position for a menu with specified control. enum Direction { /// Aligned to the top or bottom side. Horizontal, /// Aligned to the left or right side. Vertical, }; protected: GuiMenu* openingMenu; public: IGuiMenuService(); /// Get the parent service. This service represents the parent menu that host the menu item control that contains this menu. /// The parent service. virtual IGuiMenuService* GetParentMenuService()=0; /// Get the preferred direction to open the sub menu. /// The preferred direction to open the sub menu. virtual Direction GetPreferredDirection()=0; /// Test is this menu is active. When an menu is active, the sub menu is automatically opened when the corresponding menu item is opened. /// Returns true if this menu is active. virtual bool IsActiveState()=0; /// Test all sub menu items are actived by mouse down. /// Returns true if all sub menu items are actived by mouse down. virtual bool IsSubMenuActivatedByMouseDown()=0; /// Called when the menu item is executed. virtual void MenuItemExecuted(); /// Get the opening sub menu. /// The opening sub menu. virtual GuiMenu* GetOpeningMenu(); /// Called when the sub menu is opened. /// The sub menu. virtual void MenuOpened(GuiMenu* menu); /// Called when the sub menu is closed. /// The sub menu. virtual void MenuClosed(GuiMenu* menu); }; /// IGuiMenuService is a required service to tell a ribbon group that this control has a dropdown to display. class IGuiMenuDropdownProvider : public virtual IDescriptable, public Description { public: /// The identifier for this service. static const wchar_t* const Identifier; /// Get the dropdown to display. /// The dropdown to display. Returns null to indicate the dropdown cannot be displaied temporary. virtual GuiMenu* ProvideDropdownMenu() = 0; }; /*********************************************************************** Menu ***********************************************************************/ /// Popup menu. class GuiMenu : public GuiPopup, protected IGuiMenuService, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(MenuTemplate, GuiPopup) private: IGuiMenuService* parentMenuService = nullptr; bool hideOnDeactivateAltHost = true; Size preferredMenuClientSizeBeforeUpdating; Size preferredMenuClientSize; IGuiMenuService* GetParentMenuService()override; Direction GetPreferredDirection()override; bool IsActiveState()override; bool IsSubMenuActivatedByMouseDown()override; void MenuItemExecuted()override; void Moving(NativeRect& bounds, bool fixSizeOnly, bool draggingBorder)override; void UpdateClientSizeAfterRendering(Size preferredSize, Size clientSize)override; protected: GuiControl* owner; void OnDeactivatedAltHost()override; void OnWindowOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnWindowClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. /// The owner menu item of the parent menu. GuiMenu(theme::ThemeName themeName, GuiControl* _owner); ~GuiMenu(); /// Update the reference to the parent . This function is not required to call outside the menu or menu item control. void UpdateMenuService(); IDescriptable* QueryService(const WString& identifier)override; /// Test if this menu hide after pressing ESC key to exit to the upper level of ALT shortcuts. /// Returns true if this menu hide after pressing ESC key to exit to the upper level of ALT shortcuts. bool GetHideOnDeactivateAltHost(); /// Set if this menu hide after pressing ESC key to exit to the upper level of ALT shortcuts. /// Set to true to make this menu hide after pressing ESC key to exit to the upper level of ALT shortcuts. void SetHideOnDeactivateAltHost(bool value); /// Get the preferred client size for the menu. /// The preferred client size for the menu. Size GetPreferredMenuClientSize(); /// Set the preferred client size for the menu. /// The preferred client size for the menu. void SetPreferredMenuClientSize(Size value); }; /// Menu bar. class GuiMenuBar : public GuiControl, protected IGuiMenuService, public Description { private: IGuiMenuService* GetParentMenuService()override; Direction GetPreferredDirection()override; bool IsActiveState()override; bool IsSubMenuActivatedByMouseDown()override; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiMenuBar(theme::ThemeName themeName); ~GuiMenuBar(); IDescriptable* QueryService(const WString& identifier)override; }; /*********************************************************************** MenuButton ***********************************************************************/ /// Menu item. class GuiMenuButton : public GuiSelectableButton, private IGuiMenuDropdownProvider, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ToolstripButtonTemplate, GuiSelectableButton) using IEventHandler = compositions::IGuiGraphicsEventHandler; protected: Ptr subMenuDisposeFlag; Ptr subMenuWindowOpenedHandler; Ptr subMenuWindowClosedHandler; Ptr hostClickedHandler; Ptr hostMouseEnterHandler; Ptr image; Ptr largeImage; WString shortcutText; GuiMenu* subMenu; bool ownedSubMenu; Size preferredMenuClientSize; IGuiMenuService* ownerMenuService; bool cascadeAction; GuiButton* GetSubMenuHost(); bool OpenSubMenuInternal(); void OnParentLineChanged()override; compositions::IGuiAltActionHost* GetActivatingAltHost()override; void OnSubMenuWindowOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnSubMenuWindowClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); virtual IGuiMenuService::Direction GetSubMenuDirection(); private: void DetachSubMenu(); GuiMenu* ProvideDropdownMenu()override; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiMenuButton(theme::ThemeName themeName); ~GuiMenuButton(); /// Before sub menu opening event. compositions::GuiNotifyEvent BeforeSubMenuOpening; /// After sub menu opening event. compositions::GuiNotifyEvent AfterSubMenuOpening; /// Sub menu opening changed event. compositions::GuiNotifyEvent SubMenuOpeningChanged; /// Large image changed event. compositions::GuiNotifyEvent LargeImageChanged; /// Image changed event. compositions::GuiNotifyEvent ImageChanged; /// Shortcut text changed event. compositions::GuiNotifyEvent ShortcutTextChanged; /// Get the large image for the menu button. /// The large image for the menu button. Ptr GetLargeImage(); /// Set the large image for the menu button. /// The large image for the menu button. void SetLargeImage(Ptr value); /// Get the image for the menu button. /// The image for the menu button. Ptr GetImage(); /// Set the image for the menu button. /// The image for the menu button. void SetImage(Ptr value); /// Get the shortcut key text for the menu button. /// The shortcut key text for the menu button. const WString& GetShortcutText(); /// Set the shortcut key text for the menu button. /// The shortcut key text for the menu button. void SetShortcutText(const WString& value); /// Test does the sub menu exist. /// Returns true if the sub menu exists. bool IsSubMenuExists(); /// Get the sub menu. If the sub menu is not created, it returns null. /// The sub menu. GuiMenu* GetSubMenu(); /// Create the sub menu if necessary. The created sub menu is owned by this menu button. /// The created sub menu. /// The style controller for the sub menu. Set to null to use the default control template. GuiMenu* CreateSubMenu(TemplateProperty subMenuTemplate = {}); /// Associate a sub menu if there is no sub menu binded in this menu button. The associated sub menu is not owned by this menu button if the "owned" argument is set to false. /// The sub menu to associate. /// Set to true if the menu is expected to be owned. void SetSubMenu(GuiMenu* value, bool owned); /// Destroy the sub menu if necessary. void DestroySubMenu(); /// Test is the sub menu owned by this menu button. If the sub menu is owned, both deleting this menu button or calling will delete the sub menu. /// Returns true if the sub menu is owned by this menu button. bool GetOwnedSubMenu(); /// Test is the sub menu opened. /// Returns true if the sub menu is opened. bool GetSubMenuOpening(); /// Open or close the sub menu. /// Set to true to open the sub menu. void SetSubMenuOpening(bool value); /// Get the preferred client size for the sub menu. /// The preferred client size for the sub menu. Size GetPreferredMenuClientSize(); /// Set the preferred client size for the sub menu. /// The preferred client size for the sub menu. void SetPreferredMenuClientSize(Size value); /// Test is cascade action enabled. If the cascade action is enabled, when the mouse enter this menu button, the sub menu will be automatically opened if the parent menu is in an active state (see ), closing the sub menu will also close the parent menu. /// Returns true if cascade action is enabled. bool GetCascadeAction(); /// Enable or disable cascade action. /// Set to true to enable cascade action. void SetCascadeAction(bool value); IDescriptable* QueryService(const WString& identifier)override; }; } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUICOMBOCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUICOMBOCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUICOMBOCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** ComboBox Base ***********************************************************************/ /// The base class of combo box control. class GuiComboBoxBase : public GuiMenuButton, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ComboBoxTemplate, GuiMenuButton) protected: IGuiMenuService::Direction GetSubMenuDirection()override; void OnBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiComboBoxBase(theme::ThemeName themeName); ~GuiComboBoxBase(); }; /*********************************************************************** ComboBox with GuiListControl ***********************************************************************/ /// Combo box list control. This control is a combo box with a list control in its popup. class GuiComboBoxListControl : public GuiComboBoxBase , private GuiListControl::IItemProviderCallback , public Description { public: using ItemStyleProperty = TemplateProperty; protected: GuiSelectableListControl* containedListControl = nullptr; vint selectedIndex = -1; ItemStyleProperty itemStyleProperty; templates::GuiTemplate* itemStyleController = nullptr; Ptr boundsChangedHandler; void UpdateDisplayFont()override; void BeforeControlTemplateUninstalled()override; void AfterControlTemplateInstalled(bool initialize)override; void RemoveStyleController(); void InstallStyleController(vint itemIndex); virtual void DisplaySelectedContent(vint itemIndex); void AdoptSubMenuSize(); void OnTextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnContextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnVisuallyEnabledChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnAfterSubMenuOpening(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnListControlAdoptedSizeInvalidated(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnListControlBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnListControlItemMouseDown(compositions::GuiGraphicsComposition* sender, compositions::GuiItemMouseEventArgs& arguments); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); private: // ===================== GuiListControl::IItemProviderCallback ===================== void OnAttached(GuiListControl::IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; public: /// Create a control with a specified default theme and a list control that will be put in the popup control to show all items. /// The theme name for retriving a default control template. /// The list controller. GuiComboBoxListControl(theme::ThemeName themeName, GuiSelectableListControl* _containedListControl); ~GuiComboBoxListControl(); /// Style provider changed event. compositions::GuiNotifyEvent ItemTemplateChanged; /// Selected index changed event. compositions::GuiNotifyEvent SelectedIndexChanged; /// Get the list control. /// The list control. GuiSelectableListControl* GetContainedListControl(); /// Get the item style provider. /// The item style provider. virtual ItemStyleProperty GetItemTemplate(); /// Set the item style provider /// The new item style provider virtual void SetItemTemplate(ItemStyleProperty value); /// Get the selected index. /// The selected index. vint GetSelectedIndex(); /// Set the selected index. /// The selected index. void SetSelectedIndex(vint value); /// Get the selected item. /// The selected item. description::Value GetSelectedItem(); /// Get the item provider in the list control. /// The item provider in the list control. GuiListControl::IItemProvider* GetItemProvider(); }; } } } #endif /*********************************************************************** .\CONTROLS\GUIDATETIMECONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATETIMECONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIDATETIMECONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** DatePicker ***********************************************************************/ /// Date picker control that display a calendar. class GuiDatePicker : public GuiControl, protected compositions::GuiAltActionHostBase, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(DatePickerTemplate, GuiControl) protected: class CommandExecutor : public Object, public IDatePickerCommandExecutor { protected: GuiDatePicker* datePicker; public: CommandExecutor(GuiDatePicker* _datePicker); ~CommandExecutor(); void NotifyDateChanged()override; void NotifyDateNavigated()override; void NotifyDateSelected()override; }; Ptr commandExecutor; DateTime date; WString dateFormat; Locale dateLocale; compositions::IGuiAltActionHost* previousAltHost = nullptr; bool nestedAlt = false; void UpdateText(); bool IsAltAvailable()override; compositions::IGuiAltActionHost* GetActivatingAltHost()override; public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. /// Set to true to make this date picker an . GuiDatePicker(theme::ThemeName themeName, bool _nestedAlt = true); ~GuiDatePicker(); /// Date changed event. compositions::GuiNotifyEvent DateChanged; /// Date navigated event. Called when the current month is changed. compositions::GuiNotifyEvent DateNavigated; /// Date selected event. Called when a day button is selected. compositions::GuiNotifyEvent DateSelected; /// Date format changed event. compositions::GuiNotifyEvent DateFormatChanged; /// Date locale changed event. compositions::GuiNotifyEvent DateLocaleChanged; /// Get the displayed date. /// The date. const DateTime& GetDate(); /// Display a date. /// The date. void SetDate(const DateTime& value); /// Get the format. /// The format. const WString& GetDateFormat(); /// Set the format for the text of this control. /// The format. void SetDateFormat(const WString& value); /// Get the locale. /// The locale. const Locale& GetDateLocale(); /// Set the locale to display texts. /// The locale. void SetDateLocale(const Locale& value); void SetText(const WString& value)override; }; /*********************************************************************** DateComboBox ***********************************************************************/ /// A combo box control with a date picker control. class GuiDateComboBox : public GuiComboBoxBase, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(DateComboBoxTemplate, GuiComboBoxBase) protected: GuiDatePicker* datePicker; DateTime selectedDate; void UpdateText(); void NotifyUpdateSelectedDate(); void OnSubMenuOpeningChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void datePicker_DateLocaleChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void datePicker_DateFormatChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void datePicker_DateSelected(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a control with a specified style provider. /// The theme name for retriving a default control template. GuiDateComboBox(theme::ThemeName themeName); ~GuiDateComboBox(); /// Selected data changed event. compositions::GuiNotifyEvent SelectedDateChanged; void SetFont(const Nullable& value)override; /// Get the displayed date. /// The date. const DateTime& GetSelectedDate(); /// Display a date. /// The date. void SetSelectedDate(const DateTime& value); /// Get the date picker control. /// The date picker control. GuiDatePicker* GetDatePicker(); }; } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUILISTVIEWCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILISTVIEWCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUILISTVIEWCONTROLS namespace vl { namespace presentation { namespace controls { ///List view column header control for detailed view. class GuiListViewColumnHeader : public GuiMenuButton, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ListViewColumnHeaderTemplate, GuiMenuButton) protected: ColumnSortingState columnSortingState = ColumnSortingState::NotSorted; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiListViewColumnHeader(theme::ThemeName themeName); ~GuiListViewColumnHeader(); bool IsAltAvailable()override; /// Get the column sorting state. /// The column sorting state. ColumnSortingState GetColumnSortingState(); /// Set the column sorting state. /// The new column sorting state. void SetColumnSortingState(ColumnSortingState value); }; /// List view base control. All list view controls inherit from this class. class GuiListViewBase : public GuiSelectableListControl, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ListViewTemplate, GuiSelectableListControl) public: /// Create a list view base control. /// The theme name for retriving a default control template. /// The item provider for this control. GuiListViewBase(theme::ThemeName themeName, GuiListControl::IItemProvider* _itemProvider); ~GuiListViewBase(); /// Column clicked event. compositions::GuiItemNotifyEvent ColumnClicked; }; /*********************************************************************** ListView ItemStyleProvider ***********************************************************************/ namespace list { /// The required view for . class IListViewItemView : public virtual IDescriptable, public Description { public: /// The identifier for this view. static const wchar_t* const Identifier; /// Get the small image of an item. /// The small image. /// The index of the item. virtual Ptr GetSmallImage(vint itemIndex) = 0; /// Get the large image of an item. /// The large image. /// The index of the item. virtual Ptr GetLargeImage(vint itemIndex) = 0; /// Get the text of an item. /// The text. /// The index of the item. virtual WString GetText(vint itemIndex) = 0; /// Get the sub item text of an item. If the sub item index out of range, it returns an empty string. /// The sub item text. /// The index of the item. /// The sub item index of the item. virtual WString GetSubItem(vint itemIndex, vint index) = 0; /// Get the number of data columns. /// The number of data columns. virtual vint GetDataColumnCount() = 0; /// Get the column index of the index-th data column. /// The column index. /// The order of the data column. virtual vint GetDataColumn(vint index) = 0; /// Get the number of all columns. /// The number of all columns. virtual vint GetColumnCount() = 0; /// Get the text of the column. /// The text of the column. /// The index of the column. virtual WString GetColumnText(vint index) = 0; }; /*********************************************************************** ListViewColumnItemArranger ***********************************************************************/ /// List view column item arranger. This arranger contains column headers. When an column header is resized, all items will be notified via the [T:vl.presentation.controls.list.ListViewColumnItemArranger.IColumnItemView] for . class ListViewColumnItemArranger : public FixedHeightItemArranger, public Description { typedef collections::List ColumnHeaderButtonList; typedef collections::List ColumnHeaderSplitterList; public: static const vint SplitterWidth=8; /// Callback for [T:vl.presentation.controls.list.ListViewColumnItemArranger.IColumnItemView]. Column item view use this interface to notify column related modification. class IColumnItemViewCallback : public virtual IDescriptable, public Description { public: /// Called when any column is changed (inserted, removed, text changed, etc.). virtual void OnColumnChanged()=0; }; /// The required view for . class IColumnItemView : public virtual IDescriptable, public Description { public: /// The identifier for this view. static const wchar_t* const Identifier; /// Attach an column item view callback to this view. /// Returns true if this operation succeeded. /// The column item view callback. virtual bool AttachCallback(IColumnItemViewCallback* value)=0; /// Detach an column item view callback from this view. /// Returns true if this operation succeeded. /// The column item view callback. virtual bool DetachCallback(IColumnItemViewCallback* value)=0; /// Get the size of the column. /// The size of the column. /// The index of the column. virtual vint GetColumnSize(vint index)=0; /// Set the size of the column. /// The index of the column. /// The new size of the column. virtual void SetColumnSize(vint index, vint value)=0; /// Get the popup binded to the column. /// The popup binded to the column. /// The index of the column. virtual GuiMenu* GetDropdownPopup(vint index)=0; /// Get the sorting state of the column. /// The sorting state of the column. /// The index of the column. virtual ColumnSortingState GetSortingState(vint index)=0; }; protected: class ColumnItemViewCallback : public Object, public virtual IColumnItemViewCallback { protected: ListViewColumnItemArranger* arranger; public: ColumnItemViewCallback(ListViewColumnItemArranger* _arranger); ~ColumnItemViewCallback(); void OnColumnChanged(); }; GuiListViewBase* listView = nullptr; IListViewItemView* listViewItemView = nullptr; IColumnItemView* columnItemView = nullptr; Ptr columnItemViewCallback; compositions::GuiStackComposition* columnHeaders = nullptr; ColumnHeaderButtonList columnHeaderButtons; ColumnHeaderSplitterList columnHeaderSplitters; bool splitterDragging = false; vint splitterLatestX = 0; void ColumnClicked(vint index, compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void ColumnBoundsChanged(vint index, compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void ColumnHeaderSplitterLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void ColumnHeaderSplitterLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void ColumnHeaderSplitterMouseMove(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void RearrangeItemBounds()override; vint GetWidth()override; vint GetYOffset()override; Size OnCalculateTotalSize()override; void DeleteColumnButtons(); void RebuildColumns(); public: ListViewColumnItemArranger(); ~ListViewColumnItemArranger(); void AttachListControl(GuiListControl* value)override; void DetachListControl()override; }; } /*********************************************************************** ListViewItemProvider ***********************************************************************/ namespace list { class ListViewItem; class ListViewSubItems : public collections::ObservableListBase { friend class ListViewItem; protected: ListViewItem* owner; void NotifyUpdateInternal(vint start, vint count, vint newCount)override; public: }; class ListViewItemProvider; /// List view item. class ListViewItem : public Object, public Description { friend class ListViewSubItems; friend class ListViewItemProvider; protected: ListViewItemProvider* owner; ListViewSubItems subItems; Ptr smallImage; Ptr largeImage; WString text; description::Value tag; void NotifyUpdate(); public: /// Create a list view item. ListViewItem(); /// Get all sub items of this item. /// All sub items of this item. ListViewSubItems& GetSubItems(); /// Get the small image of this item. /// The small image of this item. Ptr GetSmallImage(); /// Set the small image of this item. /// The small image of this item. void SetSmallImage(Ptr value); /// Get the large image of this item. /// The large image of this item. Ptr GetLargeImage(); /// Set the large image of this item. /// The large image of this item. void SetLargeImage(Ptr value); /// Get the text of this item. /// The text of this item. const WString& GetText(); /// Set the text of this item. /// The text of this item. void SetText(const WString& value); /// Get the tag of this item. /// The tag of this item. description::Value GetTag(); /// Set the tag of this item. /// The tag of this item. void SetTag(const description::Value& value); }; class ListViewColumns; /// List view column. class ListViewColumn : public Object, public Description { friend class ListViewColumns; protected: ListViewColumns* owner = nullptr; WString text; ItemProperty textProperty; vint size; bool ownPopup = true; GuiMenu* dropdownPopup = nullptr; ColumnSortingState sortingState = ColumnSortingState::NotSorted; void NotifyUpdate(bool affectItem); public: /// Create a column with the specified text and size. /// The specified text. /// The specified size. ListViewColumn(const WString& _text=L"", vint _size=160); ~ListViewColumn(); /// Get the text of this item. /// The text of this item. const WString& GetText(); /// Set the text of this item. /// The text of this item. void SetText(const WString& value); /// Get the text property of this item. /// The text property of this item. ItemProperty GetTextProperty(); /// Set the text property of this item. /// The text property of this item. void SetTextProperty(const ItemProperty& value); /// Get the size of this item. /// The size of this item. vint GetSize(); /// Set the size of this item. /// The size of this item. void SetSize(vint value); /// Test if the column owns the popup. Owned popup will be deleted in the destructor. /// Returns true if the column owns the popup. bool GetOwnPopup(); /// Set if the column owns the popup. /// Set to true to let the column own the popup. void SetOwnPopup(bool value); /// Get the dropdown context menu of this item. /// The dropdown context menu of this item. GuiMenu* GetDropdownPopup(); /// Set the dropdown context menu of this item. /// The dropdown context menu of this item. void SetDropdownPopup(GuiMenu* value); /// Get the sorting state of this item. /// The sorting state of this item. ColumnSortingState GetSortingState(); /// Set the sorting state of this item. /// The sorting state of this item. void SetSortingState(ColumnSortingState value); }; class IListViewItemProvider : public virtual Interface { public: virtual void NotifyAllItemsUpdate() = 0; virtual void NotifyAllColumnsUpdate() = 0; }; /// List view data column container. class ListViewDataColumns : public collections::ObservableListBase { protected: IListViewItemProvider* itemProvider; void NotifyUpdateInternal(vint start, vint count, vint newCount)override; public: /// Create a container. /// The item provider in the same control to receive notifications. ListViewDataColumns(IListViewItemProvider* _itemProvider); ~ListViewDataColumns(); }; /// List view column container. class ListViewColumns : public collections::ObservableListBase> { friend class ListViewColumn; protected: IListViewItemProvider* itemProvider; bool affectItemFlag = true; void NotifyColumnUpdated(vint column, bool affectItem); void AfterInsert(vint index, const Ptr& value)override; void BeforeRemove(vint index, const Ptr& value)override; void NotifyUpdateInternal(vint start, vint count, vint newCount)override; public: /// Create a container. /// The item provider in the same control to receive notifications. ListViewColumns(IListViewItemProvider* _itemProvider); ~ListViewColumns(); }; /// Item provider for . class ListViewItemProvider : public ListProvider> , protected virtual IListViewItemProvider , public virtual IListViewItemView , public virtual ListViewColumnItemArranger::IColumnItemView , public Description { friend class ListViewItem; friend class ListViewColumns; friend class ListViewDataColumns; typedef collections::List ColumnItemViewCallbackList; protected: ListViewDataColumns dataColumns; ListViewColumns columns; ColumnItemViewCallbackList columnItemViewCallbacks; void AfterInsert(vint index, const Ptr& value)override; void BeforeRemove(vint index, const Ptr& value)override; void NotifyAllItemsUpdate()override; void NotifyAllColumnsUpdate()override; Ptr GetSmallImage(vint itemIndex)override; Ptr GetLargeImage(vint itemIndex)override; WString GetText(vint itemIndex)override; WString GetSubItem(vint itemIndex, vint index)override; vint GetDataColumnCount()override; vint GetDataColumn(vint index)override; vint GetColumnCount()override; WString GetColumnText(vint index)override;; bool AttachCallback(ListViewColumnItemArranger::IColumnItemViewCallback* value)override; bool DetachCallback(ListViewColumnItemArranger::IColumnItemViewCallback* value)override; vint GetColumnSize(vint index)override; void SetColumnSize(vint index, vint value)override; GuiMenu* GetDropdownPopup(vint index)override; ColumnSortingState GetSortingState(vint index)override; WString GetTextValue(vint itemIndex)override; description::Value GetBindingValue(vint itemIndex)override; public: ListViewItemProvider(); ~ListViewItemProvider(); IDescriptable* RequestView(const WString& identifier)override; /// Get all data columns indices in columns. /// All data columns indices in columns. ListViewDataColumns& GetDataColumns(); /// Get all columns. /// All columns. ListViewColumns& GetColumns(); }; } /*********************************************************************** GuiVirtualListView ***********************************************************************/ enum class ListViewView { BigIcon, SmallIcon, List, Tile, Information, Detail, Unknown, }; /// List view control in virtual mode. class GuiVirtualListView : public GuiListViewBase, public Description { protected: ListViewView view = ListViewView::Unknown; void OnStyleInstalled(vint itemIndex, ItemStyle* style)override; void OnItemTemplateChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a list view control in virtual mode. /// The theme name for retriving a default control template. /// The item provider for this control. GuiVirtualListView(theme::ThemeName themeName, GuiListControl::IItemProvider* _itemProvider); ~GuiVirtualListView(); /// Get the current view. /// The current view. After [M:vl.presentation.controls.GuiListControl.SetItemTemplate] is called, the current view is reset to Unknown. ListViewView GetView(); /// Set the current view. /// The current view. void SetView(ListViewView _view); }; /*********************************************************************** GuiListView ***********************************************************************/ /// List view control in virtual mode. class GuiListView : public GuiVirtualListView, public Description { protected: list::ListViewItemProvider* items; public: /// Create a list view control. /// The theme name for retriving a default control template. GuiListView(theme::ThemeName themeName); ~GuiListView(); /// Get all list view items. /// All list view items. list::ListViewItemProvider& GetItems(); /// Get all data columns indices in columns. /// All data columns indices in columns. list::ListViewDataColumns& GetDataColumns(); /// Get all columns. /// All columns. list::ListViewColumns& GetColumns(); /// Get the selected item. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. Ptr GetSelectedItem(); }; } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUIBINDABLELISTCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIBINDABLELISTCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIBINDABLELISTCONTROLS namespace vl { namespace presentation { namespace controls { template struct DefaultValueOf { static T Get() { return reflection::description::TypedValueSerializerProvider::GetDefaultValue(); } }; template struct DefaultValueOf> { static Ptr Get() { return nullptr; } }; template<> struct DefaultValueOf { static description::Value Get() { return description::Value(); } }; template T ReadProperty(const description::Value& thisObject, const ItemProperty& propertyName) { if (!thisObject.IsNull() && propertyName) { return propertyName(thisObject); } else { return DefaultValueOf::Get(); } } template T ReadProperty(const description::Value& thisObject, const WritableItemProperty& propertyName) { auto defaultValue = DefaultValueOf::Get(); if (!thisObject.IsNull() && propertyName) { return propertyName(thisObject, defaultValue, false); } else { return defaultValue; } } template void WriteProperty(const description::Value& thisObject, const WritableItemProperty& propertyName, const T& value) { if (!thisObject.IsNull() && propertyName) { propertyName(thisObject, value, true); } } /*********************************************************************** GuiBindableTextList ***********************************************************************/ /// A bindable Text list control. class GuiBindableTextList : public GuiVirtualTextList, public Description { protected: class ItemSource : public list::ItemProviderBase , protected list::ITextItemView { protected: Ptr itemChangedEventHandler; Ptr itemSource; public: ItemProperty textProperty; WritableItemProperty checkedProperty; public: ItemSource(); ~ItemSource(); Ptr GetItemSource(); void SetItemSource(Ptr _itemSource); description::Value Get(vint index); void UpdateBindingProperties(); // ===================== GuiListControl::IItemProvider ===================== WString GetTextValue(vint itemIndex)override; description::Value GetBindingValue(vint itemIndex)override; vint Count()override; IDescriptable* RequestView(const WString& identifier)override; // ===================== list::TextItemStyleProvider::ITextItemView ===================== bool GetChecked(vint itemIndex)override; void SetChecked(vint itemIndex, bool value)override; }; protected: ItemSource* itemSource; public: /// Create a bindable Text list control. /// The theme name for retriving a default control template. GuiBindableTextList(theme::ThemeName themeName); ~GuiBindableTextList(); /// Text property name changed event. compositions::GuiNotifyEvent TextPropertyChanged; /// Checked property name changed event. compositions::GuiNotifyEvent CheckedPropertyChanged; /// Get the item source. /// The item source. Ptr GetItemSource(); /// Set the item source. /// The item source. Null is acceptable if you want to clear all data. void SetItemSource(Ptr _itemSource); /// Get the text property name to get the item text from an item. /// The text property name. ItemProperty GetTextProperty(); /// Set the text property name to get the item text from an item. /// The text property name. void SetTextProperty(const ItemProperty& value); /// Get the checked property name to get the check state from an item. /// The checked property name. WritableItemProperty GetCheckedProperty(); /// Set the checked property name to get the check state from an item. /// The checked property name. void SetCheckedProperty(const WritableItemProperty& value); /// Get the selected item. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. description::Value GetSelectedItem(); }; /*********************************************************************** GuiBindableListView ***********************************************************************/ /// A bindable List view control. class GuiBindableListView : public GuiVirtualListView, public Description { protected: class ItemSource : public list::ItemProviderBase , protected virtual list::IListViewItemProvider , public virtual list::IListViewItemView , public virtual list::ListViewColumnItemArranger::IColumnItemView { typedef collections::List ColumnItemViewCallbackList; protected: list::ListViewDataColumns dataColumns; list::ListViewColumns columns; ColumnItemViewCallbackList columnItemViewCallbacks; Ptr itemChangedEventHandler; Ptr itemSource; public: ItemProperty> largeImageProperty; ItemProperty> smallImageProperty; public: ItemSource(); ~ItemSource(); Ptr GetItemSource(); void SetItemSource(Ptr _itemSource); description::Value Get(vint index); void UpdateBindingProperties(); bool NotifyUpdate(vint start, vint count); list::ListViewDataColumns& GetDataColumns(); list::ListViewColumns& GetColumns(); // ===================== list::IListViewItemProvider ===================== void NotifyAllItemsUpdate()override; void NotifyAllColumnsUpdate()override; // ===================== GuiListControl::IItemProvider ===================== WString GetTextValue(vint itemIndex)override; description::Value GetBindingValue(vint itemIndex)override; vint Count()override; IDescriptable* RequestView(const WString& identifier)override; // ===================== list::ListViewItemStyleProvider::IListViewItemView ===================== Ptr GetSmallImage(vint itemIndex)override; Ptr GetLargeImage(vint itemIndex)override; WString GetText(vint itemIndex)override; WString GetSubItem(vint itemIndex, vint index)override; vint GetDataColumnCount()override; vint GetDataColumn(vint index)override; vint GetColumnCount()override; WString GetColumnText(vint index)override; // ===================== list::ListViewColumnItemArranger::IColumnItemView ===================== bool AttachCallback(list::ListViewColumnItemArranger::IColumnItemViewCallback* value)override; bool DetachCallback(list::ListViewColumnItemArranger::IColumnItemViewCallback* value)override; vint GetColumnSize(vint index)override; void SetColumnSize(vint index, vint value)override; GuiMenu* GetDropdownPopup(vint index)override; ColumnSortingState GetSortingState(vint index)override; }; protected: ItemSource* itemSource; public: /// Create a bindable List view control. /// The theme name for retriving a default control template. GuiBindableListView(theme::ThemeName themeName); ~GuiBindableListView(); /// Get all data columns indices in columns. /// All data columns indices in columns. list::ListViewDataColumns& GetDataColumns(); /// Get all columns. /// All columns. list::ListViewColumns& GetColumns(); /// Get the item source. /// The item source. Ptr GetItemSource(); /// Set the item source. /// The item source. Null is acceptable if you want to clear all data. void SetItemSource(Ptr _itemSource); /// Large image property name changed event. compositions::GuiNotifyEvent LargeImagePropertyChanged; /// Small image property name changed event. compositions::GuiNotifyEvent SmallImagePropertyChanged; /// Get the large image property name to get the large image from an item. /// The large image property name. ItemProperty> GetLargeImageProperty(); /// Set the large image property name to get the large image from an item. /// The large image property name. void SetLargeImageProperty(const ItemProperty>& value); /// Get the small image property name to get the small image from an item. /// The small image property name. ItemProperty> GetSmallImageProperty(); /// Set the small image property name to get the small image from an item. /// The small image property name. void SetSmallImageProperty(const ItemProperty>& value); /// Get the selected item. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. description::Value GetSelectedItem(); }; /*********************************************************************** GuiBindableTreeView ***********************************************************************/ /// A bindable Tree view control. class GuiBindableTreeView : public GuiVirtualTreeView, public Description { using IValueEnumerable = reflection::description::IValueEnumerable; protected: class ItemSource; class ItemSourceNode : public Object , public virtual tree::INodeProvider { friend class ItemSource; typedef collections::List> NodeList; protected: description::Value itemSource; ItemSource* rootProvider; ItemSourceNode* parent; tree::INodeProviderCallback* callback; bool expanding = false; Ptr itemChangedEventHandler; Ptr childrenVirtualList; NodeList children; Ptr PrepareValueList(const description::Value& inputItemSource); void PrepareChildren(Ptr newValueList); void UnprepareChildren(); public: ItemSourceNode(const description::Value& _itemSource, ItemSourceNode* _parent); ItemSourceNode(ItemSource* _rootProvider); ~ItemSourceNode(); description::Value GetItemSource(); void SetItemSource(const description::Value& _itemSource); // ===================== tree::INodeProvider ===================== bool GetExpanding()override; void SetExpanding(bool value)override; vint CalculateTotalVisibleNodes()override; vint GetChildCount()override; Ptr GetParent()override; Ptr GetChild(vint index)override; }; class ItemSource : public tree::NodeRootProviderBase , public virtual tree::ITreeViewItemView { friend class ItemSourceNode; public: ItemProperty textProperty; ItemProperty> imageProperty; ItemProperty> childrenProperty; Ptr rootNode; public: ItemSource(); ~ItemSource(); description::Value GetItemSource(); void SetItemSource(const description::Value& _itemSource); void UpdateBindingProperties(bool updateChildrenProperty); // ===================== tree::INodeRootProvider ===================== Ptr GetRootNode()override; WString GetTextValue(tree::INodeProvider* node)override; description::Value GetBindingValue(tree::INodeProvider* node)override; IDescriptable* RequestView(const WString& identifier)override; // ===================== tree::ITreeViewItemView ===================== Ptr GetNodeImage(tree::INodeProvider* node)override; }; protected: ItemSource* itemSource; public: /// Create a bindable Tree view control. /// The theme name for retriving a default control template. GuiBindableTreeView(theme::ThemeName themeName); ~GuiBindableTreeView(); /// Text property name changed event. compositions::GuiNotifyEvent TextPropertyChanged; /// Image property name changed event. compositions::GuiNotifyEvent ImagePropertyChanged; /// Children property name changed event. compositions::GuiNotifyEvent ChildrenPropertyChanged; /// Get the item source. /// The item source. description::Value GetItemSource(); /// Set the item source. /// The item source. Null is acceptable if you want to clear all data. void SetItemSource(description::Value _itemSource); /// Get the text property name to get the item text from an item. /// The text property name. ItemProperty GetTextProperty(); /// Set the text property name to get the item text from an item. /// The text property name. void SetTextProperty(const ItemProperty& value); /// Get the image property name to get the image from an item. /// The image property name. ItemProperty> GetImageProperty(); /// Set the image property name to get the image from an item. /// The image property name. void SetImageProperty(const ItemProperty>& value); /// Get the children property name to get the children from an item. /// The children property name. ItemProperty> GetChildrenProperty(); /// Set the children property name to get the children from an item. /// The children property name. void SetChildrenProperty(const ItemProperty>& value); /// Get the selected item. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. description::Value GetSelectedItem(); }; } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUIDATAGRIDINTERFACES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATAGRIDINTERFACES #define VCZH_PRESENTATION_CONTROLS_GUIDATAGRIDINTERFACES namespace vl { namespace presentation { namespace controls { namespace list { /*********************************************************************** Datagrid Interfaces ***********************************************************************/ class IDataVisualizer; class IDataEditor; /// The data grid context. class IDataGridContext : public virtual IDescriptable, public Description { public: virtual GuiListControl::IItemProvider* GetItemProvider() = 0; virtual templates::GuiListViewTemplate* GetListViewControlTemplate() = 0; virtual void RequestSaveData() = 0; }; /// The visualizer factory. class IDataVisualizerFactory : public virtual IDescriptable, public Description { public: /// Create a data visualizer. /// The created data visualizer. /// Context information of the data grid. virtual Ptr CreateVisualizer(IDataGridContext* dataGridContext) = 0; }; /// The visualizer for each cell in [T:vl.presentation.controls.GuiVirtualDataGrid]. class IDataVisualizer : public virtual IDescriptable, public Description { public: /// Get the factory object that creates this visualizer. /// The factory object. virtual IDataVisualizerFactory* GetFactory() = 0; /// Get the template that renders the data. The data visualizer should maintain this template, and delete it when necessary. /// The template. virtual templates::GuiGridVisualizerTemplate* GetTemplate() = 0; /// Notify that the template has been deleted during the deconstruction of UI objects. virtual void NotifyDeletedTemplate() = 0; /// Called before visualizing a cell. /// The item provider. /// The row number of the cell. /// The column number of the cell. virtual void BeforeVisualizeCell(GuiListControl::IItemProvider* itemProvider, vint row, vint column) = 0; /// Set the selected state. /// Set to true to make this data visualizer looks selected. virtual void SetSelected(bool value) = 0; }; /// The editor factory. class IDataEditorFactory : public virtual IDescriptable, public Description { public: /// Create a data editor. /// The created data editor. /// Context information of the data grid. virtual Ptr CreateEditor(IDataGridContext* dataGridContext) = 0; }; /// The editor for each cell in [T:vl.presentation.controls.GuiVirtualDataGrid]. class IDataEditor : public virtual IDescriptable, public Description { public: /// Get the factory object that creates this editor. /// The factory object. virtual IDataEditorFactory* GetFactory() = 0; /// Get the template that edit the data. The data editor should maintain this template, and delete it when necessary. /// The template. virtual templates::GuiGridEditorTemplate* GetTemplate() = 0; /// Notify that the template has been deleted during the deconstruction of UI objects. virtual void NotifyDeletedTemplate() = 0; /// Called before editing a cell. /// The item provider. /// The row number of the cell. /// The column number of the cell. virtual void BeforeEditCell(GuiListControl::IItemProvider* itemProvider, vint row, vint column) = 0; /// Test if the edit has saved the data. /// Returns true if the data is saved. virtual bool GetCellValueSaved() = 0; }; /// The required view for [T:vl.presentation.controls.GuiVirtualDataGrid]. class IDataGridView : public virtual IDescriptable, public Description { public: /// The identifier for this view. static const wchar_t* const Identifier; /// Test is a column sortable. /// Returns true if this column is sortable. /// The index of the column. virtual bool IsColumnSortable(vint column) = 0; /// Set the column sorting state to update the data. /// The index of the column. Set to -1 means go back to the unsorted state. /// Set to true if the data is sorted in ascending order. virtual void SortByColumn(vint column, bool ascending) = 0; /// Get the sorted columm. If no column is under a sorted state, it returns -1. /// The column number. virtual vint GetSortedColumn() = 0; /// Test is the sort order ascending. /// Returns true if the sort order is ascending. virtual bool IsSortOrderAscending() = 0; /// Get the column span for the cell. /// The column span for the cell. /// The row number for the cell. /// The column number for the cell. virtual vint GetCellSpan(vint row, vint column) = 0; /// Get the data visualizer factory that creates data visualizers for visualizing the cell. /// The data visualizer factory. The data grid control to use the predefined data visualizer if this function returns null. /// The row number for the cell. /// The column number for the cell. virtual IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row, vint column) = 0; /// Get the data editor factory that creates data editors for editing the cell. /// The data editor factory. Returns null to disable editing. /// The row number for the cell. /// The column number for the cell. virtual IDataEditorFactory* GetCellDataEditorFactory(vint row, vint column) = 0; /// Get the binding value of a cell. /// The binding value of cell. /// The row index of the cell. /// The column index of the cell. virtual description::Value GetBindingCellValue(vint row, vint column) = 0; /// Set the binding value of a cell. /// The row index of the cell. /// The column index of the cell. /// The value to set. virtual void SetBindingCellValue(vint row, vint column, const description::Value& value) = 0; }; } } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUIDATAGRIDEXTENSIONS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATAEXTENSIONS #define VCZH_PRESENTATION_CONTROLS_GUIDATAEXTENSIONS namespace vl { namespace presentation { namespace controls { namespace list { /*********************************************************************** Extension Bases ***********************************************************************/ class DataVisualizerFactory; class DataEditorFactory; /// Base class for all data visualizers. class DataVisualizerBase : public Object, public virtual IDataVisualizer { friend class DataVisualizerFactory; using ItemTemplate = templates::GuiGridVisualizerTemplate; protected: DataVisualizerFactory* factory = nullptr; IDataGridContext* dataGridContext = nullptr; templates::GuiGridVisualizerTemplate* visualizerTemplate = nullptr; public: /// Create the data visualizer. DataVisualizerBase(); ~DataVisualizerBase(); IDataVisualizerFactory* GetFactory()override; templates::GuiGridVisualizerTemplate* GetTemplate()override; void NotifyDeletedTemplate()override; void BeforeVisualizeCell(GuiListControl::IItemProvider* itemProvider, vint row, vint column)override; void SetSelected(bool value)override; }; class DataVisualizerFactory : public Object, public virtual IDataVisualizerFactory, public Description { using ItemTemplate = templates::GuiGridVisualizerTemplate; protected: TemplateProperty templateFactory; Ptr decoratedFactory; ItemTemplate* CreateItemTemplate(controls::list::IDataGridContext* dataGridContext); public: DataVisualizerFactory(TemplateProperty _templateFactory, Ptr _decoratedFactory = nullptr); ~DataVisualizerFactory(); Ptr CreateVisualizer(IDataGridContext* dataGridContext)override; }; /// Base class for all data editors. class DataEditorBase : public Object, public virtual IDataEditor { friend class DataEditorFactory; using ItemTemplate = templates::GuiGridEditorTemplate; protected: IDataEditorFactory* factory = nullptr; IDataGridContext* dataGridContext = nullptr; templates::GuiGridEditorTemplate* editorTemplate = nullptr; void OnCellValueChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create the data editor. DataEditorBase(); ~DataEditorBase(); IDataEditorFactory* GetFactory()override; templates::GuiGridEditorTemplate* GetTemplate()override; void NotifyDeletedTemplate()override; void BeforeEditCell(GuiListControl::IItemProvider* itemProvider, vint row, vint column)override; bool GetCellValueSaved()override; }; class DataEditorFactory : public Object, public virtual IDataEditorFactory, public Description { using ItemTemplate = templates::GuiGridEditorTemplate; protected: TemplateProperty templateFactory; public: DataEditorFactory(TemplateProperty _templateFactory); ~DataEditorFactory(); Ptr CreateEditor(IDataGridContext* dataGridContext)override; }; /*********************************************************************** Visualizer Extensions ***********************************************************************/ class MainColumnVisualizerTemplate : public templates::GuiGridVisualizerTemplate, public Description { protected: elements::GuiImageFrameElement* image = nullptr; elements::GuiSolidLabelElement* text = nullptr; void OnTextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextColorChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnSmallImageChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: MainColumnVisualizerTemplate(); ~MainColumnVisualizerTemplate(); }; class SubColumnVisualizerTemplate : public templates::GuiGridVisualizerTemplate, public Description { protected: elements::GuiSolidLabelElement* text = nullptr; void OnTextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextColorChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void Initialize(bool fixTextColor); SubColumnVisualizerTemplate(bool fixTextColor); public: SubColumnVisualizerTemplate(); ~SubColumnVisualizerTemplate(); }; class HyperlinkVisualizerTemplate : public SubColumnVisualizerTemplate, public Description { protected: void label_MouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void label_MouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: HyperlinkVisualizerTemplate(); ~HyperlinkVisualizerTemplate(); }; class FocusRectangleVisualizerTemplate : public templates::GuiGridVisualizerTemplate, public Description { protected: compositions::GuiBoundsComposition* focusComposition = nullptr; void OnSelectedChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: FocusRectangleVisualizerTemplate(); ~FocusRectangleVisualizerTemplate(); }; class CellBorderVisualizerTemplate : public templates::GuiGridVisualizerTemplate, public Description { protected: elements::GuiSolidBorderElement* border1 = nullptr; elements::GuiSolidBorderElement* border2 = nullptr; void OnItemSeparatorColorChanged(GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: CellBorderVisualizerTemplate(); ~CellBorderVisualizerTemplate(); }; } } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUILISTVIEWITEMTEMPLATES.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILISTVIEWITEMTEMPLATES #define VCZH_PRESENTATION_CONTROLS_GUILISTVIEWITEMTEMPLATES namespace vl { namespace presentation { namespace controls { namespace list { class DefaultListViewItemTemplate : public templates::GuiListItemTemplate { public: DefaultListViewItemTemplate(); ~DefaultListViewItemTemplate(); }; class BigIconListViewItemTemplate : public DefaultListViewItemTemplate { protected: elements::GuiImageFrameElement* image = nullptr; elements::GuiSolidLabelElement* text = nullptr; void OnInitialize()override; void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: BigIconListViewItemTemplate(); ~BigIconListViewItemTemplate(); }; class SmallIconListViewItemTemplate : public DefaultListViewItemTemplate { protected: elements::GuiImageFrameElement* image = nullptr; elements::GuiSolidLabelElement* text = nullptr; void OnInitialize()override; void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: SmallIconListViewItemTemplate(); ~SmallIconListViewItemTemplate(); }; class ListListViewItemTemplate : public DefaultListViewItemTemplate { protected: elements::GuiImageFrameElement* image = nullptr; elements::GuiSolidLabelElement* text = nullptr; void OnInitialize()override; void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: ListListViewItemTemplate(); ~ListListViewItemTemplate(); }; class TileListViewItemTemplate : public DefaultListViewItemTemplate { typedef collections::Array DataTextElementArray; protected: elements::GuiImageFrameElement* image = nullptr; elements::GuiSolidLabelElement* text = nullptr; compositions::GuiTableComposition* textTable = nullptr; DataTextElementArray dataTexts; elements::GuiSolidLabelElement* CreateTextElement(vint textRow); void ResetTextTable(vint textRows); void OnInitialize()override; void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: TileListViewItemTemplate(); ~TileListViewItemTemplate(); }; class InformationListViewItemTemplate : public DefaultListViewItemTemplate { typedef collections::Array DataTextElementArray; protected: elements::GuiImageFrameElement* image = nullptr; elements::GuiSolidLabelElement* text = nullptr; compositions::GuiTableComposition* textTable = nullptr; DataTextElementArray columnTexts; DataTextElementArray dataTexts; elements::GuiSolidBackgroundElement* bottomLine = nullptr; compositions::GuiBoundsComposition* bottomLineComposition = nullptr; void OnInitialize()override; void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: InformationListViewItemTemplate(); ~InformationListViewItemTemplate(); }; class DetailListViewItemTemplate : public DefaultListViewItemTemplate , public virtual ListViewColumnItemArranger::IColumnItemViewCallback { typedef collections::Array SubItemList; typedef ListViewColumnItemArranger::IColumnItemView IColumnItemView; protected: IColumnItemView* columnItemView = nullptr; elements::GuiImageFrameElement* image = nullptr; elements::GuiSolidLabelElement* text = nullptr; compositions::GuiTableComposition* textTable = nullptr; SubItemList subItems; void OnInitialize()override; void OnColumnChanged()override; void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: DetailListViewItemTemplate(); ~DetailListViewItemTemplate(); }; } } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUIDATAGRIDCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATAGRIDCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIDATAGRIDCONTROLS namespace vl { namespace presentation { namespace controls { class GuiVirtualDataGrid; namespace list { /*********************************************************************** DefaultDataGridItemTemplate ***********************************************************************/ class DefaultDataGridItemTemplate : public DefaultListViewItemTemplate , public ListViewColumnItemArranger::IColumnItemViewCallback { protected: compositions::GuiTableComposition* textTable = nullptr; collections::Array> dataVisualizers; IDataEditor* currentEditor = nullptr; IDataVisualizerFactory* GetDataVisualizerFactory(vint row, vint column); IDataEditorFactory* GetDataEditorFactory(vint row, vint column); vint GetCellColumnIndex(compositions::GuiGraphicsComposition* composition); bool IsInEditor(GuiVirtualDataGrid* dataGrid, compositions::GuiMouseEventArgs& arguments); void OnCellButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnCellLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnCellRightButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); void OnColumnChanged()override; void OnInitialize()override; void OnSelectedChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnContextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnVisuallyEnabledChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: DefaultDataGridItemTemplate(); ~DefaultDataGridItemTemplate(); void UpdateSubItemSize(); bool IsEditorOpened(); void NotifyOpenEditor(vint column, IDataEditor* editor); void NotifyCloseEditor(); void NotifySelectCell(vint column); void NotifyCellEdited(); }; } /*********************************************************************** GuiVirtualDataGrid ***********************************************************************/ /// Data grid control in virtual mode. class GuiVirtualDataGrid : public GuiVirtualListView , protected compositions::GuiAltActionHostBase , private list::IDataGridContext , public Description { friend class list::DefaultDataGridItemTemplate; protected: list::IListViewItemView* listViewItemView = nullptr; list::ListViewColumnItemArranger::IColumnItemView* columnItemView = nullptr; list::IDataGridView* dataGridView = nullptr; Ptr defaultMainColumnVisualizerFactory; Ptr defaultSubColumnVisualizerFactory; bool skipOnSelectionChanged = false; GridPos selectedCell{ -1,-1 }; Ptr currentEditor; GridPos currentEditorPos{ -1,-1 }; bool currentEditorOpeningEditor = false; compositions::IGuiAltActionHost* GetActivatingAltHost()override; void OnItemModified(vint start, vint count, vint newCount)override; void OnStyleInstalled(vint index, ItemStyle* style)override; void OnStyleUninstalled(ItemStyle* style)override; void NotifyCloseEditor(); void NotifySelectCell(vint row, vint column); bool StartEdit(vint row, vint column); void StopEdit(); void OnColumnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); void OnSelectionChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); void OnKeyUp(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments); public: templates::GuiListViewTemplate* GetListViewControlTemplate()override; void RequestSaveData()override; public: /// Create a data grid control in virtual mode. /// The theme name for retriving a default control template. /// The item provider for this control. GuiVirtualDataGrid(theme::ThemeName themeName, GuiListControl::IItemProvider* _itemProvider); ~GuiVirtualDataGrid(); /// Selected cell changed event. compositions::GuiNotifyEvent SelectedCellChanged; IItemProvider* GetItemProvider()override; /// Change the view to data grid's default view. void SetViewToDefault(); /// Get the row index and column index of the selected cell. /// The row index and column index of the selected cell. GridPos GetSelectedCell(); /// Select a cell. /// Returns true if the editor is opened. /// The row index and column index of the selected cell. /// Set to true to open an editor. bool SelectCell(const GridPos& value, bool openEditor); }; } } } #endif /*********************************************************************** .\CONTROLS\LISTCONTROLPACKAGE\GUIBINDABLEDATAGRID.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIDATASTRUCTURED #define VCZH_PRESENTATION_CONTROLS_GUIDATASTRUCTURED namespace vl { namespace presentation { namespace controls { class GuiBindableDataGrid; namespace list { /*********************************************************************** Interfaces ***********************************************************************/ class IDataProcessorCallback : public virtual IDescriptable, public Description { public: virtual GuiListControl::IItemProvider* GetItemProvider() = 0; virtual void OnProcessorChanged() = 0; }; class IDataFilter : public virtual IDescriptable, public Description { public: virtual void SetCallback(IDataProcessorCallback* value) = 0; virtual bool Filter(const description::Value& row) = 0; }; class IDataSorter : public virtual IDescriptable, public Description { public: virtual void SetCallback(IDataProcessorCallback* value) = 0; virtual vint Compare(const description::Value& row1, const description::Value& row2) = 0; }; /*********************************************************************** Filter Extensions ***********************************************************************/ /// Base class for . class DataFilterBase : public Object, public virtual IDataFilter, public Description { protected: IDataProcessorCallback* callback = nullptr; /// Called when the structure or properties for this filter is changed. void InvokeOnProcessorChanged(); public: DataFilterBase(); void SetCallback(IDataProcessorCallback* value)override; }; /// Base class for a that contains multiple sub filters. class DataMultipleFilter : public DataFilterBase, public Description { protected: collections::List> filters; public: DataMultipleFilter(); /// Add a sub filter. /// Returns true if this operation succeeded. /// The sub filter. bool AddSubFilter(Ptr value); /// Remove a sub filter. /// Returns true if this operation succeeded. /// The sub filter. bool RemoveSubFilter(Ptr value); void SetCallback(IDataProcessorCallback* value)override; }; /// A filter that keep a row if all sub filters agree. class DataAndFilter : public DataMultipleFilter, public Description { public: /// Create the filter. DataAndFilter(); bool Filter(const description::Value& row)override; }; /// A filter that keep a row if one of all sub filters agrees. class DataOrFilter : public DataMultipleFilter, public Description { public: /// Create the filter. DataOrFilter(); bool Filter(const description::Value& row)override; }; /// A filter that keep a row if the sub filter not agrees. class DataNotFilter : public DataFilterBase, public Description { protected: Ptr filter; public: /// Create the filter. DataNotFilter(); /// Set a sub filter. /// Returns true if this operation succeeded. /// The sub filter. bool SetSubFilter(Ptr value); void SetCallback(IDataProcessorCallback* value)override; bool Filter(const description::Value& row)override; }; /*********************************************************************** Sorter Extensions ***********************************************************************/ /// Base class for . class DataSorterBase : public Object, public virtual IDataSorter, public Description { protected: IDataProcessorCallback* callback = nullptr; /// Called when the structure or properties for this filter is changed. void InvokeOnProcessorChanged(); public: DataSorterBase(); void SetCallback(IDataProcessorCallback* value)override; }; /// A multi-level . class DataMultipleSorter : public DataSorterBase, public Description { protected: Ptr leftSorter; Ptr rightSorter; public: /// Create the sorter. DataMultipleSorter(); /// Set the first sub sorter. /// Returns true if this operation succeeded. /// The sub sorter. bool SetLeftSorter(Ptr value); /// Set the second sub sorter. /// Returns true if this operation succeeded. /// The sub sorter. bool SetRightSorter(Ptr value); void SetCallback(IDataProcessorCallback* value)override; vint Compare(const description::Value& row1, const description::Value& row2)override; }; /// A reverse order . class DataReverseSorter : public DataSorterBase, public Description { protected: Ptr sorter; public: /// Create the sorter. DataReverseSorter(); /// Set the sub sorter. /// Returns true if this operation succeeded. /// The sub sorter. bool SetSubSorter(Ptr value); void SetCallback(IDataProcessorCallback* value)override; vint Compare(const description::Value& row1, const description::Value& row2)override; }; /*********************************************************************** DataColumn ***********************************************************************/ class DataColumns; class DataProvider; /// Datagrid Column. class DataColumn : public Object, public Description { friend class DataColumns; friend class DataProvider; protected: DataProvider* dataProvider = nullptr; ItemProperty textProperty; WritableItemProperty valueProperty; WString text; vint size = 160; ColumnSortingState sortingState = ColumnSortingState::NotSorted; bool ownPopup = true; GuiMenu* popup = nullptr; Ptr associatedFilter; Ptr associatedSorter; Ptr visualizerFactory; Ptr editorFactory; void NotifyAllColumnsUpdate(bool affectItem); public: DataColumn(); ~DataColumn(); /// Value property name changed event. compositions::GuiNotifyEvent ValuePropertyChanged; /// Text property name changed event. compositions::GuiNotifyEvent TextPropertyChanged; /// Get the text for the column. /// The text for the column. WString GetText(); /// Set the text for the column. /// The text for the column. void SetText(const WString& value); /// Get the size for the column. /// The size for the column. vint GetSize(); /// Set the size for the column. /// The size for the column. void SetSize(vint value); /// Test if the column owns the popup. Owned popup will be deleted in the destructor. /// Returns true if the column owns the popup. bool GetOwnPopup(); /// Set if the column owns the popup. /// Set to true to let the column own the popup. void SetOwnPopup(bool value); /// Get the popup for the column. /// The popup for the column. GuiMenu* GetPopup(); /// Set the popup for the column. /// The popup for the column. void SetPopup(GuiMenu* value); /// Get the filter for the column. /// The filter for the column. Ptr GetFilter(); /// Set the filter for the column. /// The filter. void SetFilter(Ptr value); /// Get the sorter for the column. /// The sorter for the column. Ptr GetSorter(); /// Set the sorter for the column. /// The sorter. void SetSorter(Ptr value); /// Get the visualizer factory for the column. /// The the visualizer factory for the column. Ptr GetVisualizerFactory(); /// Set the visualizer factory for the column. /// The visualizer factory. void SetVisualizerFactory(Ptr value); /// Get the editor factory for the column. /// The the editor factory for the column. Ptr GetEditorFactory(); /// Set the editor factory for the column. /// The editor factory. void SetEditorFactory(Ptr value); /// Get the text value from an item. /// The text value. /// The row index of the item. WString GetCellText(vint row); /// Get the cell value from an item. /// The cell value. /// The row index of the item. description::Value GetCellValue(vint row); /// Set the cell value to an item. /// The row index of the item. /// The value property name. void SetCellValue(vint row, description::Value value); /// Get the text property name to get the cell text from an item. /// The text property name. ItemProperty GetTextProperty(); /// Set the text property name to get the cell text from an item. /// The text property name. void SetTextProperty(const ItemProperty& value); /// Get the value property name to get the cell value from an item. /// The value property name. WritableItemProperty GetValueProperty(); /// Set the value property name to get the cell value from an item. /// The value property name. void SetValueProperty(const WritableItemProperty& value); }; class DataColumns : public collections::ObservableListBase> { friend class DataColumn; protected: DataProvider* dataProvider = nullptr; bool affectItemFlag = true; void NotifyColumnUpdated(vint index, bool affectItem); void NotifyUpdateInternal(vint start, vint count, vint newCount)override; bool QueryInsert(vint index, const Ptr& value)override; void AfterInsert(vint index, const Ptr& value)override; void BeforeRemove(vint index, const Ptr& value)override; public: DataColumns(DataProvider* _dataProvider); ~DataColumns(); }; /*********************************************************************** DataProvider ***********************************************************************/ class DataProvider : public virtual ItemProviderBase , public virtual IListViewItemView , public virtual ListViewColumnItemArranger::IColumnItemView , public virtual IDataGridView , public virtual IDataProcessorCallback , public virtual IListViewItemProvider , public Description { friend class DataColumn; friend class DataColumns; friend class controls::GuiBindableDataGrid; protected: ListViewDataColumns dataColumns; DataColumns columns; ListViewColumnItemArranger::IColumnItemViewCallback* columnItemViewCallback = nullptr; Ptr itemSource; Ptr itemChangedEventHandler; Ptr additionalFilter; Ptr currentFilter; Ptr currentSorter; collections::List virtualRowToSourceRow; void NotifyAllItemsUpdate()override; void NotifyAllColumnsUpdate()override; GuiListControl::IItemProvider* GetItemProvider()override; void OnProcessorChanged()override; void OnItemSourceModified(vint start, vint count, vint newCount); void RebuildFilter(); void ReorderRows(bool invokeCallback); public: ItemProperty> largeImageProperty; ItemProperty> smallImageProperty; public: /// Create a data provider. DataProvider(); ~DataProvider(); ListViewDataColumns& GetDataColumns(); DataColumns& GetColumns(); Ptr GetItemSource(); void SetItemSource(Ptr _itemSource); Ptr GetAdditionalFilter(); void SetAdditionalFilter(Ptr value); // ===================== GuiListControl::IItemProvider ===================== vint Count()override; WString GetTextValue(vint itemIndex)override; description::Value GetBindingValue(vint itemIndex)override; IDescriptable* RequestView(const WString& identifier)override; // ===================== list::IListViewItemProvider ===================== Ptr GetSmallImage(vint itemIndex)override; Ptr GetLargeImage(vint itemIndex)override; WString GetText(vint itemIndex)override; WString GetSubItem(vint itemIndex, vint index)override; vint GetDataColumnCount()override; vint GetDataColumn(vint index)override; vint GetColumnCount()override; WString GetColumnText(vint index)override; // ===================== list::ListViewColumnItemArranger::IColumnItemView ===================== bool AttachCallback(ListViewColumnItemArranger::IColumnItemViewCallback* value)override; bool DetachCallback(ListViewColumnItemArranger::IColumnItemViewCallback* value)override; vint GetColumnSize(vint index)override; void SetColumnSize(vint index, vint value)override; GuiMenu* GetDropdownPopup(vint index)override; ColumnSortingState GetSortingState(vint index)override; // ===================== list::IDataGridView ===================== bool IsColumnSortable(vint column)override; void SortByColumn(vint column, bool ascending)override; vint GetSortedColumn()override; bool IsSortOrderAscending()override; vint GetCellSpan(vint row, vint column)override; IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row, vint column)override; IDataEditorFactory* GetCellDataEditorFactory(vint row, vint column)override; description::Value GetBindingCellValue(vint row, vint column)override; void SetBindingCellValue(vint row, vint column, const description::Value& value)override; }; } /*********************************************************************** GuiBindableDataGrid ***********************************************************************/ /// A bindable Data grid control. class GuiBindableDataGrid : public GuiVirtualDataGrid, public Description { protected: list::DataProvider* dataProvider = nullptr; public: /// Create a bindable Data grid control. /// The theme name for retriving a default control template. GuiBindableDataGrid(theme::ThemeName themeName); ~GuiBindableDataGrid(); /// Get all data columns indices in columns. /// All data columns indices in columns. list::ListViewDataColumns& GetDataColumns(); /// Get all columns. /// All columns. list::DataColumns& GetColumns(); /// Get the item source. /// The item source. Ptr GetItemSource(); /// Set the item source. /// The item source. Null is acceptable if you want to clear all data. void SetItemSource(Ptr _itemSource); /// Get the additional filter. /// The additional filter. Ptr GetAdditionalFilter(); /// Set the additional filter. This filter will be composed with filters of all column to be the final filter. /// The additional filter. void SetAdditionalFilter(Ptr value); /// Large image property name changed event. compositions::GuiNotifyEvent LargeImagePropertyChanged; /// Small image property name changed event. compositions::GuiNotifyEvent SmallImagePropertyChanged; /// Get the large image property name to get the large image from an item. /// The large image property name. ItemProperty> GetLargeImageProperty(); /// Set the large image property name to get the large image from an item. /// The large image property name. void SetLargeImageProperty(const ItemProperty>& value); /// Get the small image property name to get the small image from an item. /// The small image property name. ItemProperty> GetSmallImageProperty(); /// Set the small image property name to get the small image from an item. /// The small image property name. void SetSmallImageProperty(const ItemProperty>& value); /// Get the selected cell. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. description::Value GetSelectedRowValue(); /// Get the selected cell. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. description::Value GetSelectedCellValue(); }; } } } #endif /*********************************************************************** .\CONTROLS\TOOLSTRIPPACKAGE\GUIRIBBONIMPL.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIRIBBONIMPL #define VCZH_PRESENTATION_CONTROLS_GUIRIBBONIMPL namespace vl { namespace presentation { namespace controls { class GuiBindableRibbonGalleryList; /*********************************************************************** GalleryItemArranger ***********************************************************************/ namespace ribbon_impl { class GalleryItemArranger : public list::RangedItemArrangerBase, public Description { private: vint pim_itemWidth = 0; bool blockScrollUpdate = true; protected: GuiBindableRibbonGalleryList* owner; vint itemWidth = 1; vint firstIndex = 0; void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex)override; void PlaceItem(bool forMoving, bool newCreatedStyle, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent)override; bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds)override; bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex)override; void InvalidateItemSizeCache()override; Size OnCalculateTotalSize()override; public: GalleryItemArranger(GuiBindableRibbonGalleryList* _owner); ~GalleryItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; GuiListControl::EnsureItemVisibleResult EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; void ScrollUp(); void ScrollDown(); void UnblockScrollUpdate(); }; class GalleryResponsiveLayout : public compositions::GuiResponsiveCompositionBase, public Description { protected: vint minCount = 0; vint maxCount = 0; Size sizeOffset; vint itemCount = 0; vint itemWidth = 1; void UpdateMinSize(); public: GalleryResponsiveLayout(); ~GalleryResponsiveLayout(); vint GetMinCount(); vint GetMaxCount(); vint GetItemWidth(); Size GetSizeOffset(); vint GetVisibleItemCount(); void SetMinCount(vint value); void SetMaxCount(vint value); void SetItemWidth(vint value); void SetSizeOffset(Size value); vint GetLevelCount()override; vint GetCurrentLevel()override; bool LevelDown()override; bool LevelUp()override; }; } } } } #endif /*********************************************************************** .\CONTROLS\TOOLSTRIPPACKAGE\GUITOOLSTRIPCOMMAND.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITOOLSTRIPCOMMAND #define VCZH_PRESENTATION_CONTROLS_GUITOOLSTRIPCOMMAND namespace vl { namespace presentation { namespace compositions { class IGuiShortcutKeyItem; } namespace controls { /// A command for toolstrip controls. class GuiToolstripCommand : public GuiComponent, public Description { public: class ShortcutBuilder : public Object { public: WString text; bool ctrl; bool shift; bool alt; VKEY key; }; protected: Ptr image; Ptr largeImage; WString text; compositions::IGuiShortcutKeyItem* shortcutKeyItem = nullptr; bool enabled = true; bool selected = false; Ptr shortcutKeyItemExecutedHandler; Ptr shortcutBuilder; GuiInstanceRootObject* attachedRootObject = nullptr; Ptr renderTargetChangedHandler; GuiControlHost* shortcutOwner = nullptr; void OnShortcutKeyItemExecuted(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnRenderTargetChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void InvokeDescriptionChanged(); void ReplaceShortcut(compositions::IGuiShortcutKeyItem* value, Ptr builder); void BuildShortcut(const WString& builderText); void UpdateShortcutOwner(); public: /// Create the command. GuiToolstripCommand(); ~GuiToolstripCommand(); void Attach(GuiInstanceRootObject* rootObject)override; void Detach(GuiInstanceRootObject* rootObject)override; /// Executed event. compositions::GuiNotifyEvent Executed; /// Description changed event, raised when any description property is modified. compositions::GuiNotifyEvent DescriptionChanged; /// Get the large image for this command. /// The large image for this command. Ptr GetLargeImage(); /// Set the large image for this command. /// The large image for this command. void SetLargeImage(Ptr value); /// Get the image for this command. /// The image for this command. Ptr GetImage(); /// Set the image for this command. /// The image for this command. void SetImage(Ptr value); /// Get the text for this command. /// The text for this command. const WString& GetText(); /// Set the text for this command. /// The text for this command. void SetText(const WString& value); /// Get the shortcut key item for this command. /// The shortcut key item for this command. compositions::IGuiShortcutKeyItem* GetShortcut(); /// Set the shortcut key item for this command. /// The shortcut key item for this command. void SetShortcut(compositions::IGuiShortcutKeyItem* value); /// Get the shortcut builder for this command. /// The shortcut builder for this command. WString GetShortcutBuilder(); /// Set the shortcut builder for this command. When the command is attached to a window as a component without a shortcut, the command will try to convert the shortcut builder to a shortcut key item. /// The shortcut builder for this command. void SetShortcutBuilder(const WString& value); /// Get the enablility for this command. /// The enablility for this command. bool GetEnabled(); /// Set the enablility for this command. /// The enablility for this command. void SetEnabled(bool value); /// Get the selection for this command. /// The selection for this command. bool GetSelected(); /// Set the selection for this command. /// The selection for this command. void SetSelected(bool value); }; } } } #endif /*********************************************************************** .\CONTROLS\TOOLSTRIPPACKAGE\GUITOOLSTRIPMENU.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUITOOLSTRIPMENU #define VCZH_PRESENTATION_CONTROLS_GUITOOLSTRIPMENU namespace vl { namespace presentation { namespace controls { /*********************************************************************** Toolstrip Item Collection ***********************************************************************/ /// IToolstripUpdateLayout is a required service for all menu item container. class IToolstripUpdateLayout : public IDescriptable { public: virtual void UpdateLayout() = 0; }; /// IToolstripUpdateLayout is a required service for a menu item which want to force the container to redo layout. class IToolstripUpdateLayoutInvoker : public IDescriptable { public: /// The identifier for this service. static const wchar_t* const Identifier; virtual void SetCallback(IToolstripUpdateLayout* callback) = 0; }; /// Toolstrip item collection. class GuiToolstripCollectionBase : public collections::ObservableListBase { public: protected: IToolstripUpdateLayout * contentCallback; void InvokeUpdateLayout(); bool QueryInsert(vint index, GuiControl* const& child)override; void BeforeRemove(vint index, GuiControl* const& child)override; void AfterInsert(vint index, GuiControl* const& child)override; void AfterRemove(vint index, vint count)override; public: GuiToolstripCollectionBase(IToolstripUpdateLayout* _contentCallback); ~GuiToolstripCollectionBase(); }; /// Toolstrip item collection. class GuiToolstripCollection : public GuiToolstripCollectionBase { using EventHandlerList = collections::List>; protected: compositions::GuiStackComposition* stackComposition; EventHandlerList eventHandlers; void UpdateItemVisibility(vint index, GuiControl* child); void OnItemVisibleChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void BeforeRemove(vint index, GuiControl* const& child)override; void AfterInsert(vint index, GuiControl* const& child)override; void AfterRemove(vint index, vint count)override; public: GuiToolstripCollection(IToolstripUpdateLayout* _contentCallback, compositions::GuiStackComposition* _stackComposition); ~GuiToolstripCollection(); }; /*********************************************************************** Toolstrip Container ***********************************************************************/ /// Toolstrip menu. class GuiToolstripMenu : public GuiMenu, protected IToolstripUpdateLayout, Description { protected: compositions::GuiSharedSizeRootComposition* sharedSizeRootComposition; compositions::GuiStackComposition* stackComposition; Ptr toolstripItems; void UpdateLayout()override; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. /// The owner menu item of the parent menu. GuiToolstripMenu(theme::ThemeName themeName, GuiControl* _owner); ~GuiToolstripMenu(); /// Get all managed child controls ordered by their positions. /// All managed child controls. collections::ObservableListBase& GetToolstripItems(); }; /// Toolstrip menu bar. class GuiToolstripMenuBar : public GuiMenuBar, public Description { protected: compositions::GuiStackComposition* stackComposition; Ptr toolstripItems; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiToolstripMenuBar(theme::ThemeName themeName); ~GuiToolstripMenuBar(); /// Get all managed child controls ordered by their positions. /// All managed child controls. collections::ObservableListBase& GetToolstripItems(); }; /// Toolstrip tool bar. class GuiToolstripToolBar : public GuiControl, public Description { protected: compositions::GuiStackComposition* stackComposition; Ptr toolstripItems; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiToolstripToolBar(theme::ThemeName themeName); ~GuiToolstripToolBar(); /// Get all managed child controls ordered by their positions. /// All managed child controls. collections::ObservableListBase& GetToolstripItems(); }; /*********************************************************************** Toolstrip Component ***********************************************************************/ /// Toolstrip button that can connect with a . class GuiToolstripButton : public GuiMenuButton, protected IToolstripUpdateLayoutInvoker, public Description { protected: GuiToolstripCommand* command; IToolstripUpdateLayout* callback = nullptr; Ptr descriptionChangedHandler; void SetCallback(IToolstripUpdateLayout* _callback)override; void OnActiveAlt()override; void UpdateCommandContent(); void OnLayoutAwaredPropertyChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnCommandDescriptionChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiToolstripButton(theme::ThemeName themeName); ~GuiToolstripButton(); /// Get the attached . /// The attached toolstrip command. GuiToolstripCommand* GetCommand(); /// Detach from the previous and attach to a new one. If the command is null, this function only do detaching. /// The new toolstrip command. void SetCommand(GuiToolstripCommand* value); /// Get the toolstrip sub menu. If the sub menu is not created, it returns null. /// The toolstrip sub menu. GuiToolstripMenu* GetToolstripSubMenu(); /// Get the toolstrip sub menu. If the sub menu is not created, it returns null. /// The toolstrip sub menu. GuiToolstripMenu* EnsureToolstripSubMenu(); /// Create the toolstrip sub menu if necessary. The created toolstrip sub menu is owned by this menu button. /// The style controller for the toolstrip sub menu. Set to null to use the default control template. void CreateToolstripSubMenu(TemplateProperty subMenuTemplate); IDescriptable* QueryService(const WString& identifier)override; }; /*********************************************************************** Toolstrip Group ***********************************************************************/ class GuiToolstripNestedContainer : public GuiControl, protected IToolstripUpdateLayout, protected IToolstripUpdateLayoutInvoker { protected: IToolstripUpdateLayout* callback = nullptr; void UpdateLayout()override; void SetCallback(IToolstripUpdateLayout* _callback)override; public: GuiToolstripNestedContainer(theme::ThemeName themeName); ~GuiToolstripNestedContainer(); IDescriptable* QueryService(const WString& identifier)override; }; /// A toolstrip item, which is also a toolstrip item container, automatically maintaining splitters between items. class GuiToolstripGroupContainer : public GuiToolstripNestedContainer, public Description { protected: class GroupCollection : public GuiToolstripCollectionBase { protected: GuiToolstripGroupContainer* container; ControlTemplatePropertyType splitterTemplate; void BeforeRemove(vint index, GuiControl* const& child)override; void AfterInsert(vint index, GuiControl* const& child)override; void AfterRemove(vint index, vint count)override; public: GroupCollection(GuiToolstripGroupContainer* _container); ~GroupCollection(); ControlTemplatePropertyType GetSplitterTemplate(); void SetSplitterTemplate(const ControlTemplatePropertyType& value); void RebuildSplitters(); }; protected: compositions::GuiStackComposition* stackComposition; theme::ThemeName splitterThemeName; Ptr groupCollection; void OnParentLineChanged()override; public: GuiToolstripGroupContainer(theme::ThemeName themeName); ~GuiToolstripGroupContainer(); ControlTemplatePropertyType GetSplitterTemplate(); void SetSplitterTemplate(const ControlTemplatePropertyType& value); /// Get all managed child controls ordered by their positions. /// All managed child controls. collections::ObservableListBase& GetToolstripItems(); }; /// A toolstrip item, which is also a toolstrip item container. class GuiToolstripGroup : public GuiToolstripNestedContainer, public Description { protected: compositions::GuiStackComposition* stackComposition; Ptr toolstripItems; void OnParentLineChanged()override; public: GuiToolstripGroup(theme::ThemeName themeName); ~GuiToolstripGroup(); /// Get all managed child controls ordered by their positions. /// All managed child controls. collections::ObservableListBase& GetToolstripItems(); }; } } namespace collections { namespace randomaccess_internal { template<> struct RandomAccessable { static const bool CanRead = true; static const bool CanResize = false; }; } } } #endif /*********************************************************************** .\CONTROLS\TOOLSTRIPPACKAGE\GUIRIBBONCONTROLS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIRIBBONCONTROLS #define VCZH_PRESENTATION_CONTROLS_GUIRIBBONCONTROLS namespace vl { namespace presentation { namespace controls { /*********************************************************************** Ribbon Containers ***********************************************************************/ class GuiRibbonTabPage; class GuiRibbonGroup; /// Ribbon tab control, for displaying ribbon tab pages. class GuiRibbonTab : public GuiTab, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonTabTemplate, GuiTab) protected: compositions::GuiBoundsComposition* beforeHeaders = nullptr; compositions::GuiBoundsComposition* afterHeaders = nullptr; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiRibbonTab(theme::ThemeName themeName); ~GuiRibbonTab(); /// Get the composition representing the space before tabs. /// The composition representing the space before tabs. compositions::GuiGraphicsComposition* GetBeforeHeaders(); /// Get the composition representing the space after tabs. /// The composition representing the space after tabs. compositions::GuiGraphicsComposition* GetAfterHeaders(); }; class GuiRibbonGroupCollection : public collections::ObservableListBase { protected: GuiRibbonTabPage* tabPage = nullptr; bool QueryInsert(vint index, GuiRibbonGroup* const& value)override; void AfterInsert(vint index, GuiRibbonGroup* const& value)override; void AfterRemove(vint index, vint count)override; public: GuiRibbonGroupCollection(GuiRibbonTabPage* _tabPage); ~GuiRibbonGroupCollection(); }; /// Ribbon tab page control, adding to the Pages property of a . class GuiRibbonTabPage : public GuiTabPage, public AggregatableDescription { friend class GuiRibbonGroupCollection; protected: bool highlighted = false; GuiRibbonGroupCollection groups; compositions::GuiResponsiveStackComposition* responsiveStack = nullptr; compositions::GuiResponsiveContainerComposition* responsiveContainer = nullptr; compositions::GuiStackComposition* stack = nullptr; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiRibbonTabPage(theme::ThemeName themeName); ~GuiRibbonTabPage(); /// Highlighted changed event. compositions::GuiNotifyEvent HighlightedChanged; /// Test if this is a highlighted tab page. /// Returns true if this is a highlighted tab page. bool GetHighlighted(); /// Set if this is a highlighted tab page. /// Set to true to highlight the tab page. void SetHighlighted(bool value); /// Get the collection of ribbon groups. /// The collection of ribbon groups. collections::ObservableListBase& GetGroups(); }; class GuiRibbonGroupItemCollection : public collections::ObservableListBase { protected: GuiRibbonGroup* group = nullptr; bool QueryInsert(vint index, GuiControl* const& value)override; void AfterInsert(vint index, GuiControl* const& value)override; void AfterRemove(vint index, vint count)override; public: GuiRibbonGroupItemCollection(GuiRibbonGroup* _group); ~GuiRibbonGroupItemCollection(); }; /// Ribbon group control, adding to the Groups property of a . class GuiRibbonGroup : public GuiControl, protected compositions::GuiAltActionHostBase, public Description { friend class GuiRibbonGroupItemCollection; GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonGroupTemplate, GuiControl) protected: class CommandExecutor : public Object, public IRibbonGroupCommandExecutor { protected: GuiRibbonGroup* group; public: CommandExecutor(GuiRibbonGroup* _group); ~CommandExecutor(); void NotifyExpandButtonClicked()override; }; bool expandable = false; Ptr largeImage; GuiRibbonGroupItemCollection items; compositions::GuiResponsiveStackComposition* responsiveStack = nullptr; compositions::GuiStackComposition* stack = nullptr; Ptr commandExecutor; compositions::GuiResponsiveViewComposition* responsiveView = nullptr; compositions::GuiResponsiveFixedComposition* responsiveFixedButton = nullptr; GuiToolstripButton* dropdownButton = nullptr; GuiMenu* dropdownMenu = nullptr; bool IsAltAvailable()override; compositions::IGuiAltActionHost* GetActivatingAltHost()override; void OnBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBeforeSwitchingView(compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); void OnBeforeSubMenuOpening(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiRibbonGroup(theme::ThemeName themeName); ~GuiRibbonGroup(); /// Expandable changed event. compositions::GuiNotifyEvent ExpandableChanged; /// Expand button clicked event. compositions::GuiNotifyEvent ExpandButtonClicked; /// Large image changed event. compositions::GuiNotifyEvent LargeImageChanged; /// Test if this group is expandable. An expandable group will display an extra small button, which raises . /// Returns true if this group is expandable. bool GetExpandable(); /// Set if this group is expandable. /// Set to true to make this group is expandable. void SetExpandable(bool value); /// Get the large image for the collapsed ribbon group. /// The large image for the collapsed ribbon group. Ptr GetLargeImage(); /// Set the large image for the collapsed ribbon group. /// The large image for the collapsed ribbon group. void SetLargeImage(Ptr value); /// Get the collection of controls in this group. /// The collection of controls. collections::ObservableListBase& GetItems(); }; /*********************************************************************** Ribbon Buttons ***********************************************************************/ /// Auto resizable ribbon icon label. class GuiRibbonIconLabel : public GuiControl, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonIconLabelTemplate, GuiControl) protected: Ptr image; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiRibbonIconLabel(theme::ThemeName themeName); ~GuiRibbonIconLabel(); /// Image changed event. compositions::GuiNotifyEvent ImageChanged; /// Get the image for the menu button. /// The image for the menu button. Ptr GetImage(); /// Set the image for the menu button. /// The image for the menu button. void SetImage(Ptr value); }; /// Represents the size of a ribbon button in a control. enum class RibbonButtonSize { /// Large icon with text. Large = 0, /// Small icon with text. Small = 1, /// Small icon only. Icon = 2, }; class GuiRibbonButtons; class GuiRibbonButtonsItemCollection : public collections::ObservableListBase { protected: GuiRibbonButtons* buttons = nullptr; bool QueryInsert(vint index, GuiControl* const& value)override; void AfterInsert(vint index, GuiControl* const& value)override; void BeforeRemove(vint index, GuiControl* const& value)override; public: GuiRibbonButtonsItemCollection(GuiRibbonButtons* _buttons); ~GuiRibbonButtonsItemCollection(); }; /// Auto resizable ribbon buttons. class GuiRibbonButtons : public GuiControl, public Description { friend class GuiRibbonButtonsItemCollection; GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonButtonsTemplate, GuiControl) protected: RibbonButtonSize minSize; RibbonButtonSize maxSize; compositions::GuiResponsiveViewComposition* responsiveView = nullptr; compositions::GuiResponsiveFixedComposition* views[3] = { nullptr,nullptr,nullptr }; GuiRibbonButtonsItemCollection buttons; void OnBeforeSwitchingView(compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); void SetButtonThemeName(compositions::GuiResponsiveCompositionBase* fixed, GuiControl* button); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. /// Max allowed size. /// Min allowed size. GuiRibbonButtons(theme::ThemeName themeName, RibbonButtonSize _maxSize, RibbonButtonSize _minSize); ~GuiRibbonButtons(); /// Get the collection of buttons. is expected. /// The collection of buttons. collections::ObservableListBase& GetButtons(); }; /*********************************************************************** Ribbon Toolstrips ***********************************************************************/ class GuiRibbonToolstrips; class GuiRibbonToolstripsGroupCollection : public collections::ObservableListBase { protected: GuiRibbonToolstrips* toolstrips = nullptr; bool QueryInsert(vint index, GuiToolstripGroup* const& value)override; void AfterInsert(vint index, GuiToolstripGroup* const& value)override; void AfterRemove(vint index, vint count)override; public: GuiRibbonToolstripsGroupCollection(GuiRibbonToolstrips* _toolstrips); ~GuiRibbonToolstripsGroupCollection(); }; /// Auto resizable ribbon toolstrips. class GuiRibbonToolstrips : public GuiControl, public Description { friend class GuiRibbonToolstripsGroupCollection; GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonToolstripsTemplate, GuiControl) protected: compositions::GuiResponsiveViewComposition* responsiveView = nullptr; GuiToolstripToolBar* toolbars[5] = { nullptr,nullptr,nullptr,nullptr,nullptr }; GuiToolstripGroupContainer* longContainers[2] = { nullptr,nullptr }; GuiToolstripGroupContainer* shortContainers[3] = { nullptr,nullptr,nullptr }; compositions::GuiResponsiveFixedComposition* views[2] = { nullptr,nullptr }; GuiRibbonToolstripsGroupCollection groups; void OnBeforeSwitchingView(compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); void RearrangeToolstripGroups(vint viewIndex = -1); public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiRibbonToolstrips(theme::ThemeName themeName); ~GuiRibbonToolstrips(); /// Get the collection of toolstrip groups. will decide the order of these toolstrip groups. /// The collection of toolstrip groups. collections::ObservableListBase& GetGroups(); }; /*********************************************************************** Ribbon Gallery ***********************************************************************/ /// Ribbon gallery, with scroll up, scroll down, dropdown buttons. class GuiRibbonGallery : public GuiControl, public Description { using ItemStyle = templates::GuiListItemTemplate; using ItemStyleProperty = TemplateProperty; GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonGalleryTemplate, GuiControl) protected: class CommandExecutor : public Object, public IRibbonGalleryCommandExecutor { protected: GuiRibbonGallery* gallery; public: CommandExecutor(GuiRibbonGallery* _gallery); ~CommandExecutor(); void NotifyScrollUp()override; void NotifyScrollDown()override; void NotifyDropdown()override; }; bool scrollUpEnabled = true; bool scrollDownEnabled = true; Ptr commandExecutor; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiRibbonGallery(theme::ThemeName themeName); ~GuiRibbonGallery(); /// Scroll up enabled changed event. compositions::GuiNotifyEvent ScrollUpEnabledChanged; /// Scroll down enabled changed event. compositions::GuiNotifyEvent ScrollDownEnabledChanged; /// Scroll up button clicked event. compositions::GuiNotifyEvent RequestedScrollUp; /// Scroll down button clicked event. compositions::GuiNotifyEvent RequestedScrollDown; /// Dropdown button clicked event. compositions::GuiNotifyEvent RequestedDropdown; /// Test if the scroll up button is enabled. /// Returns true if the scroll up button is enabled. bool GetScrollUpEnabled(); /// Set if the scroll up button is enabled. /// Set to true to enable the scroll up button. void SetScrollUpEnabled(bool value); /// Test if the scroll down button is enabled. /// Returns true if the scroll down button is enabled. bool GetScrollDownEnabled(); /// Set if the scroll down button is enabled. /// Set to true to enable the scroll down button. void SetScrollDownEnabled(bool value); }; /// Resizable ribbon toolstrip menu with a space above of all menu items to display extra content. class GuiRibbonToolstripMenu : public GuiToolstripMenu, public Description { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonToolstripMenuTemplate, GuiToolstripMenu) protected: compositions::GuiBoundsComposition* contentComposition; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. /// The owner menu item of the parent menu. GuiRibbonToolstripMenu(theme::ThemeName themeName, GuiControl* owner); ~GuiRibbonToolstripMenu(); /// Get the composition representing the space above of menu items. /// The composition representing the space above of menu items. compositions::GuiGraphicsComposition* GetContentComposition(); }; } } } #endif /*********************************************************************** .\CONTROLS\TOOLSTRIPPACKAGE\GUIRIBBONGALLERYLIST.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUIRIBBONGALLERYLIST #define VCZH_PRESENTATION_CONTROLS_GUIRIBBONGALLERYLIST namespace vl { namespace presentation { namespace controls { /*********************************************************************** Ribbon Gallery List ***********************************************************************/ /// Represents the position of an item in the gallery list. struct GalleryPos { /// Group index. vint group; /// Item index. vint item; GalleryPos() :group(-1), item(-1) { } GalleryPos(vint _group, vint _item) :group(_group), item(_item) { } inline vint Compare(const GalleryPos& value)const { vint result; if ((result = group - value.group) != 0) return result; if ((result = item - value.item) != 0) return result; return 0; } GUI_DEFINE_COMPARE_OPERATORS(GalleryPos) }; namespace list { class GroupedDataSource; /// A gallery group. class GalleryGroup : public Description { friend class GroupedDataSource; using IValueList = reflection::description::IValueList; protected: Ptr eventHandler; WString name; Ptr itemValues; public: GalleryGroup(); ~GalleryGroup(); /// Get the title of this group. /// The title of this group. WString GetName(); /// Get the all items of this group, could be null. /// All items of this group. Ptr GetItemValues(); }; class GroupedDataSource : public Description { using IValueEnumerable = reflection::description::IValueEnumerable; using IValueList = reflection::description::IValueList; using IValueObservableList = reflection::description::IValueObservableList; using GalleryItemList = collections::ObservableList; using GalleryGroupList = collections::ObservableList>; protected: compositions::GuiGraphicsComposition* associatedComposition; Ptr itemSource; ItemProperty titleProperty; ItemProperty> childrenProperty; GalleryItemList joinedItemSource; GalleryGroupList groupedItemSource; collections::List cachedGroupItemCounts; Ptr groupChangedHandler; bool ignoreGroupChanged = false; void RebuildItemSource(); Ptr GetChildren(Ptr children); void AttachGroupChanged(Ptr group, vint index); void OnGroupChanged(vint start, vint oldCount, vint newCount); void OnGroupItemChanged(vint index, vint start, vint oldCount, vint newCount); vint GetCountBeforeGroup(vint index); void InsertGroupToJoined(vint index); void RemoveGroupFromJoined(vint index); public: GroupedDataSource(compositions::GuiGraphicsComposition* _associatedComposition); ~GroupedDataSource(); /// Group enabled event. compositions::GuiNotifyEvent GroupEnabledChanged; /// Group title property changed event. compositions::GuiNotifyEvent GroupTitlePropertyChanged; /// Group children property changed event. compositions::GuiNotifyEvent GroupChildrenPropertyChanged; /// Get the item source. /// The item source. Ptr GetItemSource(); /// Set the item source. /// The item source. Null is acceptable if you want to clear all data. void SetItemSource(Ptr value); /// Test if grouping is enabled. Enabled means there is really both GroupTitleProperty and GroupChildrenProperty is not empty. /// Returns true if grouping is enabled. bool GetGroupEnabled(); /// Get the group title property. /// The group title property. ItemProperty GetGroupTitleProperty(); /// Get the group title property. /// The group title property. void SetGroupTitleProperty(const ItemProperty& value); /// Get the group children property. /// The group children property. ItemProperty> GetGroupChildrenProperty(); /// Get the group children property. /// The children title property. void SetGroupChildrenProperty(const ItemProperty>& value); /// Get all groups. /// All groups. const GalleryGroupList& GetGroups(); }; } namespace ribbon_impl { class GalleryItemArranger; class GalleryResponsiveLayout; } /// Auto resizable ribbon gallyer list. class GuiBindableRibbonGalleryList : public GuiRibbonGallery, public list::GroupedDataSource, private IGuiMenuDropdownProvider, public Description { friend class ribbon_impl::GalleryItemArranger; using IValueEnumerable = reflection::description::IValueEnumerable; using IValueObservableList = reflection::description::IValueObservableList; using ItemStyleProperty = TemplateProperty; GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonGalleryListTemplate, GuiRibbonGallery) protected: ItemStyleProperty itemStyle; GuiBindableTextList* itemList; GuiRibbonToolstripMenu* subMenu; vint visibleItemCount = 1; bool skipItemAppliedEvent = false; ribbon_impl::GalleryItemArranger* itemListArranger; ribbon_impl::GalleryResponsiveLayout* layout; GuiScrollContainer* groupContainer; compositions::GuiRepeatStackComposition* groupStack; void UpdateLayoutSizeOffset(); void OnItemListSelectionChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnItemListItemMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); void OnItemListItemMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); void OnBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnRequestedDropdown(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnRequestedScrollUp(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnRequestedScrollDown(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void MenuResetGroupTemplate(); GuiControl* MenuGetGroupHeader(vint groupIndex); compositions::GuiRepeatFlowComposition* MenuGetGroupFlow(vint groupIndex); GuiSelectableButton* MenuGetGroupItemBackground(vint groupIndex, vint itemIndex); void StartPreview(vint index); void StopPreview(vint index); private: GuiMenu* ProvideDropdownMenu()override; public: /// Create a control with a specified default theme. /// The theme name for retriving a default control template. GuiBindableRibbonGalleryList(theme::ThemeName themeName); ~GuiBindableRibbonGalleryList(); /// Item template changed event. compositions::GuiNotifyEvent ItemTemplateChanged; /// Selection changed event. compositions::GuiNotifyEvent SelectionChanged; /// Preview started event. compositions::GuiItemNotifyEvent PreviewStarted; /// Preview stopped event. compositions::GuiItemNotifyEvent PreviewStopped; /// Item applied event. compositions::GuiItemNotifyEvent ItemApplied; /// Get the item style provider. /// The item style provider. ItemStyleProperty GetItemTemplate(); /// Set the item style provider /// The new item style provider void SetItemTemplate(ItemStyleProperty value); /// Convert an item index to a gallery item position. /// The gallery item position. /// The item index. GalleryPos IndexToGalleryPos(vint index); /// Convert a gallery item position to an item index. /// The item index. /// The gallery item position. vint GalleryPosToIndex(GalleryPos pos); /// Get the minimum number of items should be displayed. /// The minimum number of items should be displayed. vint GetMinCount(); /// Set the minimum number of items should be displayed. /// The minimum number of items should be displayed. void SetMinCount(vint value); /// Get the maximum number of items should be displayed. /// The maximum number of items should be displayed. vint GetMaxCount(); /// Set the maximum number of items should be displayed. /// The maximum number of items should be displayed. void SetMaxCount(vint value); /// Get the selected item index. /// The index of the selected item. If there are multiple selected items, or there is no selected item, -1 will be returned. vint GetSelectedIndex(); /// Get the selected item. /// Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned. description::Value GetSelectedItem(); /// Select an item with event raised. /// The index of the item to select. Set to -1 to clear the selection. void ApplyItem(vint index); /// Select an item without event raised. /// The index of the item to select. Set to -1 to clear the selection. void SelectItem(vint index); /// Get the minimum items visible in the drop down menu. /// The minimum items visible in the drop down menu. vint GetVisibleItemCount(); /// Set minimum items visible in the drop down menu. /// The minimum items visible in the drop down menu. void SetVisibleItemCount(vint value); /// Get the dropdown menu. /// The dropdown menu. GuiToolstripMenu* GetSubMenu(); IDescriptable* QueryService(const WString& identifier)override; }; } } } #endif /*********************************************************************** .\CONTROLS\INCLUDEALL.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Application Framework Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_INCLUDEALL #define VCZH_PRESENTATION_CONTROLS_INCLUDEALL #endif /*********************************************************************** .\RESOURCES\GUIDOCUMENTCLIPBOARD.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Resource Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_RESOURCES_GUIDOCUMENTCLIPBOARD #define VCZH_PRESENTATION_RESOURCES_GUIDOCUMENTCLIPBOARD namespace vl { namespace presentation { extern void ModifyDocumentForClipboard(Ptr model); extern Ptr LoadDocumentFromClipboardStream(stream::IStream& clipboardStream); extern void SaveDocumentToClipboardStream(Ptr model, stream::IStream& clipboardStream); extern void SaveDocumentToRtf(Ptr model, AString& rtf); extern void SaveDocumentToRtfStream(Ptr model, stream::IStream& rtfStream); extern void SaveDocumentToHtmlUtf8(Ptr model, AString& header, AString& content, AString& footer); extern void SaveDocumentToHtmlClipboardStream(Ptr model, stream::IStream& clipboardStream); } } #endif /*********************************************************************** .\RESOURCES\GUIDOCUMENTEDITOR.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Resource Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_RESOURCES_GUIDOCUMENTEDITOR #define VCZH_PRESENTATION_RESOURCES_GUIDOCUMENTEDITOR namespace vl { namespace presentation { typedef DocumentModel::RunRange RunRange; typedef DocumentModel::RunRangeMap RunRangeMap; namespace document_editor { extern void GetRunRange(DocumentParagraphRun* run, RunRangeMap& runRanges); extern void LocateStyle(DocumentParagraphRun* run, RunRangeMap& runRanges, vint position, bool frontSide, collections::List& locatedRuns); extern Ptr LocateHyperlink(DocumentParagraphRun* run, RunRangeMap& runRanges, vint row, vint start, vint end); extern Ptr CopyStyle(Ptr style); extern Ptr CopyRun(DocumentRun* run); extern Ptr CopyStyledText(collections::List& styleRuns, const WString& text); extern Ptr CopyRunRecursively(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end, bool deepCopy); extern void CollectStyleName(DocumentParagraphRun* run, collections::List& styleNames); extern void ReplaceStyleName(DocumentParagraphRun* run, const WString& oldStyleName, const WString& newStyleName); extern void RemoveRun(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end); extern void CutRun(DocumentParagraphRun* run, RunRangeMap& runRanges, vint position, Ptr& leftRun, Ptr& rightRun); extern void ClearUnnecessaryRun(DocumentParagraphRun* run, DocumentModel* model); extern void AddStyle(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end, Ptr style); extern void AddHyperlink(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end, const WString& reference, const WString& normalStyleName, const WString& activeStyleName); extern void AddStyleName(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end, const WString& styleName); extern void RemoveHyperlink(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end); extern void RemoveStyleName(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end); extern void ClearStyle(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end); extern Ptr SummarizeStyle(DocumentParagraphRun* run, RunRangeMap& runRanges, DocumentModel* model, vint start, vint end); extern Nullable SummarizeStyleName(DocumentParagraphRun* run, RunRangeMap& runRanges, DocumentModel* model, vint start, vint end); extern void AggregateStyle(Ptr& dst, Ptr src); } } } #endif /*********************************************************************** .\RESOURCES\GUIPARSERMANAGER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Resource Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_RESOURCES_GUIPARSERMANAGER #define VCZH_PRESENTATION_RESOURCES_GUIPARSERMANAGER namespace vl { namespace presentation { /*********************************************************************** Parser ***********************************************************************/ /// Represents a parser. class IGuiGeneralParser : public IDescriptable, public Description { public: }; template class IGuiParser : public IGuiGeneralParser { using ErrorList = collections::List; public: virtual Ptr ParseInternal(const WString& text, ErrorList& errors) = 0; Ptr Parse(GuiResourceLocation location, const WString& text, collections::List& errors) { ErrorList parsingErrors; auto result = ParseInternal(text, parsingErrors); GuiResourceError::Transform(location, errors, parsingErrors); return result; } Ptr Parse(GuiResourceLocation location, const WString& text, glr::ParsingTextPos position, collections::List& errors) { ErrorList parsingErrors; auto result = ParseInternal(text, parsingErrors); GuiResourceError::Transform(location, errors, parsingErrors, position); return result; } Ptr Parse(GuiResourceLocation location, const WString& text, GuiResourceTextPos position, collections::List& errors) { ErrorList parsingErrors; auto result = ParseInternal(text, parsingErrors); GuiResourceError::Transform(location, errors, parsingErrors, position); return result; } }; /*********************************************************************** Parser Manager ***********************************************************************/ /// Parser manager for caching parsing table globally. class IGuiParserManager : public IDescriptable, public Description { public: /// Get a parser. /// The parser. /// The name. virtual Ptr GetParser(const WString& name)=0; /// Set a parser by name. /// Returns true if this operation succeeded. /// The name. /// The parser. virtual bool SetParser(const WString& name, Ptr parser)=0; template Ptr> GetParser(const WString& name); }; /// Get the global object. /// The parser manager. extern IGuiParserManager* GetParserManager(); /*********************************************************************** Parser Manager ***********************************************************************/ template Ptr> IGuiParserManager::GetParser(const WString& name) { return GetParser(name).Cast>(); } } } #endif /*********************************************************************** .\RESOURCES\GUIRESOURCEMANAGER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI Reflection: Instance Loader Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_REFLECTION_GUIRESOURCEMANAGER #define VCZH_PRESENTATION_REFLECTION_GUIRESOURCEMANAGER namespace vl { namespace presentation { /*********************************************************************** IGuiResourceManager ***********************************************************************/ class GuiResourceClassNameRecord : public Object, public Description { public: collections::List classNames; collections::Dictionary> classResources; }; class IGuiResourceManager : public IDescriptable, public Description { public: virtual void SetResource(Ptr resource, GuiResourceError::List& errors, GuiResourceUsage usage = GuiResourceUsage::DataOnly) = 0; virtual Ptr GetResource(const WString& name) = 0; virtual Ptr GetResourceFromClassName(const WString& classFullName) = 0; virtual void UnloadResource(const WString& name) = 0; virtual void LoadResourceOrPending(stream::IStream& resourceStream, GuiResourceError::List& errors, GuiResourceUsage usage = GuiResourceUsage::DataOnly) = 0; virtual void LoadResourceOrPending(stream::IStream& resourceStream, GuiResourceUsage usage = GuiResourceUsage::DataOnly) = 0; virtual void GetPendingResourceNames(collections::List& names) = 0; }; extern IGuiResourceManager* GetResourceManager(); } } #endif /*********************************************************************** .\GACUIREFLECTIONHELPER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI Reflection Helper ***********************************************************************/ #ifndef VCZH_PRESENTATION_GACUIREFLECTIONHELPER #define VCZH_PRESENTATION_GACUIREFLECTIONHELPER namespace vl { namespace presentation { namespace helper_types { struct SiteValue { vint row = 0; vint column = 0; vint rowSpan = 1; vint columnSpan = 1; }; } } namespace reflection { namespace description { /*********************************************************************** Serialization ***********************************************************************/ template<> struct TypedValueSerializerProvider { static presentation::Color GetDefaultValue(); static bool Serialize(const presentation::Color& input, WString& output); static bool Deserialize(const WString& input, presentation::Color& output); static IBoxedValue::CompareResult Compare(const presentation::Color& a, const presentation::Color& b); }; template<> struct TypedValueSerializerProvider { static presentation::DocumentFontSize GetDefaultValue(); static bool Serialize(const presentation::DocumentFontSize& input, WString& output); static bool Deserialize(const WString& input, presentation::DocumentFontSize& output); static IBoxedValue::CompareResult Compare(const presentation::DocumentFontSize& a, const presentation::DocumentFontSize& b); }; template<> struct TypedValueSerializerProvider { static presentation::GlobalStringKey GetDefaultValue(); static bool Serialize(const presentation::GlobalStringKey& input, WString& output); static bool Deserialize(const WString& input, presentation::GlobalStringKey& output); static IBoxedValue::CompareResult Compare(const presentation::GlobalStringKey& a, const presentation::GlobalStringKey& b); }; /*********************************************************************** External Functions ***********************************************************************/ extern Ptr INativeImage_Constructor(const WString& path); extern presentation::INativeCursor* INativeCursor_Constructor1(); extern presentation::INativeCursor* INativeCursor_Constructor2(presentation::INativeCursor::SystemCursorType type); template Ptr Element_Constructor() { return T::Create(); } extern presentation::elements::text::TextLines* GuiColorizedTextElement_GetLines(presentation::elements::GuiColorizedTextElement* thisObject); extern void GuiTableComposition_SetRows(presentation::compositions::GuiTableComposition* thisObject, vint value); extern void GuiTableComposition_SetColumns(presentation::compositions::GuiTableComposition* thisObject, vint value); extern void IGuiAltActionHost_CollectAltActions(presentation::compositions::IGuiAltActionHost* host, collections::List& actions); } } } #endif /*********************************************************************** .\GACUI.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI Header Files and Common Namespaces Global Objects: vl::reflection::description:: GetGlobalTypeManager vl::presentation:: GetParserManager vl::presentation:: GetResourceResolverManager vl::presentation:: GetCurrentController vl::presentation:: GetInstanceLoaderManager vl::presentation::elements:: GetGuiGraphicsResourceManager vl::presentation::controls:: GetApplication vl::presentation::controls:: GetPluginManager vl::presentation::theme:: GetCurrentTheme vl::presentation::windows:: GetDirect2DFactory vl::presentation::windows:: GetDirectWriteFactory vl::presentation::elements_windows_gdi:: GetWindowsGDIResourceManager vl::presentation::elements_windows_gdi:: GetWindowsGDIObjectProvider vl::presentation::elements_windows_d2d:: GetWindowsDirect2DResourceManager vl::presentation::elements_windows_d2d:: GetWindowsDirect2DObjectProvider ***********************************************************************/ #ifndef VCZH_PRESENTATION_GACUI #define VCZH_PRESENTATION_GACUI #ifdef GAC_HEADER_USE_NAMESPACE using namespace vl; using namespace vl::presentation; using namespace vl::presentation::elements; using namespace vl::presentation::compositions; using namespace vl::presentation::controls; using namespace vl::presentation::theme; using namespace vl::presentation::templates; #endif extern int SetupWindowsGDIRenderer(); extern int SetupWindowsDirect2DRenderer(); extern int SetupOSXCoreGraphicsRenderer(); #endif