blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
3f797eb020d6b8fb87a74c0e21c5d04536a67e30
ff151e1c274204bedbaeeba5ccb3ee400f348cb0
/data/hist/12/25800/a.inc
e1819d91efe71f06587446292a7f5d5265868d78
[]
no_license
bildschirmtext/bildschirmtext
136a194b67cb1d2bcdf0309905d1d58fd7edfd83
f1123f4cce2b7f690c5844751f06c0acd7782b56
refs/heads/master
2023-03-04T09:17:41.050196
2023-03-03T17:29:54
2023-03-03T17:29:54
163,882,281
54
19
null
2022-08-25T13:55:33
2019-01-02T19:42:49
Python
UTF-8
C++
false
false
182
inc
# GA#!0@GOxO@_G^L^N.0-!,!-@^FGGC.0-!,!-@OCGCcCG@O0x@@`G`Gpcp.0^N"^L_GO@OxG@ 0GC!FG@^-,!-! 0CCCaCC@G-,!-! 0cp#GpG``@|@ #,0!GE`DXDVDaE@G 0!xAhFHZHaH@hx 0!O|^^_~^N^^XFO|
[ "mist64@mac.com" ]
mist64@mac.com
5c1f0fc7c97ec3dbd12c27f64197ae499f09e77e
1c6eeacc6d9b871b06007177e07efbe722d79ba8
/resto-app/user.admin.component.cpp
26e818d094a1752d1f5a8420b2904da9d384c4c0
[]
no_license
mic8/resto-app-cpp
35395c55faa98a9799fa453f91519f56acbb6093
771b170a13a6b309f082f46bebefa4c121d98afe
refs/heads/master
2021-01-19T15:54:55.745043
2017-05-19T04:12:56
2017-05-19T04:12:56
87,287,882
0
0
null
null
null
null
UTF-8
C++
false
false
1,012
cpp
#include "user.admin.component.h" void UserAdminComponent::bindList() { this->list.push_back("Add User"); this->list.push_back("View Users"); } void UserAdminComponent::bindTitle(string title) { this->setTitle(title); } void UserAdminComponent::addUser() { UserAddAdminComponent userAdd; userAdd.init(); } void UserAdminComponent::viewUsers() { UserViewAdminComponent userView; userView.init(); } void UserAdminComponent::action(int currIndex) { StreamHelper::cls(); switch (currIndex) { case 0 : this->addUser(); break; case 1 : this->viewUsers(); break; case 2 : //update user break; case 3 : //delete user break; } } void UserAdminComponent::back() { VendorAdminComponent vendorAdminComponent; vendorAdminComponent.init(); } void UserAdminComponent::init() { this->bindList(); this->bindTitle("Choose your action to manage user: "); StreamHelper::cls(); this->_init(true); if (this->isBack) { this->back(); } else { this->action(this->getCurrIndex()); } }
[ "michaelreynald78@gmail.com" ]
michaelreynald78@gmail.com
5c99d2b909a729a3f329be9c805010bcb09405b0
6680f8d317de48876d4176d443bfd580ec7a5aef
/Header/misWin32Interactor.h
65d640e4936f7e033d813f0b55410a5a15b5a18f
[]
no_license
AlirezaMojtabavi/misInteractiveSegmentation
1b51b0babb0c6f9601330fafc5c15ca560d6af31
4630a8c614f6421042636a2adc47ed6b5d960a2b
refs/heads/master
2020-12-10T11:09:19.345393
2020-03-04T11:34:26
2020-03-04T11:34:26
233,574,482
3
0
null
null
null
null
UTF-8
C++
false
false
5,018
h
#pragma once #include "vtkRenderingOpenGLModule.h" // For export macro #include "vtkRenderWindowInteractor.h" #include "vtkWindows.h" // For windows API. #include "vtkTDxConfigure.h" // defines VTK_USE_TDX #ifdef VTK_USE_TDX class vtkTDxWinDevice; #endif class misWin32Interactor : public vtkRenderWindowInteractor { public: /** * Construct object so that light follows camera motion. */ static misWin32Interactor *New(); vtkTypeMacro(misWin32Interactor, vtkRenderWindowInteractor); void PrintSelf(ostream& os, vtkIndent indent); /** * Initialize the event handler */ virtual void Initialize(); //@{ /** * Enable/Disable interactions. By default interactors are enabled when * initialized. Initialize() must be called prior to enabling/disabling * interaction. These methods are used when a window/widget is being * shared by multiple renderers and interactors. This allows a "modal" * display where one interactor is active when its data is to be displayed * and all other interactors associated with the widget are disabled * when their data is not displayed. */ virtual void Enable(); virtual void Disable(); //@} //@{ /** * By default the interactor installs a MessageProc callback which * intercepts windows messages to the window and controls interactions. * MFC or BCB programs can prevent this and instead directly route any mouse/key * messages into the event bindings by setting InstallMessgeProc to false. */ vtkSetMacro(InstallMessageProc, int); vtkGetMacro(InstallMessageProc, int); vtkBooleanMacro(InstallMessageProc, int); //@} /** * Win32 specific application terminate, calls ClassExitMethod then * calls PostQuitMessage(0) to terminate the application. An application can Specify * ExitMethod for alternative behavior (i.e. suppression of keyboard exit) */ void TerminateApp(void); friend VTKRENDERINGOPENGL_EXPORT LRESULT CALLBACK misHandleMessage(HWND hwnd, UINT uMsg, WPARAM w, LPARAM l); friend VTKRENDERINGOPENGL_EXPORT LRESULT CALLBACK misHandleMessage2(HWND hwnd, UINT uMsg, WPARAM w, LPARAM l, misWin32Interactor *me); //@{ /** * Various methods that a Win32 window can redirect to this class to be * handled. */ virtual int OnMouseMove(HWND wnd, UINT nFlags, int X, int Y); virtual int OnNCMouseMove(HWND wnd, UINT nFlags, int X, int Y); virtual int OnRButtonDown(HWND wnd, UINT nFlags, int X, int Y, int repeat = 0); virtual int OnRButtonUp(HWND wnd, UINT nFlags, int X, int Y); virtual int OnMButtonDown(HWND wnd, UINT nFlags, int X, int Y, int repeat = 0); virtual int OnMButtonUp(HWND wnd, UINT nFlags, int X, int Y); virtual int OnLButtonDown(HWND wnd, UINT nFlags, int X, int Y, int repeat = 0); virtual int OnLButtonUp(HWND wnd, UINT nFlags, int X, int Y); virtual int OnSize(HWND wnd, UINT nType, int X, int Y); virtual int OnTimer(HWND wnd, UINT nIDEvent); virtual int OnKeyDown(HWND wnd, UINT nChar, UINT nRepCnt, UINT nFlags); virtual int OnKeyUp(HWND wnd, UINT nChar, UINT nRepCnt, UINT nFlags); virtual int OnChar(HWND wnd, UINT nChar, UINT nRepCnt, UINT nFlags); virtual int OnMouseWheelForward(HWND wnd, UINT nFlags, int X, int Y); virtual int OnMouseWheelBackward(HWND wnd, UINT nFlags, int X, int Y); virtual int OnFocus(HWND wnd, UINT nFlags); virtual int OnKillFocus(HWND wnd, UINT nFlags); //@} //@{ /** * Methods to set the default exit method for the class. This method is * only used if no instance level ExitMethod has been defined. It is * provided as a means to control how an interactor is exited given * the various language bindings (tcl, Win32, etc.). */ static void SetClassExitMethod(void(*f)(void *), void *arg); static void SetClassExitMethodArgDelete(void(*f)(void *)); //@} /** * These methods correspond to the the Exit, User and Pick * callbacks. They allow for the Style to invoke them. */ virtual void ExitCallback(); protected: misWin32Interactor(); ~misWin32Interactor(); HWND WindowId; WNDPROC OldProc; int InstallMessageProc; int MouseInWindow; int StartedMessageLoop; //@{ /** * Class variables so an exit method can be defined for this class * (used to set different exit methods for various language bindings, * i.e. tcl, java, Win32) */ static void(*ClassExitMethod)(void *); static void(*ClassExitMethodArgDelete)(void *); static void *ClassExitMethodArg; //@} //@{ /** * Win32-specific internal timer methods. See the superclass for detailed * documentation. */ virtual int InternalCreateTimer(int timerId, int timerType, unsigned long duration); virtual int InternalDestroyTimer(int platformTimerId); //@} /** * This will start up the event loop and never return. If you * call this method it will loop processing events until the * application is exited. */ virtual void StartEventLoop(); #ifdef VTK_USE_TDX vtkTDxWinDevice *Device; #endif private: misWin32Interactor(const misWin32Interactor&) VTK_DELETE_FUNCTION; void operator=(const misWin32Interactor&) VTK_DELETE_FUNCTION; };
[ "alireza_mojtabavi@yahoo.com" ]
alireza_mojtabavi@yahoo.com
6010692aefec5a3e99b72ec581892354f07bc2b8
b0899eb26a5213f7d86b5f8be60f1e8dc7db6d03
/include/Array2D.h
7b5dff4b134736f34e1a92526576bb95f9147428
[]
no_license
redclock/GIEngine
bbdb440fa0d1ded2233ce728083c7c5ae5114f65
0c95238e6b3f81a27eccca6f2c97a0e5f3c08580
refs/heads/master
2021-01-23T10:44:50.191656
2014-06-30T03:25:37
2014-06-30T03:25:37
21,327,591
2
1
null
null
null
null
GB18030
C++
false
false
2,437
h
/************************************************************************/ /* Utilities */ /* 二维数组 编写: 姚春晖 */ /************************************************************************/ #pragma once #include <assert.h> //T为数组元素类型 template<class T> class Array2D { private: //Buffer T* m_buf; int m_rows, m_cols; //Buf是否是外部管理 bool m_attached; public: int GetRows() const { return m_rows; }; int GetCols() const { return m_cols; }; //构造默认数组1x1 Array2D(): m_rows(1), m_cols(1), m_attached(false) { m_buf = new T[m_rows * m_cols]; } //构造数组 Array2D(int row, int col): m_rows(row), m_cols(col), m_attached(false) { m_buf = new T[m_rows * m_cols]; } //拷贝构造函数 Array2D(const Array2D & arr): m_rows(arr.m_rows), m_cols(arr.m_cols), m_attached(arr.m_attached) { if (arr.m_attached) { m_buf = arr.m_buf; }else { m_buf = new T[m_rows * m_cols]; memcpy(m_buf, arr.m_buf, sizeof(T) * m_cols * m_rows); } } //包装外部Buffer Array2D(int row, int col, T * buf): m_rows(row), m_cols(col), m_attached(true) { m_buf = buf; } ~Array2D() { if (!m_attached) delete[] m_buf; } void ZeroArray() { memset(m_buf, 0, sizeof(T) * m_cols * m_rows); } //必须不能为包装的Buffer void Resize(int row, int col) { assert(!m_attached); int minr = min(row, m_rows); int minc = min(col, m_cols); T * temp = new T [(row) * (col)]; T * p = temp; T * q = m_buf; ZeroMemory(temp, sizeof(T) * (row) * (col)); for (int i = 0; i <= minr; i++) { memcpy(p, q, sizeof(T) * minc); p += col; q += m_cols; } delete [] m_buf; m_buf = temp; m_rows = row; m_cols = col; } T * operator [] (int i) { assert(i >= 0 && i < m_rows); return m_buf + i * m_cols; } const T * operator [] (int i) const { assert(i >= 0 && i < m_rows); return m_buf + i * m_cols; } Array2D & operator = (const Array2D & arr) { if (this == &arr) return; if (!m_attached) delete [] m_buf; m_rows = arr.m_rows; m_cols = arr.m_cols; m_attached = arr.m_attached; if (m_attached) { m_buf = arr.m_buf; }else { m_buf = new T[m_rows * m_cols]; memcpy(m_buf, arr.m_buf, sizeof(T) * m_cols * m_rows); } return *this; } T * GetBuf() { return m_buf; } };
[ "redclock" ]
redclock
611bca404a7e8ecd804012d29d6f5e6757939e5a
3282ccae547452b96c4409e6b5a447f34b8fdf64
/SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimPort_HotWaterFlowPort.cxx
a37f72a5a9a51331620cc04aba6a5f8c3b89be81
[ "MIT" ]
permissive
EnEff-BIM/EnEffBIM-Framework
c8bde8178bb9ed7d5e3e5cdf6d469a009bcb52de
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
refs/heads/master
2021-01-18T00:16:06.546875
2017-04-18T08:03:40
2017-04-18T08:03:40
28,960,534
3
0
null
2017-04-18T08:03:40
2015-01-08T10:19:18
C++
UTF-8
C++
false
false
3,681
cxx
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimPort_HotWaterFlowPort.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimPort_HotWaterFlowPort // } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimPort_HotWaterFlowPort // SimPort_HotWaterFlowPort:: SimPort_HotWaterFlowPort () : ::schema::simxml::ResourcesGeneral::SimPort () { } SimPort_HotWaterFlowPort:: SimPort_HotWaterFlowPort (const RefId_type& RefId) : ::schema::simxml::ResourcesGeneral::SimPort (RefId) { } SimPort_HotWaterFlowPort:: SimPort_HotWaterFlowPort (const SimPort_HotWaterFlowPort& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimPort (x, f, c) { } SimPort_HotWaterFlowPort:: SimPort_HotWaterFlowPort (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimPort (e, f, c) { } SimPort_HotWaterFlowPort* SimPort_HotWaterFlowPort:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimPort_HotWaterFlowPort (*this, f, c); } SimPort_HotWaterFlowPort:: ~SimPort_HotWaterFlowPort () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
[ "cao@e3d.rwth-aachen.de" ]
cao@e3d.rwth-aachen.de
5334788f2a52f821ba08d9cbd958e6b0e6496e7b
ba83d0c538126736f4daa676d2028fd082dfb9e7
/kalibrate-bladeRF/src/kal.cc
8a76991c894e4e687cb4a86ffb343228bddc9e08
[ "BSD-2-Clause" ]
permissive
walidraach/mnrt
32019e72b5f6baf793666d0a4dde713781f52123
4154e7fa227c583647aeb05852c0fd79fbd1edc6
refs/heads/main
2023-06-28T09:54:14.741913
2021-08-04T09:55:19
2021-08-04T09:55:19
392,635,599
1
0
null
null
null
null
UTF-8
C++
false
false
9,209
cc
/* * Copyright (c) 2010, Joshua Lackey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * kal * * Two functions: * * 1. Calculates the frequency offset between a local GSM tower and the * USRP clock. * * 2. Identifies the frequency of all GSM base stations in a given band. */ #ifdef HAVE_CONFIG_H #include "config.h" #else #define PACKAGE_VERSION "custom build" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stdlib.h> #ifndef _WIN32 #include <unistd.h> #include <sys/time.h> #endif #ifdef D_HOST_OSX #include <libgen.h> #endif /* D_HOST_OSX */ #include <string.h> #include <errno.h> #include "bladeRF_source.h" #include "fcch_detector.h" #include "arfcn_freq.h" #include "offset.h" #include "c0_detect.h" #include "version.h" #ifdef _WIN32 #include <getopt.h> #define basename(x) "meh" #define strtof strtod #endif #define GSM_RATE (1625000.0 / 6.0) int g_verbosity = 0; int g_debug = 0; void usage(char *prog) { printf("kalibrate v%s, Copyright (c) 2010, Joshua Lackey\n", kal_version_string); printf("\nUsage:\n"); printf("\tGSM Base Station Scan:\n"); printf("\t\t%s <-s band indicator> [options]\n", basename(prog)); printf("\n"); printf("\tClock Offset Calculation:\n"); printf("\t\t%s <-f frequency | -c channel> [options]\n", basename(prog)); printf("\n"); printf("Where options are:\n"); printf("\t-s\tband to scan (GSM850, GSM900, EGSM, DCS, PCS)\n"); printf("\t-f\tfrequency of nearby GSM base station\n"); printf("\t-c\tchannel of nearby GSM base station\n"); printf("\t-b\tband indicator (GSM850, GSM900, EGSM, DCS, PCS)\n"); printf("\t-R\tside A (0) or B (1), defaults to B\n"); printf("\t-A\tantenna TX/RX (0) or RX2 (1), defaults to RX2\n"); printf("\t-g\tgain as %% of range, defaults to 45%%\n"); printf("\t-F\tFPGA master clock frequency, defaults to 52MHz\n"); printf("\t-C\tmanually specify DAC trim value\n"); printf("\t-w\twrite the new DAC calibration value to the device\n"); printf("\t-m\tindicate how much longer a scan should stay on each channel (ie. 4)\n"); printf("\t-v\tverbose\n"); printf("\t-D\tenable debug messages\n"); printf("\t-h\thelp\n"); exit(-1); } int main(int argc, char **argv) { char *endptr; int c, antenna = 1, bi = BI_NOT_DEFINED, chan = -1, bts_scan = 0; unsigned int subdev = 1, decimation = 192; long int fpga_master_clock_freq = 52000000; float gain = 0.45; double freq = -1.0, fd; int calibration = -1; int multiplier = 1; int write = 0; bladeRF_source *u; while((c = getopt(argc, argv, "f:c:C:m:s:b:R:A:g:F:vwDh?")) != EOF) { switch(c) { case 'w': write = 1; break; case 'm': multiplier = strtoul(optarg, 0, 0); break; case 'C': calibration = strtoul(optarg, 0, 0); break; case 'f': freq = strtod(optarg, 0); break; case 'c': chan = strtoul(optarg, 0, 0); break; case 's': if((bi = str_to_bi(optarg)) == -1) { fprintf(stderr, "error: bad band " "indicator: ``%s''\n", optarg); usage(argv[0]); } bts_scan = 1; break; case 'b': if((bi = str_to_bi(optarg)) == -1) { fprintf(stderr, "error: bad band " "indicator: ``%s''\n", optarg); usage(argv[0]); } break; case 'R': errno = 0; subdev = strtoul(optarg, &endptr, 0); if((!errno) && (endptr != optarg)) break; if(tolower(*optarg) == 'a') { subdev = 0; } else if(tolower(*optarg) == 'b') { subdev = 1; } else { fprintf(stderr, "error: bad side: " "``%s''\n", optarg); usage(argv[0]); } break; case 'A': if(!strcmp(optarg, "RX2")) { antenna = 1; } else if(!strcmp(optarg, "TX/RX")) { antenna = 0; } else { errno = 0; antenna = strtoul(optarg, &endptr, 0); if(errno || (endptr == optarg)) { fprintf(stderr, "error: bad " "antenna: ``%s''\n", optarg); usage(argv[0]); } } break; case 'g': gain = strtod(optarg, 0); if((gain > 1.0) && (gain <= 100.0)) gain /= 100.0; if((gain < 0.0) || (1.0 < gain)) usage(argv[0]); break; case 'F': fpga_master_clock_freq = strtol(optarg, 0, 0); if(!fpga_master_clock_freq) fpga_master_clock_freq = (long int)strtod(optarg, 0); // was answer in MHz? if(fpga_master_clock_freq < 1000) { fpga_master_clock_freq *= 1000000; } break; case 'v': g_verbosity++; break; case 'D': g_debug = 1; break; case 'h': case '?': default: usage(argv[0]); break; } } // sanity check frequency / channel if(bts_scan) { if(bi == BI_NOT_DEFINED) { fprintf(stderr, "error: scaning requires band\n"); usage(argv[0]); } } else { if(freq < 0.0) { if(chan < 0) { fprintf(stderr, "error: must enter channel or " "frequency\n"); usage(argv[0]); } if((freq = arfcn_to_freq(chan, &bi)) < 869e6) usage(argv[0]); } if((freq < 869e6) || (2e9 < freq)) { fprintf(stderr, "error: bad frequency: %lf\n", freq); usage(argv[0]); } chan = freq_to_arfcn(freq, &bi); } // sanity check clock if(fpga_master_clock_freq < 48000000) { fprintf(stderr, "error: FPGA master clock too slow: %li\n", fpga_master_clock_freq); // usage(argv[0]); } // calculate decimation -- get as close to GSM rate as we can // fd = (double)fpga_master_clock_freq / GSM_RATE; // decimation = (unsigned int)fd; if(g_debug) { #ifdef D_HOST_OSX printf("debug: Mac OS X version\n"); #endif printf("debug: FPGA Master Clock Freq:\t%li\n", fpga_master_clock_freq); printf("debug: decimation :\t%u\n", decimation); printf("debug: RX Subdev Spec :\t%s\n", subdev? "B" : "A"); printf("debug: Antenna :\t%s\n", antenna? "RX2" : "TX/RX"); printf("debug: Gain :\t%f\n", gain); } u = new bladeRF_source((float)(GSM_RATE * 4), fpga_master_clock_freq); if(!u) { fprintf(stderr, "error: bladeRF_source\n"); return -1; } if(u->open(subdev) == -1) { fprintf(stderr, "error: bladeRF_source::open\n"); return -1; } u->set_antenna(antenna); /* Disable gain as xA4 sets automatically if(!u->set_gain(gain)) { fprintf(stderr, "error: bladeRF_source::set_gain\n"); return -1; }*/ if(!bts_scan) { if(!u->tune(freq)) { fprintf(stderr, "error: bladeRF_source::tune\n"); return -1; } fprintf(stderr, "%s: Calculating clock frequency offset.\n", basename(argv[0])); fprintf(stderr, "Using %s channel %d (%.1fMHz)\n", bi_to_str(bi), chan, freq / 1e6); float off; int dac = 0x8000; int delta = 0x4000; int max = 16; float lowest = 100e6; int dac_l = 0; do { printf("================\n"); u->tune_dac(dac); offset_detect(u, &off); if (fabs(off) < fabs(lowest)) { dac_l = dac; lowest = off; } if (fabs(off) < 50) { printf("BEGINNING LINEAR SEARCH\n"); for (int i = -6; i < 6; i++) { printf("================\n"); u->tune_dac(dac + i); offset_detect(u, &off); if (fabs(off) < fabs(lowest)) { dac_l = dac + i; lowest = off; } } break; } if (off < 0) dac -= delta; if (off > 0) dac += delta; if (off == 0) break; delta /= 2; if (max-- < 0) break; } while (off > 30 || off < 30); printf("Found lowest offset of %fHz at %fMHz (%f ppm) using DAC trim 0x%x\n", lowest, freq/1e6, lowest/freq*1e6, dac_l); if (write) { printf("Saving contents to bladeRF flash\n"); if (!u->save_dac(dac_l)) { printf("Saved successfully. New calibration data will be used when the next time the device is rebooted.\n"); } else printf("Saved unsuccessfully\n"); } return 0; } fprintf(stderr, "%s: Scanning for %s base stations.\n", basename(argv[0]), bi_to_str(bi)); if (calibration != -1) { u->tune_dac(calibration); } return c0_detect(u, bi, multiplier); }
[ "mohamed.walid.raach@gmail.com" ]
mohamed.walid.raach@gmail.com
17eba6564bece97d9d372d6f7271b54435da95c9
475e971618d28efada45bccde7381999e6d51803
/cubey2/Utilities.h
da1a88d5571df96b31043685bc533a3bc23e5da3
[]
no_license
byebyebryan/cubey2
ee287fd61d737093b545833dcc303c44dbaf2290
80443a97338ad5dd8aa5b89b1ea0229b8a40e1ff
refs/heads/master
2021-01-10T13:00:11.956529
2015-11-03T04:19:53
2015-11-03T04:19:53
44,360,798
0
0
null
null
null
null
UTF-8
C++
false
false
88
h
#pragma once namespace cubey2 { inline bool ReturnFalse() { return false; } }
[ "byebyebryan@gmail.com" ]
byebyebryan@gmail.com
23089ab91e2c6791b091a3b3a74b0e74ac571214
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/core/scoring/methods/util.cc
b5e5387f0f1d9e31c32cb314a1ac109134696e49
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
4,957
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file core/scoring/methods/util.cc /// /// @brief utility methods for scoring. /// @author James Thompson // Unit headers #include <core/scoring/methods/util.hh> #include <basic/options/option.hh> #include <basic/Tracer.hh> #include <core/types.hh> #include <core/scoring/Energies.hh> #include <core/conformation/Residue.hh> #include <core/id/AtomID.hh> #include <core/pose/Pose.hh> #include <core/chemical/ResidueConnection.hh> #include <core/scoring/PolymerBondedEnergyContainer.hh> #include <utility/exit.hh> // option key includes #include <basic/options/keys/abinitio.OptionKeys.gen.hh> #include <utility/vector1.hh> namespace core { namespace scoring { namespace methods { static basic::Tracer tr( "core.scoring.methods" ); core::Real get_residue_weight_by_ss( const char ss ) { using namespace basic::options; using namespace basic::options::OptionKeys; core::Real rsd_wt = 1.0; if ( ss == 'H' ) { rsd_wt = option[ abinitio::rsd_wt_helix ](); } else if ( ss == 'E' ) { rsd_wt = option[ abinitio::rsd_wt_strand ](); } else if ( ss == 'L' ) { rsd_wt = option[ abinitio::rsd_wt_loop ](); } else { tr.Error << "don't recognize secondary structure character '" << ss << "' " << std::endl; rsd_wt = option[ abinitio::rsd_wt_loop ](); } return rsd_wt; } // get_residue_wt_by_ss bool residues_interact( conformation::Residue const & rsd1, conformation::Residue const & rsd2, core::Real const interaction_cutoff ) { Real const rsd1_reach( rsd1.nbr_radius() ), rsd2_reach( rsd2.nbr_radius() ); Distance const intxn_dist( rsd1_reach + rsd2_reach + interaction_cutoff ); DistanceSquared const intxn_dist2( intxn_dist * intxn_dist ); DistanceSquared const nbr_dist2( rsd1.xyz( rsd1.nbr_atom() ).distance_squared( rsd2.xyz( rsd2.nbr_atom() ) ) ); return ( nbr_dist2 < intxn_dist2 ); } bool atoms_interact( conformation::Residue const & rsd1, conformation::Residue const & rsd2, core::id::AtomID const & id1, core::id::AtomID const & id2, core::Real const interaction_cutoff ) { debug_assert( id1.rsd() == rsd1.seqpos() ); debug_assert( id2.rsd() == rsd2.seqpos() ); Distance const dist( rsd1.xyz( id1.atomno() ).distance( rsd2.xyz( id2.atomno() ) ) ); return ( dist < interaction_cutoff ); } /// @brief Given two residues that may or may not be connected, determine which of the two, if any, /// is the lower one and which is the upper. /// @details Inputs are rsd1 and rsd2; outputs are rsd1_is_lo and rsd2_is_lo. Both will be false if /// the residues aren't connected (s.t. the C of one connected to some connection of the other). /// @author Vikram K. Mulligan (vmullig@uw.edu). void determine_lo_and_hi_residues( core::pose::Pose const &pose, core::Size const rsd1, core::Size const rsd2, bool &res1_is_lo, bool &res2_is_lo ) { res1_is_lo = ( pose.residue(rsd1).has_upper_connect() && pose.residue(rsd1).residue_connection_partner( pose.residue(rsd1).upper_connect().index() ) == rsd2 ); res2_is_lo = ( pose.residue(rsd2).has_upper_connect() && pose.residue(rsd2).residue_connection_partner( pose.residue(rsd2).upper_connect().index() ) == rsd1 ); } /// @brief Determines whether a long-range energies container exists in the pose energies object. If not, /// creates a new one and appends the score type to it, if necessary. /// @author Vikram K. Mulligan (vmullig@uw.edu). void create_long_range_energy_container( core::pose::Pose &pose, core::scoring::ScoreType const scoretype, core::scoring::methods::LongRangeEnergyType const lr_type ) { using namespace methods; // create LR energy container core::scoring::Energies & energies( pose.energies() ); bool create_new_lre_container( false ); if ( energies.long_range_container( lr_type ) == nullptr ) { create_new_lre_container = true; } else { LREnergyContainerOP lrc = energies.nonconst_long_range_container( lr_type ); PolymerBondedEnergyContainerOP dec( utility::pointer::static_pointer_cast< core::scoring::PolymerBondedEnergyContainer > ( lrc ) ); if ( !dec || !dec->is_valid( pose ) ) { create_new_lre_container = true; } } if ( create_new_lre_container ) { utility::vector1< ScoreType > s_types; s_types.push_back( scoretype ); LREnergyContainerOP new_dec( new PolymerBondedEnergyContainer( pose, s_types ) ); energies.set_long_range_container( lr_type, new_dec ); } } } // namespace methods } // namespace scoring } // namespace core
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
68cb2369f4a71d9e190192cef4742ec2b86e7d17
a802488c68d5c8607e8d4696b8244eaacc9c3ac2
/DK/DKFoundation/DKValue.h
eb77eb0bad079ff64d36ea61cae0ca0e2785824b
[ "LGPL-2.0-or-later", "BSD-3-Clause" ]
permissive
Hongtae/DKGL
e311c6e528349c8b9e7e8392f1d01ac976e76be1
eb33d843622504cd6134accf08c8ec2c98794b55
refs/heads/develop
2023-04-28T22:02:44.866063
2023-01-14T02:11:30
2023-01-14T02:11:30
30,572,734
11
3
BSD-3-Clause
2023-01-18T03:02:10
2015-02-10T03:23:18
C
UTF-8
C++
false
false
1,107
h
// // File: DKValue.h // Author: Hongtae Kim (tiff2766@gmail.com) // // Copyright (c) 2004-2016 Hongtae Kim. All rights reserved. // #pragma once #include "../DKInclude.h" #include "DKTypeTraits.h" #include "DKObject.h" #include "DKInvocation.h" namespace DKFoundation { template <typename T> class DKInvocationValue : public DKInvocation<T> { public: DKInvocationValue(T v) : value(v) { } protected: T Invoke() const { return value; } private: T value; }; template <typename T> class DKInvocationValue<T*> : public DKInvocation<T*> { public: DKInvocationValue(T* v) : value(v) { } protected: T* Invoke() const { return const_cast<T*>((const T*)value); } private: DKObject<T> value; }; /// Binds variable or constant to DKInvocation object. (see DKInvocation.h) /// a variable or constant bounds, will become result of invocation. template <typename T> DKObject<DKInvocation<T>> DKValue(T value) { DKObject<DKInvocationValue<T>> invocation = DKOBJECT_NEW DKInvocationValue<T>(value); return invocation.template SafeCast<DKInvocation<T>>(); } }
[ "tiff2766@gmail.com" ]
tiff2766@gmail.com
234c20da1ee0cc40aa00f897339f0d48e456febb
51635684d03e47ebad12b8872ff469b83f36aa52
/external/gcc-12.1.0/libstdc++-v3/testsuite/21_strings/basic_string/requirements/citerators.cc
e0e629ca4d7429c2d6b800e1eb5e98b8c503bdef
[ "LGPL-2.1-only", "GPL-3.0-only", "GCC-exception-3.1", "GPL-2.0-only", "LGPL-3.0-only", "LGPL-2.0-or-later", "Zlib", "LicenseRef-scancode-public-domain" ]
permissive
zhmu/ananas
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
30850c1639f03bccbfb2f2b03361792cc8fae52e
refs/heads/master
2022-06-25T10:44:46.256604
2022-06-12T17:04:40
2022-06-12T17:04:40
30,108,381
59
8
Zlib
2021-09-26T17:30:30
2015-01-31T09:44:33
C
UTF-8
C++
false
false
1,140
cc
// { dg-do run { target c++11 } } // { dg-require-string-conversions "" } // Copyright (C) 2009-2022 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <string> #include <debug/string> #include <testsuite_containers.h> int main() { __gnu_test::citerator<std::string> test1; __gnu_test::citerator<__gnu_debug::string> dtest1; __gnu_test::citerator<std::wstring> test2; __gnu_test::citerator<__gnu_debug::wstring> dtest2; return 0; }
[ "rink@rink.nu" ]
rink@rink.nu
4226da02c010c64a21551baad3772831d6bfcd99
d1b610d184e31586aba6ecf42b4e5d633347a35c
/algorithms/test_mutability.cpp
1938029f44d0938f773590ae4e7e4798427333c7
[]
no_license
KuangyiZhu/algorithms
8cab551337c81169f20f9eafda8267963ea8dbb3
0ef1d08c4d321c2fdec26132c620aa742d34cc5a
refs/heads/master
2020-04-05T22:53:13.672613
2019-08-07T03:15:07
2019-08-07T03:15:07
62,196,339
0
0
null
2016-09-02T13:21:16
2016-06-29T04:48:30
C++
UTF-8
C++
false
false
1,392
cpp
#include <iostream> #include <vector> class TestClass { public: class TestStruct { public: std::vector<int> & m_vtest; const std::vector<int> & im_vtest; TestStruct(std::vector<int> & vtest1, std::vector<int> & vtest2) : m_vtest(vtest1), im_vtest(vtest2) {} }; TestStruct GetTestStruct() {return (TestStruct(_vtest1, _vtest2));} void AddTest1(int value) {_vtest1.push_back(value);} void AddTest2(int value) {_vtest2.push_back(value);} const std::vector<int> & GetTest1() {return _vtest1;} const std::vector<int> & GetTest2() {return _vtest2;} private: std::vector<int> _vtest1; std::vector<int> _vtest2; }; int main(int argc, char** argvs) { std::cout << "Test Mutability" << std::endl; TestClass tc; tc.AddTest1(1); tc.AddTest2(2); TestClass::TestStruct ts = tc.GetTestStruct(); std::cout << ts.m_vtest[0] << std::endl; std::cout << ts.im_vtest[0] << std::endl; ts.m_vtest[0] += 2; std::cout << ts.m_vtest[0] << std::endl; // error ts.im_vtest[0] += 2; std::cout << ts.im_vtest[0] << std::endl; }
[ "noreply@github.com" ]
KuangyiZhu.noreply@github.com
0a576ed7020bd381935e47fc8616057097f44677
8242fcd5afc97ab88d0890d12a9c52475e8d1187
/源代码/gamemap.cpp
46e876f41d842af2a6915e51df8c1ed7f045e8fe
[]
no_license
clayandgithub/AstarSearchAlgorithm2DGame
a8a2193b982ee8d9f632c6bfdfac8c5e52848f57
b0c32760af38dd1bc97ca599145d10e2dcead031
refs/heads/master
2020-09-25T00:54:14.300933
2016-08-23T10:11:13
2016-08-23T10:11:13
66,355,885
0
0
null
null
null
null
UTF-8
C++
false
false
3,439
cpp
#include "gamemap.h" GameMap::GameMap(QPixmap *bmp, int fWidth, int fHeight, int layer_level):Layer(bmp,fWidth,fHeight,layer_level) { for(int i = 0;i < MAP_ROW; ++i) { for(int j = 0;j < MAP_COLUMN; ++j) { mMap[i][j] = -1; } } genMapData(); } GameMap::~GameMap() {} void GameMap::genMapData() { srand(time(NULL)); if(mLayerLevel == 0) { int rand_0_99 = 0;//100以下的随机数 //固定的周围 //two sides for(int i = 0;i < MAP_ROW-1;++i) { mMap[i][0] = 2; mMap[i][MAP_COLUMN-1] = 0; } //top for(int i = 0;i < 2;++i) { for(int j = 1;j < MAP_COLUMN-1;++j) { mMap[i][j] = 6; } } //top end for(int j = 1;j < MAP_COLUMN-1;++j) { mMap[2][j] = 26; } //corners mMap[MAP_ROW-1][0] = 4; mMap[MAP_ROW-1][MAP_COLUMN-1] = 5; for(int i = 3;i < MAP_ROW-1;++i) { for(int j = 1;j < MAP_COLUMN-1;++j) { rand_0_99 = rand()%100; if(rand_0_99 < 80)//80% { mMap[i][j] = 420;//地面1 } else if(rand_0_99 < 85) mMap[i][j] = 320;//矿石1 else if(rand_0_99 < 90) mMap[i][j] = 321;//矿石2 else if(rand_0_99 < 95) mMap[i][j] = 322;//矿石3 else if(rand_0_99 < 98) mMap[i][j] = 280;//石头4 else mMap[i][j] = 281;//植物1 } } for(int j = 1;j < MAP_COLUMN-1;++j) { mMap[MAP_ROW-1][j] = 420; } { //半随机入口 int rand_1_13 = rand()%13+1; mMap[1][rand_1_13] = 300; mMap[2][rand_1_13] = 431; mMap[3][rand_1_13] = 420; //随机放在这里 } } else {//(第二层图) for(int j = 1;j < MAP_COLUMN-1;++j) { mMap[MAP_ROW-1][j] = 1; } { //半随机出口 int rand_2_13 = rand()%12+2; mMap[MAP_ROW-1][rand_2_13-1] = 2; mMap[MAP_ROW-1][rand_2_13] = -1; mMap[MAP_ROW-1][rand_2_13+1] = 0; } } //readFromFile(); } void GameMap::setCell(int row,int col,int tileIndex) { if(row >= 0 && col >= 0) { mMap[row][col] = tileIndex; } } int GameMap::getCell(int row,int col) { if(row >= 0 && col >= 0) { return mMap[row][col]; } return -1; } void GameMap::tick() { } void GameMap::paint(QPixmap *canvas) { // !!!!!这里面可以考虑添加一张背景bmp元素.直接先画这个bmp,再画图块,这里用黑色代替 // 在绘制第一层地图时用黑色清除之前的画布 // canvas->fill(Qt::black); if(mBitmap == NULL) { return; } QPainter painter(canvas); for(int i = 0;i < MAP_ROW; ++i) { for(int j = 0;j < MAP_COLUMN; ++j) { if(mMap[i][j] >= 0) { painter.drawPixmap(mX+j*mFWidth,mY+i*mFHeight,mDstWidth,mDstHeight, *mBitmap,mFrameXCor[mMap[i][j]],mFrameYCor[mMap[i][j]],mFWidth,mFHeight); } } } }
[ "clayanddev@sina.com" ]
clayanddev@sina.com
3210dd18ca943ee8726a3d57c4bf72b813216932
d3883d4755656a85b022546347e5abd395da60cf
/+hem/+util/+sampen/cmatches.cpp
a63664df7f504903cf61757690a3bccb5966665d
[]
no_license
AndroulakisGrp/SB_Insulin
46e65df9e166d0b894fd2333b487d0d9cb998d1d
558f963091518c5020958076df54ba39b631a466
refs/heads/master
2020-03-18T12:42:01.916331
2019-03-25T21:38:00
2019-03-25T21:38:00
134,739,564
0
0
null
null
null
null
UTF-8
C++
false
false
1,779
cpp
#include <math.h> #include "mex.h" /* Edited by JDS, 2010-06-21 - Renamed from matches.cpp to cmatches.cpp to correspond to its name in Matlab - Fixed minor compilation errors in GCC 4.4 (variable scoping in for loops) */ void filter2(double* y, double* y2, int N); int runs(double* y, double r, int N, int* M, int *R); double getm1(double* y, int n); double getm2(double* y, int n); void mexFunction (int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs) { int mrows, ncols, N, *M, *R, *Mptr,*Rptr, i; double *Nptr, *rptr, r, *y2, *y, stdev; int dims[2]; if(nrhs != 3) mexErrMsgTxt("three inputs required.\n"); if(nlhs != 2) mexErrMsgTxt("two outputs required.\n"); Nptr = mxGetPr(prhs[1]); rptr = mxGetPr(prhs[2]); r = *rptr; N = (int)(*Nptr); y = mxGetPr(prhs[0]); M = (int*)mxCalloc(N+2, sizeof(int)); R = (int*)mxCalloc(N+2, sizeof(int)); N = runs(y, r, N, M, R); dims[0] = N; dims[1] = 1; plhs[0] = mxCreateNumericArray(1, dims, mxINT32_CLASS, mxREAL); plhs[1] = mxCreateNumericArray(1, dims, mxINT32_CLASS, mxREAL); Mptr = (int*)mxGetPr(plhs[0]); Rptr = (int*)mxGetPr(plhs[1]); M = M+1; R = R+1; for(i = 0; i < N; i++) { Mptr[i] = M[i]; Rptr[i] = R[i]; } } int runs(double* y, double r, int N, int* M, int *R) { for(int i = 0;i < N; i++) { R[i] = 0; M[i] = 0;} for(int j = 1; j < N-1; j++) { int k = 0; for(int i = 0; i < N-j; i++) { if(y[i+j]-y[i] < r && y[i+j]-y[i]>-r) k++; else if(k != 0) { R[k] = R[k]+1; k = 0; } } if(k != 0) R[k]=R[k]+1; } M[0] = 0; for(int i = 1; i < N; i++) { M[i] = R[i]; for(int j = i+1; j < N; j++) M[i] = M[i]+(j+1-i)*R[j]; } int i = 1; while(M[i++] != 0); return i; }
[ "kgbisa@gmail.com" ]
kgbisa@gmail.com
da92b39209225a7cc888ab8e2f6a1fe644c8d975
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive/e99de36c6ef3e305d1732c90f72ded9b-50d9cfc8a1d350e7409e81e87c2653ba/main.cpp
1f06ddd7de616c45feb7d3e7eb2dbfe5492f3e33
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
2,881
cpp
#include <iostream> #include <boost/graph/grid_graph.hpp> #include <boost/graph/boykov_kolmogorov_max_flow.hpp> #include <boost/graph/iteration_macros.hpp> int main() { const unsigned int D = 2; typedef boost::grid_graph<D> Graph; typedef boost::graph_traits<Graph>::vertex_descriptor VertexDescriptor; typedef boost::graph_traits<Graph>::edge_descriptor EdgeDescriptor;//ADDED typedef boost::graph_traits<Graph>::vertices_size_type VertexIndex; typedef boost::graph_traits<Graph>::edges_size_type EdgeIndex; boost::array<unsigned int, D> lengths = { { 3, 3 } }; Graph graph(lengths, false); float pixel_intensity[]={10.0f,15.0f,25.0f, 5.0f,220.0f,240.0f, 12.0f,15.0,230.0f}; std::vector<int> groups(num_vertices(graph)); std::vector<float> residual_capacity(num_edges(graph)); //this needs to be initialized to 0 std::vector<float> capacity(num_edges(graph)); //this is initialized below, I believe the capacities of an edge and its reverse should be equal, but I'm not sure std::vector<EdgeDescriptor> reverse_edges(num_edges(graph));//ADDED BGL_FORALL_EDGES(e,graph,Graph) { VertexDescriptor src = source(e,graph); VertexDescriptor tgt = target(e,graph); VertexIndex source_idx = get(boost::vertex_index,graph,src); VertexIndex target_idx = get(boost::vertex_index,graph,tgt); EdgeIndex edge_idx = get(boost::edge_index,graph,e); capacity[edge_idx] = 255.0f - fabs(pixel_intensity[source_idx]-pixel_intensity[target_idx]); //you should change this to your "gradiant or intensity or something" reverse_edges[edge_idx]=edge(tgt,src,graph).first;//ADDED } VertexDescriptor s=vertex(0,graph), t=vertex(8,graph); //in the boykov_kolmogorov_max_flow header it says that you should use this overload with an explicit color property map parameter if you are interested in finding the minimum cut boykov_kolmogorov_max_flow(graph, make_iterator_property_map(&capacity[0], get(boost::edge_index, graph)), make_iterator_property_map(&residual_capacity[0], get(boost::edge_index, graph)), make_iterator_property_map(&reverse_edges[0], get(boost::edge_index, graph)), //CHANGED make_iterator_property_map(&groups[0], get(boost::vertex_index, graph)), get(boost::vertex_index, graph), s, t ); for(size_t index=0; index < groups.size(); ++index) { if((index%lengths[0]==0)&&index) std::cout << std::endl; std::cout << groups[index] << " "; } return 0; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
2cdbefd8e306a2bfcc2f5414bbe4cdafa0cf1d4f
8a29f2fb7ad6a6d85aaf5a7582136de73252354c
/Pointers/TM07-Project/TM07-Project/LongestSubString/find the biggest substring.cpp
85a8c473350e82f218fab9ef551aed6659fd737a
[]
no_license
navin2608/c-plus-plus
615e69a0c0bfdffdaf11fa8baf30e6dc9ac23ba8
9adc3d9c1d073c7575f1d62e4c56bcd62c440dd2
refs/heads/master
2022-12-03T05:46:24.338565
2020-07-29T10:30:25
2020-07-29T10:30:25
280,698,679
0
0
null
null
null
null
UTF-8
C++
false
false
977
cpp
#include <iostream> #include <string.h> using namespace std; #define MIN(x, y) (((x) < (y)) ? (x) : (y)) void substring(char s[], char sub[], int p, int len){ int c = 0; while (c < len) { sub[c] = s[p+c]; c++; } sub[c] = '\0'; } int lcp(char s[], char t[],char a[]){ int n = MIN(strlen(s),strlen(t)); for(int i = 0; i < n; i++){ if(s[i] != t[i]){ substring(s,a,0,i); return 0; } } substring(s,a,0,n); return 0; } int main() { // cout<<"enter a string : "; // string s1; // getline(cin,s1); // char str[s1.size()+1]; // strcpy(str,s1.c_str()); // //cout<<s1<<str; char str[] = "helloredhellogreenhelloyellow"; char lrs[30], x[30], res[30], sub[30],sub1[30]; int i,j,n = strlen(str); for(i = 0; i < n; i++){ for(j = i+1; j < n; j++){ substring(str,sub,i,n); substring(str,sub1,j,n); lcp(sub,sub1,x); if(strlen(x) > strlen(lrs)) strncpy(lrs, x, strlen(x)); } } cout<<"Longest repeating sequence:"<<lrs; return 0; }
[ "msnsnavin@gmail.com" ]
msnsnavin@gmail.com
b2142bbc0f9d660c2b06bc5766ea0369643f463c
713e0defdc5532dffa142ed8feea666cd52e1966
/C++/Sorting/insertionsort.h
c355d8262e9031dd0d03dd4dc7cb9712193074d4
[]
no_license
Aymane11/BasicAlgos
f20744b1e27caa3d10daef136fdc7cc0ebbc8ec7
22ee92a7d2317627b60435c841c3f04410863ce5
refs/heads/master
2022-07-29T19:36:29.608998
2020-05-22T17:12:00
2020-05-22T17:12:00
262,923,197
2
0
null
null
null
null
UTF-8
C++
false
false
532
h
#include <bits/stdc++.h> using namespace std; /* Summary: Sorting an array using selection sort algortihm Arguments: [vector<int>] -- [initial array] Returns: [vector<int>] -- [sorted array] */ vector<int> insertionsort(vector<int> arr){ for (int i = 0; i < arr.size(); ++i){ int index_min = i; for (int j = i; j < arr.size(); ++j){ if (arr[index_min] > arr[j]) index_min = j; } swap(arr[i] ,arr[index_min]); } return arr; }
[ "aymaneboumaaza@gmail.com" ]
aymaneboumaaza@gmail.com
083ad06e301f8c87fb656ab8f91ac1042de06204
6b84794b2b0aa23a2d2c3c5f1437001d103213ae
/Problems & Contents/Maratona 2014 - Regional/Aquecimento/C-FechemAsPortas.cpp
8f7176246d67108d02e1e7520e17dfa38c844be3
[]
no_license
mtreviso/university
2406d3782759a75ef00af4da8e4e1ed99cfb89d8
164dbfc13d6dddb3bdbb04957c4702d0e0885402
refs/heads/master
2021-01-09T08:14:21.551497
2016-06-09T23:19:01
2016-06-09T23:19:01
16,703,296
0
2
null
null
null
null
UTF-8
C++
false
false
580
cpp
/* * * File: Problema C - FechemAsPortas * Author: Marcos V. Treviso * * Complexity: O(sqrt(n)) -> O(n) * * Description: * - Sequencia de numeros crescente correspondente aos * identificadores dos quartos com portas abertas. * * Compile: g++ -o teste C-FechemAsPortas.cpp -Wall -Wextra * Run: ./teste < <arquivo.txt> * */ #include <cstdio> #include <cstdlib> #include <cmath> #include <vector> using namespace std; int main(){ int n; while(scanf("%d", &n) != EOF){ int i = 1; while(i*i <= n){ printf("%d ", i*i); i++; } printf("\n"); } return 0; }
[ "marcosvtreviso@gmail.com" ]
marcosvtreviso@gmail.com
1eb19b576d94ff2ecce1b7e1125c74cae6d744c6
1945d6a94eac953229784c18b34f57539a4868e3
/src/plugins/robots/loot-bot/control_interface/ci_lootbot_light_sensor.cpp
7618fcfd77c117978999695d915a8dd971cb5762
[]
no_license
mircoAlt/argos3-lootbot
ce76cbf992cce50d2720e1f8a078f22a003969cd
ae8ad48a5987688a617564d85e0ecbc17d4d6287
refs/heads/master
2021-01-01T14:14:56.920592
2020-02-09T14:49:19
2020-02-09T14:49:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,304
cpp
/** * @file <argos3/plugins/robots/loot-bot/control_interface/ci_lootbot_light_sensor.cpp> * * @author Carlo Pinciroli - <ilpincy@gmail.com> */ #include "ci_lootbot_light_sensor.h" #ifdef ARGOS_WITH_LUA #include <argos3/core/wrappers/lua/lua_utility.h> #endif namespace argos { /****************************************/ /****************************************/ static CRadians SPACING = CRadians(ARGOS_PI / 12.0f); static CRadians START_ANGLE = SPACING * 0.5f; /****************************************/ /****************************************/ CCI_LootBotLightSensor::CCI_LootBotLightSensor() : m_tReadings(24) { for(size_t i = 0; i < 24; ++i) { m_tReadings[i].Angle = START_ANGLE + i * SPACING; m_tReadings[i].Angle.SignedNormalize(); } } /****************************************/ /****************************************/ const CCI_LootBotLightSensor::TReadings& CCI_LootBotLightSensor::GetReadings() const { return m_tReadings; } /****************************************/ /****************************************/ #ifdef ARGOS_WITH_LUA void CCI_LootBotLightSensor::CreateLuaState(lua_State* pt_lua_state) { CLuaUtility::OpenRobotStateTable(pt_lua_state, "light"); for(size_t i = 0; i < GetReadings().size(); ++i) { CLuaUtility::StartTable(pt_lua_state, i+1 ); CLuaUtility::AddToTable(pt_lua_state, "angle", m_tReadings[i].Angle); CLuaUtility::AddToTable(pt_lua_state, "value", m_tReadings[i].Value); CLuaUtility::EndTable (pt_lua_state ); } CLuaUtility::CloseRobotStateTable(pt_lua_state); } #endif /****************************************/ /****************************************/ #ifdef ARGOS_WITH_LUA void CCI_LootBotLightSensor::ReadingsToLuaState(lua_State* pt_lua_state) { lua_getfield(pt_lua_state, -1, "light"); for(size_t i = 0; i < GetReadings().size(); ++i) { lua_pushnumber(pt_lua_state, i+1 ); lua_gettable (pt_lua_state, -2 ); lua_pushnumber(pt_lua_state, m_tReadings[i].Value); lua_setfield (pt_lua_state, -2, "value" ); lua_pop(pt_lua_state, 1); } lua_pop(pt_lua_state, 1); } #endif /****************************************/ /****************************************/ std::ostream& operator<<(std::ostream& c_os, const CCI_LootBotLightSensor::SReading& s_reading) { c_os << "Value=<" << s_reading.Value << ">, Angle=<" << s_reading.Angle << ">"; return c_os; } /****************************************/ /****************************************/ std::ostream& operator<<(std::ostream& c_os, const CCI_LootBotLightSensor::TReadings& t_readings) { if(! t_readings.empty()) { c_os << "{ " << t_readings[0].Value << " }"; for(UInt32 i = 1; i < t_readings.size(); ++i) { c_os << " { " << t_readings[0].Value << " }"; } c_os << std::endl; } return c_os; } /****************************************/ /****************************************/ }
[ "mircoaltenbernd@me.com" ]
mircoaltenbernd@me.com
ffcf27fe818ef8a85c26862d9f2edb4a3feebea8
847851d522c80a2211ab69a05435f93ef0446b5b
/Year 3/composition-source/Array.h
555c5947e24435866744cb199f4463d0adf7344a
[]
no_license
huntmk/SchoolWork
454651f19ed18a5081917b5c8af017d86d303413
8cdf87b3be4c815cd3471f6292eba598038422dc
refs/heads/master
2021-12-11T19:22:38.888640
2021-12-07T23:16:53
2021-12-07T23:16:53
218,656,800
0
0
null
null
null
null
UTF-8
C++
false
false
5,664
h
// -*- C++ -*- // $Id: Array.h 380 2010-02-08 05:10:33Z hillj $ //============================================================================== /** * @file Array.h * * $Id: Array.h 380 2010-02-08 05:10:33Z hillj $ * * Honor Pledge: * * I pledge that I have neither given nor received any help * on this assignment. */ //============================================================================== #ifndef _ARRAY_H_ #define _ARRAY_H_ #include <cstring> // for size_t definition #include "Array_Base.h" /** * @class Array * * Basic implementation of a standard array class for chars. */ template <typename T> class Array : public Array_Base<T> { public: /// Type definition of the element type. typedef T type; /// Default constructor. Array (void); /** * Initializing constructor. * * @param[in] length Initial size */ Array (size_t length); /** * Initializing constructor. * * @param[in] length Initial size * @param[in] fill Initial value for each element */ Array (size_t length, T fill); /** * Copy constructor * * @param[in] arr The source array. */ Array (const Array & arr); /// Destructor. virtual ~Array (void); /** * Assignment operation * * @param[in] rhs Right-hand side of equal sign * @return Reference to self */ const Array & operator = (const Array & rhs); /** * Retrieve the current size of the array. * * @return The current size */ virtual size_t size (void) const; /** * Retrieve the maximum size of the array. * * @return The maximum size */ size_t max_size (void) const; /** * Get the character at the specified index. If the index is not * within the range of the array, then std::out_of_range exception * is thrown. * * @param[in] index Zero-based location * @exception std::out_of_range Invalid \a index value */ T & operator [] (size_t index); /** * @overload * * The returned character is not modifiable. */ const T & operator [] (size_t index) const; /** * Get the character at the specified index. If the \a index is not within * the range of the array, then std::out_of_range exception is thrown. * * @param[in] index Zero-based location * @return Character at \index * @exception std::out_of_range Invalid index value */ virtual T get (size_t index) const; /** * Set the character at the specified \a index. If the \a index is not * within range of the array, then std::out_of_range exception is * thrown. * * @param[in] index Zero-based location * @param[in] value New value for character * @exception std::out_of_range Invalid \a index value */ virtual void set (size_t index, T value); /** * Set a new size for the array. If \a new_size is less than the current * size, then the array is truncated. If \a new_size if greater then the * current size, then the array is made larger and the new elements are * not initialized to anything. If \a new_size is the same as the current * size, then nothing happens. * * The array's original contents are preserved regardless of whether the * array's size is either increased or decreased. * * @param[in] new_size New size of the array */ virtual void resize (size_t new_size); /** * Locate the specified character in the array. The index of the first * occurrence of the character is returned. If the character is not * found in the array, then -1 is returned. * * @param[in] ch Character to search for * @return Index value of the character * @retval -1 Character not found */ virtual int find (T element) const; /** * @overload * * This version allows you to specify the start index of the search. If * the start index is not within the range of the array, then the * std::out_of_range exception is thrown. * * @param[in] ch Character to search for * @param[in] start Index to begin search * @return Index value of first occurrence * @retval -1 Character not found * @exception std::out_of_range Invalid index */ virtual int find (T element, size_t start) const; /** * Test the array for equality. * * @param[in] rhs Right hand side of equal to sign * @retval true Left side is equal to right side * @retval false Left side is not equal to right side */ bool operator == (const Array & rhs) const; /** * Test the array for inequality. * * @param[in] rhs Right-hand size of not equal to sign * @retval true Left side is not equal to right side * @retval false Left size is equal to right side */ bool operator != (const Array & rhs) const; /** * Fill the contents of the array. * * @param[in] ch Fill character */ virtual void fill (T element); //shrink method virtual void shrink(); private: /// Pointer to the actual data. T * data_; /// Current size of the array. size_t cur_size_; /// Maximum size of the array. size_t max_size_; }; #include "Array.inl" #include "Array.cpp" #endif // !defined _ARRAY_H_
[ "noreply@iu.edu" ]
noreply@iu.edu
715c8ce094fc9fb903d46709165cfba49819bb75
8568b3c5044b8dd3a840e2b1dc166113071b3096
/Lib/Mapi2010/ol2010mapisamples-84078/SampleTransportProvider/MRXP/CXPLogon.h
a5d364d2d4dc2e81c8531807bdeed0379273a65f
[]
no_license
djloved/ezOneDocs
c8b588d48506cb8d6f505c5e4d2a78e99b173ecc
fab438c87482d20873de84cb08351cbdcb7e2254
refs/heads/master
2021-01-24T20:25:05.594974
2018-02-28T07:52:35
2018-02-28T07:52:35
123,249,619
0
0
null
null
null
null
UTF-8
C++
false
false
3,163
h
#pragma once #define DEF_STATUS_ROW_STRING_LEN 128 #define DEF_NDR_TEXT_LEN 512 #define NDR_ERROR_PAD 14 * sizeof(TCHAR) #define ERROR_LOADING_NDR_TEXT _T("Error loading NDR Text") #define MSG_FILTER _T("*.MSG") #define NUM_RECIP_RES 2 class CXPStatus; class CXPLogon : public IXPLogon { public: // IUnknown STDMETHODIMP QueryInterface(REFIID riid, LPVOID * ppvObj); inline STDMETHODIMP_(ULONG) AddRef() { EnterCriticalSection (&m_csObj); ++m_cRef; ULONG ulCount = m_cRef; LeaveCriticalSection (&m_csObj); return ulCount; } inline STDMETHODIMP_(ULONG) Release() { EnterCriticalSection (&m_csObj); ULONG ulCount = --m_cRef; LeaveCriticalSection (&m_csObj); if (!ulCount) delete this; return ulCount; } // IXPLogon MAPI_IXPLOGON_METHODS(IMPL); // Constructor Destructor CXPLogon(CXPProvider* pProvider, LPMAPISUP pMAPISup, LPALLOCATEBUFFER pAllocBuffer, LPALLOCATEMORE pAllocMore, LPFREEBUFFER pFreeBuffer, ULONG ulProps, LPSPropValue pProps, ULONG ulFlags); ~CXPLogon(); // Helper functions SCODE STDMETHODCALLTYPE MyAllocateBuffer(ULONG cbSize, LPVOID FAR * lppBuffer); SCODE STDMETHODCALLTYPE MyAllocateMore(ULONG cbSize, LPVOID lpObject, LPVOID FAR * lppBuffer); ULONG STDAPICALLTYPE MyFreeBuffer(LPVOID lpBuffer); inline void AddStatusBits(ULONG ulBitsToAdd) {m_ulStatusBits |= ulBitsToAdd;} inline void RemoveStatusBits(ULONG ulBitsToRemove) {m_ulStatusBits &= ~ulBitsToRemove;} inline ULONG GetStatusBits() {return m_ulStatusBits;} inline HINSTANCE GetHINST() {return m_pProvider->GetHINST();} inline void SetNextLogon(CXPLogon* pNext) {m_pNextLogon = pNext;} inline CXPLogon* GetNextLogon() {return m_pNextLogon;} HRESULT GenerateIdentity(); HRESULT CreateStatusRow(); UINT GetStatusStringID(); HRESULT UpdateStatusRow(); HRESULT GetRecipientsToProcess(LPMESSAGE lpMessage, LPADRLIST* lppAdrList); HRESULT StripDupsAndP1(LPMESSAGE lpMessage); HRESULT NewMailWaiting(LPTSTR* ppszNewMailFile, LPFILETIME pDeliveredTime); HRESULT LoadFromMSG(LPCTSTR szMessageFile, LPMESSAGE lpMessage); HRESULT LoadMSGToMessage(LPCTSTR szMessageFile, LPMESSAGE* lppMessage); HRESULT SaveToMSG(LPMESSAGE lpMessage, LPCTSTR szFileName); HRESULT StampSender(LPMESSAGE lpMessage); HRESULT SetNDRText(ADRENTRY adrRecip, HRESULT hResSendError, LPVOID pParent); HRESULT GenerateBadRecipList(LPADRLIST lpOriginal, LPADRLIST* lppBadRecips); HRESULT CopySPropValueArray(ULONG cProps, LPSPropValue lpSourceProps, LPSPropValue* lppTargetProps, LPVOID lpParent); HRESULT AnsiToUnicode(LPCSTR pszA, LPWSTR* ppszW); private: LPTSTR m_pszFileFilter; CXPProvider* m_pProvider; CXPLogon* m_pNextLogon; CXPStatus* m_pStatusObj; LPMAPISUP m_pMAPISup; LPALLOCATEBUFFER m_pAllocBuffer; LPALLOCATEMORE m_pAllocMore; LPFREEBUFFER m_pFreeBuffer; ULONG m_ulProps; LPSPropValue m_pProps; LPSPropValue m_pIdentityProps; size_t m_cchInboxPath; ULONG m_ulLogonFlags; ULONG m_ulStatusBits; ULONG m_cRef; CRITICAL_SECTION m_csObj; };
[ "djloved@gmail.com" ]
djloved@gmail.com
802ba77244e1bf655dd181f9f64622a18a60fca6
7446fede2d71cdb7c578fe60a894645e70791953
/src/uint256.cpp
ba2c6e35d5d03c087d93311cfb75c34c906de4d3
[ "MIT" ]
permissive
ondori-project/rstr
23522833c6e28e03122d40ba663c0024677d05c9
9b3a2ef39ab0f72e8efffee257b2eccc00054b38
refs/heads/master
2021-07-12T18:03:23.480909
2019-02-25T17:51:46
2019-02-25T17:51:46
149,688,410
2
3
MIT
2019-02-14T02:19:49
2018-09-21T00:44:03
C++
UTF-8
C++
false
false
11,172
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017 The PIVX developers // Copyright (c) 2017 The RSTR developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "uint256.h" #include "utilstrencodings.h" #include <stdio.h> #include <string.h> template <unsigned int BITS> base_uint<BITS>::base_uint(const std::string& str) { SetHex(str); } template <unsigned int BITS> base_uint<BITS>::base_uint(const std::vector<unsigned char>& vch) { if (vch.size() != sizeof(pn)) throw uint_error("Converting vector of wrong size to base_uint"); memcpy(pn, &vch[0], sizeof(pn)); } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator<<=(unsigned int shift) { base_uint<BITS> a(*this); for (int i = 0; i < WIDTH; i++) pn[i] = 0; int k = shift / 32; shift = shift % 32; for (int i = 0; i < WIDTH; i++) { if (i + k + 1 < WIDTH && shift != 0) pn[i + k + 1] |= (a.pn[i] >> (32 - shift)); if (i + k < WIDTH) pn[i + k] |= (a.pn[i] << shift); } return *this; } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator>>=(unsigned int shift) { base_uint<BITS> a(*this); for (int i = 0; i < WIDTH; i++) pn[i] = 0; int k = shift / 32; shift = shift % 32; for (int i = 0; i < WIDTH; i++) { if (i - k - 1 >= 0 && shift != 0) pn[i - k - 1] |= (a.pn[i] << (32 - shift)); if (i - k >= 0) pn[i - k] |= (a.pn[i] >> shift); } return *this; } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator*=(uint32_t b32) { uint64_t carry = 0; for (int i = 0; i < WIDTH; i++) { uint64_t n = carry + (uint64_t)b32 * pn[i]; pn[i] = n & 0xffffffff; carry = n >> 32; } return *this; } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator*=(const base_uint& b) { base_uint<BITS> a = *this; *this = 0; for (int j = 0; j < WIDTH; j++) { uint64_t carry = 0; for (int i = 0; i + j < WIDTH; i++) { uint64_t n = carry + pn[i + j] + (uint64_t)a.pn[j] * b.pn[i]; pn[i + j] = n & 0xffffffff; carry = n >> 32; } } return *this; } template <unsigned int BITS> base_uint<BITS>& base_uint<BITS>::operator/=(const base_uint& b) { base_uint<BITS> div = b; // make a copy, so we can shift. base_uint<BITS> num = *this; // make a copy, so we can subtract. *this = 0; // the quotient. int num_bits = num.bits(); int div_bits = div.bits(); if (div_bits == 0) throw uint_error("Division by zero"); if (div_bits > num_bits) // the result is certainly 0. return *this; int shift = num_bits - div_bits; div <<= shift; // shift so that div and nun align. while (shift >= 0) { if (num >= div) { num -= div; pn[shift / 32] |= (1 << (shift & 31)); // set a bit of the result. } div >>= 1; // shift back. shift--; } // num now contains the remainder of the division. return *this; } template <unsigned int BITS> int base_uint<BITS>::CompareTo(const base_uint<BITS>& b) const { for (int i = WIDTH - 1; i >= 0; i--) { if (pn[i] < b.pn[i]) return -1; if (pn[i] > b.pn[i]) return 1; } return 0; } template <unsigned int BITS> bool base_uint<BITS>::EqualTo(uint64_t b) const { for (int i = WIDTH - 1; i >= 2; i--) { if (pn[i]) return false; } if (pn[1] != (b >> 32)) return false; if (pn[0] != (b & 0xfffffffful)) return false; return true; } template <unsigned int BITS> double base_uint<BITS>::getdouble() const { double ret = 0.0; double fact = 1.0; for (int i = 0; i < WIDTH; i++) { ret += fact * pn[i]; fact *= 4294967296.0; } return ret; } template <unsigned int BITS> std::string base_uint<BITS>::GetHex() const { char psz[sizeof(pn) * 2 + 1]; for (unsigned int i = 0; i < sizeof(pn); i++) sprintf(psz + i * 2, "%02x", ((unsigned char*)pn)[sizeof(pn) - i - 1]); return std::string(psz, psz + sizeof(pn) * 2); } template <unsigned int BITS> void base_uint<BITS>::SetHex(const char* psz) { memset(pn, 0, sizeof(pn)); // skip leading spaces while (isspace(*psz)) psz++; // skip 0x if (psz[0] == '0' && tolower(psz[1]) == 'x') psz += 2; // hex string to uint const char* pbegin = psz; while (::HexDigit(*psz) != -1) psz++; psz--; unsigned char* p1 = (unsigned char*)pn; unsigned char* pend = p1 + WIDTH * 4; while (psz >= pbegin && p1 < pend) { *p1 = ::HexDigit(*psz--); if (psz >= pbegin) { *p1 |= ((unsigned char)::HexDigit(*psz--) << 4); p1++; } } } template <unsigned int BITS> void base_uint<BITS>::SetHex(const std::string& str) { SetHex(str.c_str()); } template <unsigned int BITS> std::string base_uint<BITS>::ToString() const { return (GetHex()); } template <unsigned int BITS> std::string base_uint<BITS>::ToStringReverseEndian() const { char psz[sizeof(pn) * 2 + 1]; for (unsigned int i = 0; i < sizeof(pn); i++) sprintf(psz + i * 2, "%02x", ((unsigned char*)pn)[i]); return std::string(psz, psz + sizeof(pn) * 2); } template <unsigned int BITS> unsigned int base_uint<BITS>::bits() const { for (int pos = WIDTH - 1; pos >= 0; pos--) { if (pn[pos]) { for (int bits = 31; bits > 0; bits--) { if (pn[pos] & 1 << bits) return 32 * pos + bits + 1; } return 32 * pos + 1; } } return 0; } // Explicit instantiations for base_uint<160> template base_uint<160>::base_uint(const std::string&); template base_uint<160>::base_uint(const std::vector<unsigned char>&); template base_uint<160>& base_uint<160>::operator<<=(unsigned int); template base_uint<160>& base_uint<160>::operator>>=(unsigned int); template base_uint<160>& base_uint<160>::operator*=(uint32_t b32); template base_uint<160>& base_uint<160>::operator*=(const base_uint<160>& b); template base_uint<160>& base_uint<160>::operator/=(const base_uint<160>& b); template int base_uint<160>::CompareTo(const base_uint<160>&) const; template bool base_uint<160>::EqualTo(uint64_t) const; template double base_uint<160>::getdouble() const; template std::string base_uint<160>::GetHex() const; template std::string base_uint<160>::ToString() const; template void base_uint<160>::SetHex(const char*); template void base_uint<160>::SetHex(const std::string&); template unsigned int base_uint<160>::bits() const; // Explicit instantiations for base_uint<256> template base_uint<256>::base_uint(const std::string&); template base_uint<256>::base_uint(const std::vector<unsigned char>&); template base_uint<256>& base_uint<256>::operator<<=(unsigned int); template base_uint<256>& base_uint<256>::operator>>=(unsigned int); template base_uint<256>& base_uint<256>::operator*=(uint32_t b32); template base_uint<256>& base_uint<256>::operator*=(const base_uint<256>& b); template base_uint<256>& base_uint<256>::operator/=(const base_uint<256>& b); template int base_uint<256>::CompareTo(const base_uint<256>&) const; template bool base_uint<256>::EqualTo(uint64_t) const; template double base_uint<256>::getdouble() const; template std::string base_uint<256>::GetHex() const; template std::string base_uint<256>::ToString() const; template void base_uint<256>::SetHex(const char*); template void base_uint<256>::SetHex(const std::string&); template unsigned int base_uint<256>::bits() const; template std::string base_uint<256>::ToStringReverseEndian() const; // Explicit instantiations for base_uint<512> template base_uint<512>::base_uint(const std::string&); template base_uint<512>& base_uint<512>::operator<<=(unsigned int); template base_uint<512>& base_uint<512>::operator>>=(unsigned int); template std::string base_uint<512>::GetHex() const; template std::string base_uint<512>::ToString() const; template std::string base_uint<512>::ToStringReverseEndian() const; // This implementation directly uses shifts instead of going // through an intermediate MPI representation. uint256& uint256::SetCompact(uint32_t nCompact, bool* pfNegative, bool* pfOverflow) { int nSize = nCompact >> 24; uint32_t nWord = nCompact & 0x007fffff; if (nSize <= 3) { nWord >>= 8 * (3 - nSize); *this = nWord; } else { *this = nWord; *this <<= 8 * (nSize - 3); } if (pfNegative) *pfNegative = nWord != 0 && (nCompact & 0x00800000) != 0; if (pfOverflow) *pfOverflow = nWord != 0 && ((nSize > 34) || (nWord > 0xff && nSize > 33) || (nWord > 0xffff && nSize > 32)); return *this; } uint32_t uint256::GetCompact(bool fNegative) const { int nSize = (bits() + 7) / 8; uint32_t nCompact = 0; if (nSize <= 3) { nCompact = GetLow64() << 8 * (3 - nSize); } else { uint256 bn = *this >> 8 * (nSize - 3); nCompact = bn.GetLow64(); } // The 0x00800000 bit denotes the sign. // Thus, if it is already set, divide the mantissa by 256 and increase the exponent. if (nCompact & 0x00800000) { nCompact >>= 8; nSize++; } assert((nCompact & ~0x007fffff) == 0); assert(nSize < 256); nCompact |= nSize << 24; nCompact |= (fNegative && (nCompact & 0x007fffff) ? 0x00800000 : 0); return nCompact; } static void inline HashMix(uint32_t& a, uint32_t& b, uint32_t& c) { // Taken from lookup3, by Bob Jenkins. a -= c; a ^= ((c << 4) | (c >> 28)); c += b; b -= a; b ^= ((a << 6) | (a >> 26)); a += c; c -= b; c ^= ((b << 8) | (b >> 24)); b += a; a -= c; a ^= ((c << 16) | (c >> 16)); c += b; b -= a; b ^= ((a << 19) | (a >> 13)); a += c; c -= b; c ^= ((b << 4) | (b >> 28)); b += a; } static void inline HashFinal(uint32_t& a, uint32_t& b, uint32_t& c) { // Taken from lookup3, by Bob Jenkins. c ^= b; c -= ((b << 14) | (b >> 18)); a ^= c; a -= ((c << 11) | (c >> 21)); b ^= a; b -= ((a << 25) | (a >> 7)); c ^= b; c -= ((b << 16) | (b >> 16)); a ^= c; a -= ((c << 4) | (c >> 28)); b ^= a; b -= ((a << 14) | (a >> 18)); c ^= b; c -= ((b << 24) | (b >> 8)); } uint64_t uint256::GetHash(const uint256& salt) const { uint32_t a, b, c; a = b = c = 0xdeadbeef + (WIDTH << 2); a += pn[0] ^ salt.pn[0]; b += pn[1] ^ salt.pn[1]; c += pn[2] ^ salt.pn[2]; HashMix(a, b, c); a += pn[3] ^ salt.pn[3]; b += pn[4] ^ salt.pn[4]; c += pn[5] ^ salt.pn[5]; HashMix(a, b, c); a += pn[6] ^ salt.pn[6]; b += pn[7] ^ salt.pn[7]; HashFinal(a, b, c); return ((((uint64_t)b) << 32) | c); }
[ "ondoricoin@gmail.com" ]
ondoricoin@gmail.com
ccf36e8aa765719fd8e10a1e12b6a2ed7b325c38
c7ec870ad42a8ef1b4721e83f636d4533717d8a6
/src/pow.h
ca3c9572f7fa9de3d4c55e0b0ea79c18e1f10ddb
[ "MIT" ]
permissive
TheRinger/Atlascoin
dcdab93e74e151d62e1efc8f4bb35f3e7b2d72ac
21f6f2372e841fd3ba89e91086cbd5add3e4ef9b
refs/heads/master
2020-04-06T22:16:48.957176
2018-11-16T07:43:21
2018-11-16T07:43:21
157,830,789
0
0
null
null
null
null
UTF-8
C++
false
false
876
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Copyright (c) 2017 The Atlas Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef ATLAS_POW_H #define ATLAS_POW_H #include "consensus/params.h" #include <stdint.h> class CBlockHeader; class CBlockIndex; class uint256; unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params&); unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params&); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params&); #endif // ATLAS_POW_H
[ "tytek2012@gmail.com" ]
tytek2012@gmail.com
eb0ad822588ae222b138ca710aa386220ee23577
b11b140ef2fbb3e3e2d0eb53fdbe4c8943ad5ebb
/codeforces/768/C/c.cpp
e750e48f845de02ada7d6af9c0d665de133c3ec1
[]
no_license
jer22/OI
ea953208ab43542c51eada3c62ef529a6c14588e
545c2424f277a6626b0f22fb666edd8c37e7328b
refs/heads/master
2021-04-18T22:57:05.678732
2017-11-02T15:40:34
2017-11-02T15:40:34
27,431,322
1
0
null
null
null
null
UTF-8
C++
false
false
819
cpp
#include <bits/stdc++.h> using namespace std; int n, k, x; int cnt[2][1030]; int main() { freopen("c.in", "r", stdin); scanf("%d %d %d", &n, &k, &x); for (int i = 1, a; i <= n; i++) { scanf("%d", &a); cnt[0][a]++; } for (int f = 1; f <= k; f++) { int sum = 0; memset(cnt[f & 1], 0, sizeof(cnt[f & 1])); for (int i = 0; i <= 1023; i++) { cnt[f & 1][i] += cnt[f & 1 ^ 1][i]; if (sum & 1) { cnt[f & 1][i ^ x] += cnt[f & 1 ^ 1][i] >> 1; cnt[f & 1][i] -= cnt[f & 1 ^ 1][i] >> 1; } else { cnt[f & 1][i ^ x] += cnt[f & 1 ^ 1][i] + 1 >> 1; cnt[f & 1][i] -= cnt[f & 1 ^ 1][i] + 1 >> 1; } sum += cnt[f & 1 ^ 1][i]; } } int mx = 0, mi = 0x3f3f3f3f; for (int i = 0; i <= 1023; i++) if (cnt[k & 1][i]) mx = i, mi = min(mi, i); cout << mx << ' ' << mi << endl; return 0; }
[ "shijieyywd@gmail.com" ]
shijieyywd@gmail.com
52ed29e2197e78c1441b5b213a58f8d7c9a7344b
e3387b3831a2f20c9fcf7755842e12529777917d
/src/Engine/Memory/LinearAllocator.hpp
c191ef4301fc47b77ede5c0555c61f8966f6b667
[]
no_license
EdFil/Concept
9e976ae149d26530e4e8c3196100862fa5d3e322
a792c612e2f76e981f9d559ead3e79547f62052a
refs/heads/master
2021-01-24T02:05:01.054247
2018-02-25T12:25:20
2018-02-25T12:25:20
122,832,598
0
0
null
null
null
null
UTF-8
C++
false
false
386
hpp
#pragma once class LinearAllocator { public: LinearAllocator(void* memoryStart, size_t memorySize); ~LinearAllocator(); void init(void* memoryStart, size_t memorySize); void allocate(size_t chunkSize, const char* debugName); void free(void* memoryPointer); private: const void* _memoryStart; const size_t _memorySize; size_t _numAllocations = 0; size_t _usedMemory = 0; };
[ "edfil221@gmail.com" ]
edfil221@gmail.com
37475eb49b7a91173927b6cc2bffa56edf350818
cf60f12785be602adaec722edac56baaee46b26b
/lectures/10_templating_generalizability/exercises.cpp
8cdf13e2d8d54f43cbcf5bb5de4b5eba57d2920e
[ "MIT" ]
permissive
joshrymkiewicz/csci-3011
da9313713bb0ec8741a0924f2017fba873507102
1a7edf7d88baccdeec20d1b31b16f580e09afe4d
refs/heads/master
2022-04-01T00:13:02.926003
2019-12-03T17:36:16
2019-12-03T17:36:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,524
cpp
#include <iostream> #include <string> #include <vector> // Names: David Skrenta // // // 1) implement two functions, AddToValues(std::vector<int> v1, int v2) // and AddToValues(std::vector<double> v1, double v2) void AddToValues(std::vector<int> v1, int v2) { for (int i = 0; i < v1.size(); i++) { v1[i] += v2; } } void AddToValues(std::vector<double> v1, double v2) { for (int i = 0; i < v1.size(); i++) { v1[i] += v2; } } // 2) Do your AddToValues functions have return values? why/ why not? // Answer: Does not have return values because we are just modifying the passed vector int main() { // 3) Instantiate an int vector std::vector<int> intVector; // 4) call AddToValues, passing in your int vector and another int. AddToValues(intVector, 1); // 5) compile this file to object code (g++ -std=c++11 -Wall exercises.cpp -o exercises.o), // then run `nm -C exercises.o`. How many versions of the AddToValues function are in the // compiled object code? Copy + paste the relevant lines here: // // To making searching through the output easier, you can pipe the output of nm to grep // `nm -C exercises.o | grep "TextToFindHere"` // // If the -C flag isn't working, you can omit it and still complete the exercise--this flag // makes the output easier to read but isn't strictly necessary // There should be two compiled versions of AddToValues, one with a vector of ints and int as params, and one with a vector of doubles and a double }
[ "dskrenta@gmail.com" ]
dskrenta@gmail.com
54b2501df98b2eb9ccdd29e5cc88eb3d1e97ed9f
904441a3953ee970325bdb4ead916a01fcc2bacd
/src/sys/transm_models/csma_transmission_model.h
d0861b148f2dc65d4ec94a8bc9ddb83c99eb7e70
[ "MIT" ]
permissive
itm/shawn
5a75053bc490f338e35ea05310cdbde50401fb50
49cb715d0044a20a01a19bc4d7b62f9f209df83c
refs/heads/master
2020-05-30T02:56:44.820211
2013-05-29T13:34:51
2013-05-29T13:34:51
5,994,638
16
4
null
2014-06-29T05:29:00
2012-09-28T08:33:42
C++
UTF-8
C++
false
false
7,521
h
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #ifndef __SHAWN_SYS_TRANS_MODELS_CSMA_H #define __SHAWN_SYS_TRANS_MODELS_CSMA_H #include "sys/transmission_model.h" #include "sys/event_scheduler.h" #include <sys/misc/dynamic_node_array.h> #include "sys/transm_models/csma_transmission_model_message.h" #include <list> namespace shawn { /** @brief A CsmaTransmissionmodel senses the channel before it delivers a message. * This class implements the CSMA/CA transmission model. * A processor waits for the medium to be free before sending. * If a neighbor is already sending, the new message will be delayed until the end of * the transmission plus a backoff time * The parameters for this model are: * bandwith: the medium's bandwith in bits/sec * backoff: fixed (not variable) backoff in sec. * sending_jitter: defines the upperbound of the jitter that is use to simulate the "asynchronous behaviour" of the nodes. * sending_jitter_lb: defines the lower_bound of the sending jitter. * This module can be called by: * transm_model=csma bandwidth=9600 backoff=0.05 sending_jitter=0.02 sending_jitter_lb=0.001 */ class CsmaTransmissionModel : public TransmissionModel, public EventScheduler::EventHandler { public: //--------------------------------------------------------------------------- ///@name construction, destruction and support for life cycle ///@{ CsmaTransmissionModel(double short_inter_frame_spacing, double long_inter_frame_spacing, int max_short_inter_frame_spacing_size, int bandwidth, bool slotted_backoff, double backoff, int max_sending_attempts, int backoff_factor_base,int min_backoff_exponent, int max_backoff_exponent); ~CsmaTransmissionModel(); /** *@brief Initialize the csma transmission model * * Gets the list of neighbors */ virtual void init() throw(); /** *@brief Reset the csma transmission model * *Clear the statistic variables and set the parameters to its default value. */ virtual void reset() throw(); ///@} //--------------------------------------------------------------------------- ///@name Transmission Model Implementation ///@{ /** *@brief Mobility is depending on mobility support from the edge model * *The edge model is used to determine the 1-hop neighbours *which will receive the message */ virtual bool supports_mobility( void ) const throw(std::logic_error); /** *@brief Stores each message in a vector for delivery at the next simulation round start * *A new structure of csma_msg will be build and inserted into aired_messages_ *@see aired_messages_ */ virtual void send_message( MessageInfo& mi ) throw(); /** *@brief Delivers all messages which are in the vector * Method inherited from shawn::TransmissionModel. Is not implemented in this module since the messages are * added to the shawn::EventScheduler and do not have to be delivered at the beginning of a round. */ virtual void deliver_messages() throw(); ///@} //--------------------------------------------------------------------------- ///@name basic method inherited from EventHandler ///@{ /** * Timeout Event. Receives a csma_msg as a EventScheduler::EventTagHandle. * If message has not been sent yet, deliver() will be called. * Otherwise message has been transfered and will be deleted from sending processor's MessageList */ virtual void timeout(EventScheduler & event_scheduler, EventScheduler::EventHandle event_handle, double time, EventScheduler::EventTagHandle & event_tag_handle) throw(); ///@} private: ///@name Method which tests if medium is free ///@{ ///@name Delivers a message. /** * This method implements the CSMA/CA algorithm. * The processor listens if a neighbor is sending. * If no neighbor is sending, it will deliver its message, otherwise * it will delay the message to the end of the transmission plus a random backoff. *@param msg Pointer to the message to be send */ inline void start_send(csma_msg* msg) throw(); inline void end_send(csma_msg* msg) throw(); ///@} ///@name Methods in which a given node will receive a message ///@{ /** * This method delivers a message to a given node. * It has to check that the target is not receiving a message from a node which is not adjacent to the sender. * In this case the message will be dropped. *@param target Pointer to the target node *@param msg Pointer to the message to be send */ inline void start_receive(Node* target, csma_msg* msg) throw(); inline void end_receive(Node* target, csma_msg* msg) throw(); /** */ inline void handle_next_message(csma_msg *new_msg) throw(); ///@} ///Duration a short inter frame spacing (SIFS) double short_inter_frame_spacing_; ///Duration a long inter frame spacing (LIFS) double long_inter_frame_spacing_; /// maximum packet size of packets followed by a short inter frame spacing int max_short_inter_frame_spacing_size_; /// determines whether slotted or continouos backoff times are used. bool slotted_backoff_; ///Backoff that will be waited after a message has been delayed double backOff_; ///Bandwidth, defines the throughput int bandwidth_; /// EventHandle EventScheduler::EventHandle event_handle_; // Maximum number of attempts to send a message int max_sending_attempts_; //Factor specifying the base of the factor for increasing backoff int backoff_factor_base_; /// minimum backoff exponent (for first medium access) int min_backoff_exponent_; /// maximum backoff exponent int max_backoff_exponent_; ///The messages that have been sent by the nodes and are waiting for delivery typedef std::list<csma_msg*> MessageList; DECLARE_HANDLES(NodeInfo); /** * */ class NodeInfo : public EventScheduler::EventTag { public: NodeInfo (Node* n) : n_(n) {} Node* n_; }; class CsmaState { public: CsmaState(): outgoing_messages_(MessageList()), destinations_(std::set<Node*>()), current_message_(NULL), busy_until_(0), ifs_end_(0), busy_(false) {} MessageList outgoing_messages_; std::set<Node*> destinations_; csma_msg *current_message_; double busy_until_; double ifs_end_; bool busy_; }; /// List of nodes in transmission range. DynamicNodeArray<CsmaState>* nodes_; }; } #endif /*----------------------------------------------------------------------- * Source $Source: /cvs/shawn/shawn/sys/transm_models/csma_transmission_model.h,v $ * Version $Revision: 38 $ * Date $Date: 2007-06-08 14:30:12 +0200 (Fr, 08 Jun 2007) $ *----------------------------------------------------------------------- * $Log: csma_transmission_model.h,v $ *-----------------------------------------------------------------------*/
[ "github@farberg.de" ]
github@farberg.de
263615d5b4fef34ad04365a56591803d2d877ab3
6767be84c4ffa16f0c1930c7b8c34c28f2c96dd2
/fipa_cal/Performatives.cpp
0996a4724964cd7e33886207a6b442447b872065
[]
no_license
hdd-robot/gAgent
6d47b597c24c09c6bbc88572023c2decce99173e
b8c3703965fa8a1671ae985b1de127389d11c007
refs/heads/master
2022-01-16T12:11:04.105880
2019-05-18T09:46:44
2019-05-18T09:46:44
95,297,136
2
0
null
null
null
null
UTF-8
C++
false
false
1,425
cpp
/* * Performatives.cpp * * Created on: 22 mai 2018 * Author: Halim Djerroud */ #include "Performatives.h" namespace fipa_cal { const std::string Performatives::ACCEPT_PROPOSAL = "accept-proposal"; const std::string Performatives::AGREE = "agree"; const std::string Performatives::CANCEL = "cancel"; const std::string Performatives::CFP = "cfp"; const std::string Performatives::CONFIRM = "confirm"; const std::string Performatives::DISCONFIRM = "disconfirm"; const std::string Performatives::FAILURE = "failure"; const std::string Performatives::INFORM = "inform"; const std::string Performatives::INFORM_IF = "inform-if"; const std::string Performatives::INFORM_REF = "inform-ref"; const std::string Performatives::NOT_UNDERSTOOD = "not-understood"; const std::string Performatives::PROPAGATE = "propagate"; const std::string Performatives::PROPOSE = "propose"; const std::string Performatives::PROXY = "proxy"; const std::string Performatives::QUERY_REF = "query-ref"; const std::string Performatives::REFUSE = "refuse"; const std::string Performatives::REJECT_PROPOSAL = "reject-proposal"; const std::string Performatives::REQUEST = "request"; const std::string Performatives::REQUEST_WHEN = "request-when"; const std::string Performatives::REQUEST_WHENEXER = "request-whenever"; const std::string Performatives::SUBSCRIBE = "subscribe"; } /* namespace fipa_cal */
[ "hdd@ai.univ-paris8.fr" ]
hdd@ai.univ-paris8.fr
7a1280aac835cd29f72fc1f67c45e36c3301e9b4
08dc60703f7c9ee04ebcc07aa9e0684eecb026e0
/src/k_means_ui/renderer.cpp
14a1214f926b86223497ac641182039bd215e81a
[]
no_license
oussama1598/k_means_implementation
6d7966471ef3c6ffc4a1d3e67564dcf020cb6d63
4453c32ccbf58bb1b33ad2e6e9559a1870d11ad5
refs/heads/main
2023-02-08T07:45:09.028301
2021-01-05T02:19:23
2021-01-05T02:19:23
326,834,486
0
0
null
null
null
null
UTF-8
C++
false
false
2,050
cpp
#include "renderer.h" Renderer::Renderer() { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) throw std::runtime_error(SDL_GetError()); _window = SDL_CreateWindow( _title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (int) _width, _height, SDL_WINDOW_ALLOW_HIGHDPI ); if (_window == nullptr) throw std::runtime_error("Could not create a _window"); _renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_PRESENTVSYNC); if (_renderer == nullptr) throw std::runtime_error("Could not create a renderer"); _running = true; } Renderer::~Renderer() { SDL_DestroyRenderer(_renderer); SDL_DestroyWindow(_window); SDL_Quit(); } void Renderer::_handle_mouse_press_up(SDL_MouseButtonEvent &event) { if (event.button == SDL_BUTTON_RIGHT) { _points.push_back({event.x, event.y}); } } void Renderer::_handle_events() { SDL_Event event; SDL_PollEvent(&event); switch (event.type) { case SDL_QUIT: _running = false; break; case SDL_MOUSEBUTTONUP: _handle_mouse_press_up(event.button); break; } } void Renderer::render() { _handle_events(); _kmeans.tick(); SDL_SetRenderDrawColor(_renderer, 0, 0, 0, 255); SDL_RenderClear(_renderer); for (auto &point: _points) { SDL_Color &color = _colors[point.centroid]; SDL_Rect rect = {point.x, point.y, 10, 10}; SDL_SetRenderDrawColor(_renderer, color.r, color.g, color.b, color.a); SDL_RenderFillRect(_renderer, &rect); } SDL_SetRenderDrawColor(_renderer, 0, 0, 255, 255); for (auto &centroid: _kmeans.get_centroids()) { SDL_Color &color = _colors[centroid.id]; SDL_Rect rect = {centroid.x, centroid.y, 10, 10}; SDL_SetRenderDrawColor(_renderer, color.r, color.g, color.b, color.a); SDL_RenderDrawRect(_renderer, &rect); } SDL_RenderPresent(_renderer); }
[ "oussama1598@gmail.com" ]
oussama1598@gmail.com
127a1241d23b9e509c4d764fca5dacd69ebcb443
039a30b5db53c7f828ea87b9f305f51be4d7e6cc
/模板/数据结构/单点最值线段树.cpp
f4520ca0aa457a2fa3faba5dd9774b98fe8af485
[]
no_license
1092772959/My-ACM-code
cd5af7cebc04c3252ed880686759257237b63b34
87109a0a98e6ea49f8726927cc4357a9155ba3f2
refs/heads/master
2021-07-03T01:31:39.173353
2020-08-25T13:48:49
2020-08-25T13:48:49
151,587,646
0
0
null
null
null
null
UTF-8
C++
false
false
1,330
cpp
#include<bits/stdc++.h> using namespace std; const int maxn =1e5+5; const int INF =0x3f3f3f3f; struct SGnode{ int mx,mn; }tree[maxn<<4]; void pushup(int root){ tree[root].mx =max(tree[root<<1].mx,tree[root<<1|1].mx); tree[root].mn =min(tree[root<<1].mn,tree[root<<1|1].mn); } void build(int root,int L,int R){ if(L==R){ tree[L].mx=tree[L].mn=0; return; } int mid =(L+R)>>1; build(root<<1,L,mid); build(root<<1|1,mid+1,R); pushup(root); } void update(int root,int L,int R,int pos,int val) { if(L==R && L==pos){ tree[root].mx =tree[root].mn= val; return; } int mid=(L+R)>>1; if(pos<=mid) update(root<<1,L,mid,pos,val); else update(root<<1|1,mid+1,R,pos,val); pushup(root); } int getmax(int root,int l,int r,int L,int R) { if(L<=l&&r<=R) return tree[root].mx; int mid=(l+r)>>1,res=0; if(L<=mid) res=max(res,getmax(root<<1,l,mid,L,R)); if(mid<R) res=max(res,getmax(root<<1|1,mid+1,r,L,R)); return res; } int getmin(int root,int l,int r,int L,int R) { if(L<=l&&r<=R) return tree[root].mn; int mid=(l+r)>>1,res=INF; if(L<=mid) res=min(res,getmin(root<<1,l,mid,L,R)); if(mid<R) res=min(res,getmin(root<<1|1,mid+1,r,L,R)); return res; }
[ "32030091+1092772959@users.noreply.github.com" ]
32030091+1092772959@users.noreply.github.com
fb96745b8fec7c6d23ce1c318d730ed3a5ae2a37
944b5734f9c0bb3cc7cd314b3960e9081f917025
/src/camera.cpp
a202a6f93e4351c79a76f107cabde4582467b2be
[]
no_license
Grieverheart/SimpleGameEngine
461bc5e0d3c85977057b466a59c5952b1c1e71b4
e6233066c592fc84636aa55132c2c64738b20fcd
refs/heads/master
2020-05-18T19:32:32.305571
2013-03-19T11:04:57
2013-03-19T11:04:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,155
cpp
#include "include/camera.h" #include "include/components.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_access.hpp> Camera::Camera(float aspect, const glm::vec3& pos, float angle, const glm::vec3& axis, eProjection mode): projection_mode_(mode), isMimicking_(false), isFollowing_(false), isProjectionChanged_(false), pos_(pos), rotation_(glm::angleAxis(angle, axis)), zn_(1.0f), zf_(100.0f), fov_(60.0f), aspect_(aspect), ortho_height_(10.0f), followee_(nullptr) { view_matrix_ = glm::translate(glm::mat4(1.0), pos_) * glm::mat4_cast(rotation_); view_matrix_ = glm::inverse(view_matrix_); if(mode == Perspective){ projection_matrix_ = glm::perspective(fov_, aspect_, zn_, zf_); } else{ projection_matrix_ = glm::ortho(-aspect_ * ortho_height_ * 0.5f, aspect_ * ortho_height_ * 0.5f, -ortho_height_ * 0.5f, ortho_height_ * 0.5f, zn_, zf_); } } Camera::~Camera(void){ } void Camera::updateView(void){ if(isFollowing_){ TransformComponent* transformation = followee_->getComponent<TransformComponent>(); glm::fquat rotation = transformation->getRotation() * rotation_; // glm::vec3 pos = pos_ + transformation->getPosition(); view_matrix_ = glm::translate(glm::mat4(1.0), transformation->getPosition()) * glm::mat4_cast(rotation) * glm::translate(glm::mat4(1.0), pos_); } else if(isMimicking_){ glm::vec3 pos = pos_ + followee_->getComponent<TransformComponent>()->getPosition(); view_matrix_ = glm::translate(glm::mat4(1.0), pos) * glm::mat4_cast(rotation_); } else{ view_matrix_ = glm::translate(glm::mat4(1.0), pos_) * glm::mat4_cast(rotation_); } view_matrix_ = glm::inverse(view_matrix_); } void Camera::rotate(float angle, const glm::vec3& axis){ rotation_ = glm::rotate(rotation_, angle, axis); } void Camera::setRotation(float angle, const glm::vec3& axis){ rotation_ = glm::rotate(rotation_, angle, axis); } void Camera::setPosition(const glm::vec3& pos){ this->pos_ = pos; } void Camera::translate(const glm::vec3& trans){ pos_ += trans; } const glm::mat4& Camera::getViewMatrix(void)const{ return view_matrix_; } void Camera::setProjectionParams(float aspect, float fov_ortho_h, float zn, float zf){ aspect_ = aspect; if(zn > 0.0f) zn_ = zn; if(zf > 0.0f) zf_ = zf; if(fov_ortho_h > 0.0f){ if(projection_mode_ == Perspective) fov_ = fov_ortho_h; else ortho_height_ = fov_ortho_h; } isProjectionChanged_ = true; } void Camera::setProjectionMode(eProjection mode){ projection_mode_ = mode; isProjectionChanged_ = true; } const glm::mat4& Camera::getProjectionMatrix(void){ if(isProjectionChanged_){ if(projection_mode_ == Perspective){ projection_matrix_ = glm::perspective(fov_, aspect_, zn_, zf_); } else{ projection_matrix_ = glm::ortho(-aspect_ * ortho_height_ * 0.5f, aspect_ * ortho_height_ * 0.5f, -ortho_height_ * 0.5f, ortho_height_ * 0.5f, zn_, zf_); } isProjectionChanged_ = false; } return projection_matrix_; } void Camera::followEntity(SES::Entity* entity){ isFollowing_ = true; followee_ = entity; } void Camera::unfollow(void){ isFollowing_ = false; } void Camera::mimicEntity(bool val){ isMimicking_ = val; }
[ "nicktasios@gmail.com" ]
nicktasios@gmail.com
af6ab6df4ae077bb1a9532bf272a1d2c5308593d
ad97897726d28b30ee145b044a3a5bace065119d
/src/IcosphereStore.h
ec701f932b9fc95bf7c1b250716419faf9099508
[]
no_license
Zowlyfon/Gravity-Smash
6c21fc83ba2fa9c9bee3ff61c0f48806f8f85b5c
45ac78f593278b26f2d7ba94209f7c4213372d44
refs/heads/main
2023-02-16T11:13:05.505797
2021-01-18T12:38:53
2021-01-18T12:38:53
316,482,204
0
0
null
null
null
null
UTF-8
C++
false
false
546
h
// // Created by zowlyfon on 26/11/2020. // #ifndef GAMEENGINE_ICOSPHERESTORE_H #define GAMEENGINE_ICOSPHERESTORE_H #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <vector> #include <map> class IcosphereStore { public: IcosphereStore(); ~IcosphereStore(); std::vector<glm::vec4> getIcosphere(unsigned int subs); private: std::map<unsigned int, std::vector<glm::vec4>> icospheres; }; #endif //GAMEENGINE_ICOSPHERESTORE_H
[ "drew@zowlyfon.net" ]
drew@zowlyfon.net
5dcaef64d1afeafcc0a08904a677ef09812aa4d9
4edd72f7d77e42b94cbcfdd07b0996408313b727
/cmdparse/SyncSystemEvent.h
0bf679abaaadc3156b34683b354b930ae230cb9d
[]
no_license
jerryxiee/trunk
e4f6a751bf289a63ae84c0fcb153f037a2f3b555
efe4cc168a3af52c44ee9ea57c78a31bba0f0fbf
refs/heads/main
2023-02-10T02:53:09.146507
2021-01-08T07:24:10
2021-01-08T07:24:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
636
h
// // Created by 何继胜 on 2017/4/24. // #ifndef OSLA_NEW_SYNCSYSTEMEVENT_H #define OSLA_NEW_SYNCSYSTEMEVENT_H #include <protobuf/message.pb.h> #include "object/BaseObjectExt.h" class SyncSystemEvent : public BaseObjectExt { public: SyncSystemEvent(std::string name = "SyncSystemEvent"); ~SyncSystemEvent(); bool createRequest(BaseObject *dataIn, BaseObject *dataOut); bool parseRequset(BaseObject *dataIn, BaseObject *dataOut); bool parseRespose(BaseObject *dataIn, BaseObject *dataOut); void reset(); private: biotech::osla::SystemEventList systemEventList; }; #endif //OSLA_NEW_SYNCSYSTEMEVENT_H
[ "macian@foxmail.com" ]
macian@foxmail.com
66a859c64b678218eb5eee73ea68a91107d6c470
1095cfe2e29ddf4e4c5e12d713bd12f45c9b6f7d
/src/systemc/tests/systemc/misc/stars/star114203/test.cpp
eeecc1fc51caa26efafd4c683b94fc3cd735d228
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "LGPL-2.0-or-later", "MIT" ]
permissive
gem5/gem5
9ec715ae036c2e08807b5919f114e1d38d189bce
48a40cf2f5182a82de360b7efa497d82e06b1631
refs/heads/stable
2023-09-03T15:56:25.819189
2023-08-31T05:53:03
2023-08-31T05:53:03
27,425,638
1,185
1,177
BSD-3-Clause
2023-09-14T08:29:31
2014-12-02T09:46:00
C++
UTF-8
C++
false
false
2,866
cpp
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** test.cpp -- Original Author: Martin Janssen, Synopsys, Inc., 2002-02-15 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ /* Dec/5/00 ulrich The constructor of an sc_biguint with an sc_bv as an argument does not compile. That happens with SystemC 1.0.1 on Solaris with both SC5.0 and gcc. */ #include <systemc.h> int sc_main(int argc, char* arg[]) { sc_bv<10> bv10 = "0000111100"; sc_bigint<10> bi10; sc_biguint<10> bu10; // works fine bi10 = sc_bigint<10> (bv10); // causes errors on g++, SC5.0 : // g++ : // .../include/numeric_bit/sc_biguint.h: // In method `sc_biguint<10>::sc_biguint(const sc_bv_ns::sc_bv<10> &)': // str.cc:10: instantiated from here // .../include/numeric_bit/sc_biguint.h:186: type `sc_signed' // is not a base type for type `sc_biguint<10>' // .../include/numeric_bit/sc_unsigned.h:1365: // `sc_unsigned::sc_unsigned()' is private // .../include/numeric_bit/sc_biguint.h:186: within this context // SC5.0: // ".../include/numeric_bit/sc_biguint.h", line 186: // Error: sc_signed is not a direct base class of sc_biguint<10>. // ".../include/numeric_bit/sc_biguint.h", line 187: // Error: sc_unsigned::sc_unsigned() is not accessible from . bu10 = sc_biguint<10>(bv10); cout << bv10.to_string() << endl; cout << bi10.to_string(SC_BIN) << endl; cout << bu10.to_string(SC_BIN) << endl; return 0; }
[ "gabeblack@google.com" ]
gabeblack@google.com
ee6db55e05c4318b0f0de6408a7bddc49817f31f
408ff1485a02b30d2a54a264f8e7774981ea7c62
/Diagram.cpp
e5bd664160d9e11e72ca29dd6271818b65174236
[]
no_license
MRVolta-Ivan/Unit-tests
52c3e0a50c06adb9b63a8cc915b8d0f797fdeb6c
ef865589b9c3dd9f3f5265a75b38732050fe6569
refs/heads/master
2023-03-21T22:01:31.394219
2021-03-17T08:14:48
2021-03-17T08:14:48
348,623,867
0
0
null
null
null
null
UTF-8
C++
false
false
24,422
cpp
#include "Diagram.h" Diagram::Diagram(Scaner *s, Tree* _tree) { sc = s; root = _tree; } Diagram::~Diagram() { } void Diagram::Program() //Программа. { int type; string lexem = ""; type = sc->Scan(lexem); if (type != Tpublic) PrintError("Ожидалось public.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != Tclass) PrintError("Ожидалось class.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != TMain) PrintError("Ожидалось Main.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != TopenBrace) PrintError("Ожидался символ {.", sc->GetLine() + 1, sc->GetUKfromStartString()); int uk = sc->GetUK(); int line = sc->GetLine(); type = sc->Scan(lexem); sc->PutLine(line); sc->PutUK(uk); //Одно описание. Мы попадаем на одно описание, если следующее int, short, long, boolean. while (type >= Tint && type <= Tboolean) { OneDescription(true); uk = sc->GetUK(); line = sc->GetLine(); type = sc->Scan(lexem); sc->PutUK(uk); sc->PutLine(line); } Function(); type = sc->Scan(lexem); if (type != TcloseBrace) PrintError("Ожидался символ }.", sc->GetLine() + 1, sc->GetUKfromStartString()); } void Diagram::Function() //Функция. { int type; string lexem = ""; type = sc->Scan(lexem); if (type != Tpublic) PrintError("Ожидалось public.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != Tstatic) PrintError("Ожидалось static.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != Tvoid) PrintError("Ожидалось void.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != Tmain) PrintError("Ожидалось main.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != TopenBracket) PrintError("Ожидался символ (.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != TcloseBracket) PrintError("Ожидался символ ).", sc->GetLine() + 1, sc->GetUKfromStartString()); CompoundOperator(); } void Diagram::CompoundOperator() //Составной оператор. { int type; string lexem = ""; type = sc->Scan(lexem); if (type != TopenBrace) PrintError("Ожидался символ {.", sc->GetLine() + 1, sc->GetUKfromStartString()); Tree* save = root->GetCur(); root->SemInclude(); //Создаём пустую вершину справа от текущего узла. int uk = sc->GetUK(); int line = sc->GetLine(); type = sc->Scan(lexem); sc->PutUK(uk); sc->PutLine(line); //Одно описание или Оператор. cout << "Данные перед входом в блок:" << endl; root->GetCur()->PrintDetail(); cout << endl << endl; while (type != TcloseBrace && type < Terror) { if (type >= Tint && type <= Tboolean) OneDescription(false); else Operator(); uk = sc->GetUK(); line = sc->GetLine(); type = sc->Scan(lexem); sc->PutUK(uk); sc->PutLine(line); } type = sc->Scan(lexem); if (type != TcloseBrace) PrintError("Ожидался символ }.", sc->GetLine() + 1, sc->GetUKfromStartString()); cout << "Данные после выхода из блока:" << endl; root->GetCur()->PrintDetail(); cout << endl << endl; root->SetCur(save); } void Diagram::OneDescription(bool field) //Одно описание. { int type; string lexem = ""; type = TypeData(); int typeVar = type; //Запоминаем тип переменных. do { Variable(typeVar, field); type = sc->Scan(lexem); } while (type == Tcomma); if (type != Tsemi) PrintError("Ожидался символ ;.", sc->GetLine() + 1, sc->GetUKfromStartString()); } int Diagram::TypeData() //Тип данных. { int type; string lexem = ""; type = sc->Scan(lexem); if (!(type >= Tint && type <= Tboolean)) PrintError("Ожидался тип данных: int, short, long, boolean.", sc->GetLine() + 1, sc->GetUKfromStartString()); return type; } void Diagram::Variable(int typeData, bool field) //Переменная. { int type; string lexem = ""; type = sc->Scan(lexem); if (type != Tident) PrintError("Ожидался идентификатор.", sc->GetLine() + 1, sc->GetUKfromStartString()); string nameIdent = lexem; //Запоминаем имя переменной. int uk = sc->GetUK(); int line = sc->GetLine(); type = sc->Scan(lexem); DataValue value; if (typeData == Tint) value.dataAsInt = 0; else value.dataAsBoolean = false; //Заносим переменную в дерево. root->SemInclude(nameIdent, typeData, value, field, false, 0, {}); //Инициализация переменной. if (type == Teval) { Node* node = Expression(); root->SetInit(node); //устанавливаем признак инициализации. cout << "Инициализация:" << endl; root->GetCur()->PrintDetail(); cout << endl << endl; } //Создание массива. else if (type == TopenSquareBracket) { int countDim = 1; //Начинаем считать количество измерений у массива. type = sc->Scan(lexem); if (type != TcloseSquareBracket) PrintError("Ожидался символ ].", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); while (type == TopenSquareBracket) { countDim++; type = sc->Scan(lexem); if (type != TcloseSquareBracket) PrintError("Ожидался символ ].", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); } root->SetNumDimension(countDim); //Устанавливаем кол-во измерений. if (type != Teval) PrintError("Ожидался символ =.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != Tnew) PrintError("Ожидалось new.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = TypeData(); Node* node = new Node(); if (type == Tint) node->type = DataType::IINT; else node->type = DataType::BBOOLEAN; vector<int> dim = ArraySize(); //Устанавливаем начало массива. int allSize = 1; for (int i = 0; i < dim.size(); i++) { allSize *= dim[i]; } if (typeData == Tint) { int* arr = new int[allSize]; for (int i = 0; i < allSize; i++) arr[i] = 0; node->value.addrAsInt = arr; } else { bool* arr = new bool[allSize]; for (int i = 0; i < allSize; i++) arr[i] = false; node->value.addrAsBoolean = arr; } root->SetDimension(dim); //Устанавливаем сами измерения. root->SetInit(node); cout << "Инициализация массива:" << endl; root->GetCur()->PrintDetail(); cout << endl << endl; } else { sc->PutUK(uk); sc->PutLine(line); } } vector<int> Diagram::ArraySize() //Размер массива. { int type; string lexem = ""; int uk, line; vector<int> dim; do { type = sc->Scan(lexem); if (type != TopenSquareBracket) PrintError("Ожидался символ [.", sc->GetLine() + 1, sc->GetUKfromStartString()); dim.push_back(Constant()); type = sc->Scan(lexem); if (type != TcloseSquareBracket) PrintError("Ожидался символ ].", sc->GetLine() + 1, sc->GetUKfromStartString()); uk = sc->GetUK(); line = sc->GetLine(); type = sc->Scan(lexem); sc->PutUK(uk); sc->PutLine(line); } while (type == TopenSquareBracket); return dim; // } void Diagram::Operator() //Оператор. { int type; string lexem = ""; int uk = sc->GetUK(); int line = sc->GetLine(); type = sc->Scan(lexem); //Присваивание. if (type == Tident) { sc->PutUK(uk); sc->PutLine(line); Assignment(); type = sc->Scan(lexem); if (type != Tsemi) PrintError("Ожидался символ ;.", sc->GetLine() + 1, sc->GetUKfromStartString()); } //Оператор break. else if (type == Tbreak) { type = sc->Scan(lexem); if (type != Tsemi) PrintError("Ожидался символ ;.", sc->GetLine() + 1, sc->GetUKfromStartString()); } //Switch. else if (type == Tswitch) { sc->PutUK(uk); sc->PutLine(line); Switch(); } //Составной оператор. else if (type == TopenBrace) { sc->PutUK(uk); sc->PutLine(line); CompoundOperator(); } //Проверяем пустой оператор. else if (type != Tsemi) PrintError("Ожидался символ ;.", sc->GetLine() + 1, sc->GetUKfromStartString()); } void Diagram::Assignment() //Присваивание. { int type; string lexem = ""; Node* nodename = Name(); type = sc->Scan(lexem); if (type != Teval) PrintError("Ожидался символ =.", sc->GetLine() + 1, sc->GetUKfromStartString()); Node* original; original = root->SemGetVar(nodename->lexem, nodename->numberDimension)->GetNode(); Node* node = Expression(); if (original->type != node->type) root->PrintError("Не соответствие типов",nodename->lexem); if (original->numberDimension == 0) original->value = node->value; else { if (original->type == DataType::IINT) *(nodename->value.addrAsInt) = node->value.dataAsInt; else *(nodename->value.addrAsBoolean) = node->value.dataAsBoolean; } cout << "Присваивание:" << endl; root->GetCur()->PrintDetail(); cout << endl << endl; } void Diagram::Switch() //Switch. { int type; string lexem = ""; type = sc->Scan(lexem); if (type != Tswitch) PrintError("Ожидалось switch.", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != TopenBracket) PrintError("Ожидался символ (.", sc->GetLine() + 1, sc->GetUKfromStartString()); Node* node = Expression(); type = sc->Scan(lexem); if (type != TcloseBracket) PrintError("Ожидался символ ).", sc->GetLine() + 1, sc->GetUKfromStartString()); type = sc->Scan(lexem); if (type != TopenBrace) PrintError("Ожидался символ {.", sc->GetLine() + 1, sc->GetUKfromStartString()); Case(); type = sc->Scan(lexem); if (type != TcloseBrace) PrintError("Ожидался символ }.", sc->GetLine() + 1, sc->GetUKfromStartString()); } void Diagram::Case() //Case. { int type; string lexem = ""; int uk = sc->GetUK(); int line = sc->GetLine(); type = sc->Scan(lexem); //Несколько Case. while (type == Tcase) { Constant(); type = sc->Scan(lexem); if (type != Tcolon) PrintError("Ожидался символ :.", sc->GetLine() + 1, sc->GetUKfromStartString()); MultipleOperators(); uk = sc->GetUK(); line = sc->GetLine(); type = sc->Scan(lexem); } //default. if (type == Tdefault) { type = sc->Scan(lexem); if (type != Tcolon) PrintError("Ожидался символ :.", sc->GetLine() + 1, sc->GetUKfromStartString()); MultipleOperators(); } //Без default. else if (type == TcloseBrace) { sc->PutUK(uk); sc->PutLine(line); } else PrintError("Ожидалось case или default.", sc->GetLine() + 1, sc->GetUKfromStartString()); } void Diagram::MultipleOperators() //Несколько операторов. { int type; string lexem = ""; int uk = sc->GetUK(); int line = sc->GetLine(); type = sc->Scan(lexem); sc->PutUK(uk); sc->PutLine(line); while (type != Tcase && type != Tdefault && type != TcloseBrace && type != Terror && type != Tend) { Operator(); uk = sc->GetUK(); line = sc->GetLine(); type = sc->Scan(lexem); sc->PutUK(uk); sc->PutLine(line); } } Node* Diagram::Name() //Имя. { int type; string lexem = ""; type = sc->Scan(lexem); if (type != Tident) PrintError("Ожидался идентификатор.", sc->GetLine() + 1, sc->GetUKfromStartString()); string nameident = lexem; //Запоминаем имя. int uk = sc->GetUK(); int line = sc->GetLine(); type = sc->Scan(lexem); int numDim = 0; //Считаем кол-во измерений. vector<int> dim; //Скобки массива. while (type == TopenSquareBracket) { numDim++; Node* node = Expression(); //Проверяем что возвращаемое значение типа INT. if (node->type != DataType::IINT) root->PrintError("В скобках массива выражение неверного типа", nameident); dim.push_back(node->value.dataAsInt); type = sc->Scan(lexem); if (type != TcloseSquareBracket) PrintError("Ожидался символ ].", sc->GetLine() + 1, sc->GetUKfromStartString()); uk = sc->GetUK(); line = sc->GetLine(); type = sc->Scan(lexem); } sc->PutUK(uk); sc->PutLine(line); //Проверяем наличие переменной или массива в дереве. Node* node2 = root->SemGetVar(nameident, numDim, dim)->GetNode(); Node* result = new Node(); result->typenode = node2->typenode; result->lexem = node2->lexem; result->numberDimension = node2->numberDimension; result->type = node2->type; result->dimension = dim; if (numDim > 0) { int index = 0; for (int i = 0; i < dim.size() - 1; i++) { index += dim[i]; index *= node2->dimension[i + 1]; } index += dim[dim.size() - 1]; if (node2->type == DataType::IINT) { int * arr = node2->value.addrAsInt; result->value.addrAsInt = arr + index; } else { bool* arr = node2->value.addrAsBoolean; result->value.addrAsBoolean = arr + index; } } else result->value = node2->value; return result; } Node* Diagram::Expression() //Выражение. { int type; string lexem = ""; Node* node = Inequality(); int uk = sc->GetUK(); int line = sc->GetLine(); int operation = type = sc->Scan(lexem); while (type == Tuneq || type == Teq) { Node* node2; node2 = Inequality(); uk = sc->GetUK(); line = sc->GetLine(); //Проверка типов. if (node->type != node2->type) { root->PrintError("Не соответствует типы", node->lexem); } else //Выполнение операций неравенства и равенства. { if (operation == Tuneq) { if (node->type == DataType::BBOOLEAN) node->value.dataAsBoolean = node->value.dataAsBoolean != node2->value.dataAsBoolean; else { node->value.dataAsBoolean = node->value.dataAsInt != node2->value.dataAsInt; } } else { if (node->type == DataType::BBOOLEAN) node->value.dataAsBoolean = node->value.dataAsBoolean == node2->value.dataAsBoolean; else { node->value.dataAsBoolean = node->value.dataAsInt == node2->value.dataAsInt; } } node->type = DataType::BBOOLEAN; node->typenode = TypeNode::CCONSTANT; } operation = type = sc->Scan(lexem); } sc->PutUK(uk); sc->PutLine(line); return node; } Node* Diagram::Inequality() //Неравенство. { int type; string lexem = ""; Node* node = Addendum(); int uk = sc->GetUK(); int line = sc->GetLine(); int operation = type = sc->Scan(lexem); while (type == Tless || type == Tmore || type == TmoreOrEq || type == TlessOrEq) { Node* node2; node2 = Addendum(); uk = sc->GetUK(); line = sc->GetLine(); //Проверка типов. if (node->type != DataType::IINT || node2->type != DataType::IINT) { if (node->type != DataType::IINT) root->PrintError("Не соответствует типу int", node->lexem); else root->PrintError("Не соответствует типу int", node2->lexem); } else //Выполнение операций меньше, больше, больше и равно, меньше и равно. { if (operation == Tless) { node->value.dataAsBoolean = node->value.dataAsInt < node2->value.dataAsInt; } else if (operation == Tmore) { node->value.dataAsBoolean = node->value.dataAsInt > node2->value.dataAsInt; } else if (operation == TmoreOrEq) { node->value.dataAsBoolean = node->value.dataAsInt >= node2->value.dataAsInt; } else { node->value.dataAsBoolean = node->value.dataAsInt <= node2->value.dataAsInt; } node->type = DataType::BBOOLEAN; node->typenode = TypeNode::CCONSTANT; } operation = type = sc->Scan(lexem); } sc->PutUK(uk); sc->PutLine(line); return node; } Node* Diagram::Addendum() //Слагаемое. { int type; string lexem = ""; Node* node = Multiplier(); int uk = sc->GetUK(); int line = sc->GetLine(); int operation = type = sc->Scan(lexem); while (type == Tminus || type == Tplus) { Node* node2; node2 = Multiplier(); uk = sc->GetUK(); line = sc->GetLine(); //Проверка типов. if (node->type != DataType::IINT || node2->type != DataType::IINT) { if (node->type != DataType::IINT) root->PrintError("Не соответствует типу int", node->lexem); else root->PrintError("Не соответствует типу int", node2->lexem); } else //Выполнение операций плюс и минус. { if (operation == Tminus) { node->value.dataAsInt = node->value.dataAsInt - node2->value.dataAsInt; } else { node->value.dataAsInt = node->value.dataAsInt + node2->value.dataAsInt; } node->type = DataType::IINT; node->typenode = TypeNode::CCONSTANT; } operation = type = sc->Scan(lexem); } sc->PutUK(uk); sc->PutLine(line); return node; } Node* Diagram::Multiplier() //Множитель. { int type; string lexem = ""; Node* node = Prefix(); int uk = sc->GetUK(); int line = sc->GetLine(); int operation = type = sc->Scan(lexem); while (type == Tremain || type == Tdiv || type == Tmul) { Node* node2; node2 = Prefix(); uk = sc->GetUK(); line = sc->GetLine(); //Проверка типов. if (node->type != DataType::IINT || node2->type != DataType::IINT) { if (node->type != DataType::IINT) root->PrintError("Не соответствует типу int", node->lexem); else root->PrintError("Не соответствует типу int", node2->lexem); } else //Выполнение операций умножить, делить и остаток. { if (operation == Tremain) { node->value.dataAsInt = node->value.dataAsInt % node2->value.dataAsInt; } else if (operation == Tdiv) { node->value.dataAsInt = node->value.dataAsInt / node2->value.dataAsInt; } else { node->value.dataAsInt = node->value.dataAsInt * node2->value.dataAsInt; } node->type = DataType::IINT; node->typenode = TypeNode::CCONSTANT; } operation = type = sc->Scan(lexem); } sc->PutUK(uk); sc->PutLine(line); return node; } Node* Diagram::Prefix() //Префикс. { int type; string lexem = ""; int uk = sc->GetUK(); int line = sc->GetLine(); int operation = type = sc->Scan(lexem); if (type != Tplus && type != Tincrement && type != Tminus && type != Tdecrement) { sc->PutUK(uk); sc->PutLine(line); } Node* node = Postfix(); if (type == Tplus || type == Tincrement || type == Tminus || type == Tdecrement) { if (node->typenode == TypeNode::CCONSTANT) PrintError("Ожидался идентификатор", uk, line); if (node->type != DataType::IINT) { root->PrintError("Не соответствует типу int", node->lexem); } else { if (operation == Tminus) { node->value.dataAsInt = -node->value.dataAsInt; } else if (operation == Tincrement || operation == Tdecrement) { Node* original; original = root->SemGetVar(node->lexem, node->numberDimension)->GetNode(); if (original->numberDimension == 0) if (operation == Tincrement) original->value.dataAsInt = node->value.dataAsInt + 1; else original->value.dataAsInt = node->value.dataAsInt - 1; else { int index = 0; for (int i = 0; i < node->dimension.size() - 1; i++) { index += node->dimension[i]; index *= original->dimension[i + 1]; } index += node->dimension[node->dimension.size() - 1]; if (original->type == DataType::IINT) if (operation == Tincrement) *(original->value.addrAsInt + index) = node->value.dataAsInt + 1; else *(original->value.addrAsInt + index) = node->value.dataAsInt - 1; } if (operation == Tincrement) { ++node->value.dataAsInt; } else { --node->value.dataAsInt; } } node->type = DataType::IINT; node->typenode = TypeNode::CCONSTANT; } } return node; } Node* Diagram::Postfix() //Постфикс. { int type; string lexem = ""; Node* node; node = ElementaryExpression(); int uk = sc->GetUK(); int line = sc->GetLine(); int operation = type = sc->Scan(lexem); if (type != Tincrement && type != Tdecrement) { sc->PutUK(uk); sc->PutLine(line); } else { if (node->typenode == TypeNode::CCONSTANT) PrintError("Ожидался идентификатор", uk, line); if (node->type != DataType::IINT) { root->PrintError("Не соответствует типу int", node->lexem); } else { Node* original; original = root->SemGetVar(node->lexem, node->numberDimension)->GetNode(); if (original->numberDimension == 0) if (operation == Tincrement) original->value.dataAsInt = node->value.dataAsInt + 1; else original->value.dataAsInt = node->value.dataAsInt - 1; else { int index = 0; for (int i = 0; i < node->dimension.size() - 1; i++) { index += node->dimension[i]; index *= original->dimension[i + 1]; } index += node->dimension[node->dimension.size() - 1]; if (original->type == DataType::IINT) if (operation == Tincrement) *(original->value.addrAsInt + index) = node->value.dataAsInt + 1; else *(original->value.addrAsInt + index) = node->value.dataAsInt - 1; } node->type = DataType::IINT; node->typenode = TypeNode::CCONSTANT; } } return node; } Node* Diagram::ElementaryExpression() //Элементарное выражение. { Node* node; int type; string lexem = ""; int uk = sc->GetUK(); int line = sc->GetLine(); type = sc->Scan(lexem); //Выражение. if (type == TopenBracket) { node = Expression(); type = sc->Scan(lexem); if (type != TcloseBracket) PrintError("Ожидался символ ).", sc->GetLine() + 1, sc->GetUKfromStartString()); } //Константа. else if (type >= TconstInt10 && type <= TconstChar) { node = new Node(); sc->PutUK(uk); sc->PutLine(line); int number = Constant(); node->typenode = TypeNode::CCONSTANT; node->lexem = to_string(number); node->type = DataType::IINT; node->value.dataAsInt = number; } //Имя. else if (type != Ttrue && type != Tfalse) { sc->PutUK(uk); sc->PutLine(line); Node* original; node = Name(); if (node->numberDimension != 0) if (node->type == DataType::IINT) { int* res = node->value.addrAsInt; node->value.dataAsInt = *res; } else { bool* res = node->value.addrAsBoolean; node->value.dataAsBoolean = *res; } } else { node = new Node(); node->typenode = TypeNode::CCONSTANT; node->lexem = lexem; node->type = DataType::BBOOLEAN; if (type == Ttrue) node->value.dataAsBoolean = true; else node->value.dataAsBoolean = false; } return node; } int Diagram::Constant() //Константа. { int type; string lexem = ""; type = sc->Scan(lexem); if (type != TconstInt10 && type != TconstInt8 && type != TconstInt16 && type != TconstInt2 && type != TconstChar) PrintError("Ожидалось константа.", sc->GetLine() + 1, sc->GetUKfromStartString()); if (type == TconstInt10) return stoi(lexem); else if (type == TconstInt8) return stoi(lexem, nullptr, 8); else if (type == TconstInt16) return stoi(lexem, nullptr, 16); else if (type == TconstInt2) { lexem.erase(lexem.begin()); lexem.erase(lexem.begin()); return stoi(lexem, nullptr, 2); } else return lexem[1]; } void Diagram::PrintError(string description, int line, int symbol) { cout << description << endl; cout << "Строка: " << line << ", позиция: " << symbol << "." << endl; throw "Error!"; }
[ "mr.volta0@gmail.com" ]
mr.volta0@gmail.com
615bdbb80f5b6a2b703ffae8479b18dbd7c1724c
d20cdd2803c4df44b5528dec55a791ff643a2655
/KrazyKritters/MenuItem.cpp
f4a300cc57cd6b48b6260c5f9d7ae12fc23c2361
[]
no_license
ohnoitsaninja/KrazyKritters
25e6766e4a9edd044d28508f5870ff3171471051
e7da3f723e7d70152b58d2d8730c411dc8a4798b
refs/heads/master
2021-01-16T20:11:39.835509
2010-06-18T05:49:41
2010-06-18T05:49:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
969
cpp
#include "MenuItem.h" // This is a GUI Control constructor, we should initialize all the variables here hgeGUIMenuItem::hgeGUIMenuItem(int _id, hgeFont * font, HEFFECT snd, float x, float y, char * title) { id = _id; font_ = font; title_ = title; sound_ = snd; color_.SetHWColor(0xFFFFFE060); shadow_.SetHWColor(0x300000000); offset_ = 0.0f; bStatic = false; bVisible = true; bEnabled = true; float w = font_->GetStringWidth(title); rect.Set(x - w/2, y, x + w/2, y + font_->GetHeight()); } void hgeGUIMenuItem::Render() { font_->SetColor(shadow_.GetHWColor()); font_->Render(rect.x1 + offset_ + 3, rect.y1 + 3, HGETEXT_LEFT, title_); font_->SetColor(color_.GetHWColor()); font_->Render(rect.x1 - offset_, rect.y1 - offset_, HGETEXT_LEFT, title_); } void hgeGUIMenuItem::MouseOver(bool bOver) { if(bOver) hge->Effect_Play(sound_); } bool hgeGUIMenuItem::MouseLButton(bool bDown) { if(!bDown) { offset_ = 4; return true; } return false; }
[ "phial1020@gmail.com" ]
phial1020@gmail.com
56377537138ea1a8f3b7f0663fd9dc2773fd8229
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/harfbuzz-ng/src/src/OT/Layout/Common/Coverage.hh
9ca88f788a908e5ea3c2644f7f3b8901ccf63ff8
[ "LicenseRef-scancode-other-permissive", "MIT-Modern-Variant", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "MIT", "Apache-2.0", "LGPL-2.0-or-later", "GPL-1.0-or-later" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
10,322
hh
/* * Copyright © 2007,2008,2009 Red Hat, Inc. * Copyright © 2010,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Red Hat Author(s): Behdad Esfahbod * Google Author(s): Behdad Esfahbod, Garret Rieger */ #ifndef OT_LAYOUT_COMMON_COVERAGE_HH #define OT_LAYOUT_COMMON_COVERAGE_HH #include "../types.hh" #include "CoverageFormat1.hh" #include "CoverageFormat2.hh" namespace OT { namespace Layout { namespace Common { template<typename Iterator> static inline void Coverage_serialize (hb_serialize_context_t *c, Iterator it); struct Coverage { protected: union { HBUINT16 format; /* Format identifier */ CoverageFormat1_3<SmallTypes> format1; CoverageFormat2_4<SmallTypes> format2; #ifndef HB_NO_BEYOND_64K CoverageFormat1_3<MediumTypes>format3; CoverageFormat2_4<MediumTypes>format4; #endif } u; public: DEFINE_SIZE_UNION (2, format); bool sanitize (hb_sanitize_context_t *c) const { TRACE_SANITIZE (this); if (!u.format.sanitize (c)) return_trace (false); switch (u.format) { case 1: return_trace (u.format1.sanitize (c)); case 2: return_trace (u.format2.sanitize (c)); #ifndef HB_NO_BEYOND_64K case 3: return_trace (u.format3.sanitize (c)); case 4: return_trace (u.format4.sanitize (c)); #endif default:return_trace (true); } } /* Has interface. */ unsigned operator [] (hb_codepoint_t k) const { return get (k); } bool has (hb_codepoint_t k) const { return (*this)[k] != NOT_COVERED; } /* Predicate. */ bool operator () (hb_codepoint_t k) const { return has (k); } unsigned int get (hb_codepoint_t k) const { return get_coverage (k); } unsigned int get_coverage (hb_codepoint_t glyph_id) const { switch (u.format) { case 1: return u.format1.get_coverage (glyph_id); case 2: return u.format2.get_coverage (glyph_id); #ifndef HB_NO_BEYOND_64K case 3: return u.format3.get_coverage (glyph_id); case 4: return u.format4.get_coverage (glyph_id); #endif default:return NOT_COVERED; } } unsigned get_population () const { switch (u.format) { case 1: return u.format1.get_population (); case 2: return u.format2.get_population (); #ifndef HB_NO_BEYOND_64K case 3: return u.format3.get_population (); case 4: return u.format4.get_population (); #endif default:return NOT_COVERED; } } template <typename Iterator, hb_requires (hb_is_sorted_source_of (Iterator, hb_codepoint_t))> bool serialize (hb_serialize_context_t *c, Iterator glyphs) { TRACE_SERIALIZE (this); if (unlikely (!c->extend_min (this))) return_trace (false); unsigned count = hb_len (glyphs); unsigned num_ranges = 0; hb_codepoint_t last = (hb_codepoint_t) -2; hb_codepoint_t max = 0; bool unsorted = false; for (auto g: glyphs) { if (last != (hb_codepoint_t) -2 && g < last) unsorted = true; if (last + 1 != g) num_ranges++; last = g; if (g > max) max = g; } u.format = !unsorted && count <= num_ranges * 3 ? 1 : 2; #ifndef HB_NO_BEYOND_64K if (max > 0xFFFFu) u.format += 2; if (unlikely (max > 0xFFFFFFu)) #else if (unlikely (max > 0xFFFFu)) #endif { c->check_success (false, HB_SERIALIZE_ERROR_INT_OVERFLOW); return_trace (false); } switch (u.format) { case 1: return_trace (u.format1.serialize (c, glyphs)); case 2: return_trace (u.format2.serialize (c, glyphs)); #ifndef HB_NO_BEYOND_64K case 3: return_trace (u.format3.serialize (c, glyphs)); case 4: return_trace (u.format4.serialize (c, glyphs)); #endif default:return_trace (false); } } bool subset (hb_subset_context_t *c) const { TRACE_SUBSET (this); auto it = + iter () | hb_take (c->plan->source->get_num_glyphs ()) | hb_map_retains_sorting (c->plan->glyph_map_gsub) | hb_filter ([] (hb_codepoint_t glyph) { return glyph != HB_MAP_VALUE_INVALID; }) ; // Cache the iterator result as it will be iterated multiple times // by the serialize code below. hb_sorted_vector_t<hb_codepoint_t> glyphs (it); Coverage_serialize (c->serializer, glyphs.iter ()); return_trace (bool (glyphs)); } bool intersects (const hb_set_t *glyphs) const { switch (u.format) { case 1: return u.format1.intersects (glyphs); case 2: return u.format2.intersects (glyphs); #ifndef HB_NO_BEYOND_64K case 3: return u.format3.intersects (glyphs); case 4: return u.format4.intersects (glyphs); #endif default:return false; } } bool intersects_coverage (const hb_set_t *glyphs, unsigned int index) const { switch (u.format) { case 1: return u.format1.intersects_coverage (glyphs, index); case 2: return u.format2.intersects_coverage (glyphs, index); #ifndef HB_NO_BEYOND_64K case 3: return u.format3.intersects_coverage (glyphs, index); case 4: return u.format4.intersects_coverage (glyphs, index); #endif default:return false; } } /* Might return false if array looks unsorted. * Used for faster rejection of corrupt data. */ template <typename set_t> bool collect_coverage (set_t *glyphs) const { switch (u.format) { case 1: return u.format1.collect_coverage (glyphs); case 2: return u.format2.collect_coverage (glyphs); #ifndef HB_NO_BEYOND_64K case 3: return u.format3.collect_coverage (glyphs); case 4: return u.format4.collect_coverage (glyphs); #endif default:return false; } } template <typename IterableOut, hb_requires (hb_is_sink_of (IterableOut, hb_codepoint_t))> void intersect_set (const hb_set_t &glyphs, IterableOut&& intersect_glyphs) const { switch (u.format) { case 1: return u.format1.intersect_set (glyphs, intersect_glyphs); case 2: return u.format2.intersect_set (glyphs, intersect_glyphs); #ifndef HB_NO_BEYOND_64K case 3: return u.format3.intersect_set (glyphs, intersect_glyphs); case 4: return u.format4.intersect_set (glyphs, intersect_glyphs); #endif default:return ; } } struct iter_t : hb_iter_with_fallback_t<iter_t, hb_codepoint_t> { static constexpr bool is_sorted_iterator = true; iter_t (const Coverage &c_ = Null (Coverage)) { hb_memset (this, 0, sizeof (*this)); format = c_.u.format; switch (format) { case 1: u.format1.init (c_.u.format1); return; case 2: u.format2.init (c_.u.format2); return; #ifndef HB_NO_BEYOND_64K case 3: u.format3.init (c_.u.format3); return; case 4: u.format4.init (c_.u.format4); return; #endif default: return; } } bool __more__ () const { switch (format) { case 1: return u.format1.__more__ (); case 2: return u.format2.__more__ (); #ifndef HB_NO_BEYOND_64K case 3: return u.format3.__more__ (); case 4: return u.format4.__more__ (); #endif default:return false; } } void __next__ () { switch (format) { case 1: u.format1.__next__ (); break; case 2: u.format2.__next__ (); break; #ifndef HB_NO_BEYOND_64K case 3: u.format3.__next__ (); break; case 4: u.format4.__next__ (); break; #endif default: break; } } typedef hb_codepoint_t __item_t__; __item_t__ __item__ () const { return get_glyph (); } hb_codepoint_t get_glyph () const { switch (format) { case 1: return u.format1.get_glyph (); case 2: return u.format2.get_glyph (); #ifndef HB_NO_BEYOND_64K case 3: return u.format3.get_glyph (); case 4: return u.format4.get_glyph (); #endif default:return 0; } } bool operator != (const iter_t& o) const { if (unlikely (format != o.format)) return true; switch (format) { case 1: return u.format1 != o.u.format1; case 2: return u.format2 != o.u.format2; #ifndef HB_NO_BEYOND_64K case 3: return u.format3 != o.u.format3; case 4: return u.format4 != o.u.format4; #endif default:return false; } } iter_t __end__ () const { iter_t it = {}; it.format = format; switch (format) { case 1: it.u.format1 = u.format1.__end__ (); break; case 2: it.u.format2 = u.format2.__end__ (); break; #ifndef HB_NO_BEYOND_64K case 3: it.u.format3 = u.format3.__end__ (); break; case 4: it.u.format4 = u.format4.__end__ (); break; #endif default: break; } return it; } private: unsigned int format; union { #ifndef HB_NO_BEYOND_64K CoverageFormat2_4<MediumTypes>::iter_t format4; /* Put this one first since it's larger; helps shut up compiler. */ CoverageFormat1_3<MediumTypes>::iter_t format3; #endif CoverageFormat2_4<SmallTypes>::iter_t format2; /* Put this one first since it's larger; helps shut up compiler. */ CoverageFormat1_3<SmallTypes>::iter_t format1; } u; }; iter_t iter () const { return iter_t (*this); } }; template<typename Iterator> static inline void Coverage_serialize (hb_serialize_context_t *c, Iterator it) { c->start_embed<Coverage> ()->serialize (c, it); } } } } #endif // #ifndef OT_LAYOUT_COMMON_COVERAGE_HH
[ "jengelh@inai.de" ]
jengelh@inai.de
026b11fa8e10f90b1856f028f7004df005b13772
682f286ad435be8d8c872e11ff9b911eb3bc9687
/DenialOfServiceAnalyzer.hpp
d0648917fa9784a5f94223041875f76d98f45fab
[]
no_license
mattofthekidd/CS1440-HW7-ITAK
e084e470378c495eb1d69755eca81150df0c8df5
1fcc13d31184bcbeac7abf37d6c3f8e7f24b8055
refs/heads/master
2021-01-19T22:59:01.060246
2017-04-21T16:21:37
2017-04-21T16:21:37
88,899,013
0
0
null
null
null
null
UTF-8
C++
false
false
758
hpp
// // Created by Matthew Kidd on 4/21/17. // #ifndef HW7_SOLID_DESIGN_DENIALOFSERVICEANALYZER_HPP #define HW7_SOLID_DESIGN_DENIALOFSERVICEANALYZER_HPP #include "Analyzer.hpp" class DenialOfServiceAnalyzer : protected Analyzer { public: DenialOfServiceAnalyzer(std::string name, std::vector<std::string> values);; ResultSet run(std::istream& input); private: }; /* * A DenialOfServiceAnalyzer object should only accept Configuration objects that include, as a minimum, parameters with the following name: “Timeframe”, “Likely Attack Message Count”, “Possible Attack Message Count”. See the algorithm in Appendix A to understand how the values of these parameters are used. */ #endif //HW7_SOLID_DESIGN_DENIALOFSERVICEANALYZER_HPP
[ "mattofthekidd@gmail.com" ]
mattofthekidd@gmail.com
8765ae21d4328a87362ef1c2df67d40f42016759
b7e97047616d9343be5b9bbe03fc0d79ba5a6143
/src/protocols/wum/SilentStructStore.cc
2895c525b61f902f3bda683d1b52817dc1ecd0a1
[]
no_license
achitturi/ROSETTA-main-source
2772623a78e33e7883a453f051d53ea6cc53ffa5
fe11c7e7cb68644f404f4c0629b64da4bb73b8f9
refs/heads/master
2021-05-09T15:04:34.006421
2018-01-26T17:10:33
2018-01-26T17:10:33
119,081,547
1
3
null
null
null
null
UTF-8
C++
false
false
9,994
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file protocols/wum/SilentStructStore.cc /// @brief /// @author Mike Tyka // MPI headers #ifdef USEMPI #include <mpi.h> //keep this first #endif #include <protocols/wum/SilentStructStore.hh> //#include <protocols/frag_picker/VallChunk.hh> //#include <protocols/frag_picker/VallProvider.hh> #include <core/chemical/ResidueTypeSet.hh> #include <core/chemical/ChemicalManager.hh> #include <core/kinematics/FoldTree.hh> #include <core/pose/util.hh> #include <core/kinematics/Jump.hh> #include <core/kinematics/RT.hh> #include <basic/options/option.hh> #include <core/import_pose/pose_stream/util.hh> #include <core/import_pose/pose_stream/MetaPoseInputStream.hh> #include <core/pose/Pose.hh> #include <core/conformation/Residue.hh> #include <basic/Tracer.hh> #include <core/io/silent/SilentFileData.hh> #include <core/io/silent/SilentFileOptions.hh> #include <core/io/silent/SilentStruct.hh> #include <core/io/silent/SilentStruct.fwd.hh> #include <core/io/silent/ProteinSilentStruct.hh> #include <core/io/silent/BinarySilentStruct.hh> #include <core/io/silent/SilentStructFactory.hh> #include <utility/exit.hh> #include <utility/pointer/owning_ptr.hh> #include <utility/io/izstream.hh> // C++ headers //#include <cstdlib> #include <iostream> #include <fstream> #include <string> // option key includes #include <basic/options/keys/in.OptionKeys.gen.hh> #include <basic/options/keys/lh.OptionKeys.gen.hh> //Auto Headers #include <core/io/silent/ProteinSilentStruct.tmpl.hh> #include <protocols/moves/Mover.fwd.hh> #include <utility/vector1.hh> #include <numeric/random/random.hh> #include <boost/unordered/unordered_map.hpp> using namespace core; using namespace kinematics; //using namespace protocols::frag_picker; using namespace core::io::silent; using namespace core::pose; using namespace core::scoring; using namespace conformation; using namespace protocols::moves; namespace protocols { namespace wum { /// @details Auto-generated virtual destructor SilentStructStore::~SilentStructStore() = default; class sort_SilentStructOPs { public: sort_SilentStructOPs(std::string field = "score" ): field_(std::move(field)) {} bool operator () (const SilentStructOP& left, const SilentStructOP& right) { runtime_assert( left != nullptr ); runtime_assert( right != nullptr ); return left->get_energy( field_ ) < right->get_energy( field_ ); } private: std::string field_; }; bool find_SilentStructOPs::operator () (const core::io::silent::SilentStructOP& check) { if ( check->get_energy(field_) == value_ ) return true; return false; } static THREAD_LOCAL basic::Tracer TR( "SilentStructStore" ); void SilentStructStore::clear() { store_.clear(); } void SilentStructStore::add( const core::pose::Pose &pose ){ using namespace basic::options; using namespace basic::options::OptionKeys; core::io::silent::SilentFileOptions opts; core::io::silent::SilentStructOP ss = option[ lh::bss]() ? core::io::silent::SilentStructFactory::get_instance()->get_silent_struct("binary", opts) : core::io::silent::SilentStructFactory::get_instance()->get_silent_struct_out( opts ); ss->fill_struct( pose ); add( ss ); } void SilentStructStore::add( SilentStructOP new_struct ){ store_.push_back( new_struct ); } void SilentStructStore::add( const SilentStruct &new_struct ){ SilentStructOP pss = new_struct.clone(); store_.push_back( pss ); } void SilentStructStore::add( core::io::silent::SilentFileData const& sfd ) { using namespace core::io::silent; using namespace core::chemical; for ( SilentFileData::const_iterator it=sfd.begin(), eit=sfd.end(); it!=eit; ++it ) { add( *it ); } } void SilentStructStore::add( SilentStructStore &mergestore ) { for ( std::vector < SilentStructOP >::const_iterator it = mergestore.store_.begin(); it != mergestore.store_.end(); ++it ) { runtime_assert( *it != nullptr ); store_.push_back( *it ); } } // @brief This uses the pose stream to read in everything from -l, -s and -in:file:silent into this store. void SilentStructStore::read_from_cmd_line( ) { using namespace basic::options; using namespace basic::options::OptionKeys; core::chemical::ResidueTypeSetCOP rsd_set; if ( option[ in::file::fullatom ]() ) { rsd_set = core::chemical::ChemicalManager::get_instance()->residue_type_set( "fa_standard" ); } else { rsd_set = core::chemical::ChemicalManager::get_instance()->residue_type_set( "centroid" ); } core::import_pose::pose_stream::MetaPoseInputStream input = core::import_pose::pose_stream::streams_from_cmd_line(); core::Size count = 0; while ( input.has_another_pose() && (count < 400 ) ) { core::pose::Pose pose; input.fill_pose( pose, *rsd_set ); add( pose ); count ++; } TR.Info << "Read " << count << " structures from command line" << std::endl; } // @brief read from silent file void SilentStructStore::read_from_string( const std::string & input ) { std::istringstream iss(input); read_from_stream( iss ); } // @brief read from silent file void SilentStructStore::read_from_stream( std::istream & input ) { SilentFileOptions opts; SilentFileData sfd( opts ); utility::vector1< std::string > tags_wanted; // empty vector signals "read all" according to author of silent io sfd.read_stream( input, tags_wanted, false ); utility::vector1< std::string> comments = sfd.comment_lines(); // utility::vector1< std::string >::iterator citer = comments.begin(); // Unused variable was causing a warning // Now loop over each structure in that silent file for ( core::io::silent::SilentFileData::iterator iter = sfd.begin(), end = sfd.end(); iter != end; ++iter ) { add( *iter); } } void SilentStructStore::read_from_file( const std::string &filename ){ utility::io::izstream data( filename.c_str() ); if ( !data.good() ) { utility_exit_with_message( "ERROR: Unable to open silent strcuture store file: '" + filename + "'" ); } read_from_stream( data ); data.close(); } void SilentStructStore::get_pose( core::Size index, core::pose::Pose &pose ) const { runtime_assert( index < store_.size() ); SilentStructCOP temp_struct = get_struct( index ); temp_struct->fill_pose( pose ); } // @brief GEt a random structure SilentStructCOP SilentStructStore::get_struct_random() const{ if ( store_.size() == 0 ) runtime_assert(false); core::Size choice=core::Size( numeric::random::rg().random_range(0,(store_.size()-1))); runtime_assert( choice < store_.size() ); return store_[ choice ]; } void SilentStructStore::serialize( std::ostream & out ) const { if ( store_.size() == 0 ) { TR.Warning << "WARNING: Empty silent struct store serialized." << std::endl; } else { (*store_.begin())->print_header( out ); SilentFileOptions opts; SilentFileData sfd( opts ); for ( auto const & it : store_ ) { runtime_assert( it != nullptr ); sfd.write_silent_struct( (*it), out ); } } } void SilentStructStore::serialize( std::string & out ) const { std::ostringstream ss; serialize( ss ); out = ss.str(); } void SilentStructStore::serialize_to_file( const std::string &filename ) const { std::ofstream out( filename.c_str() ); if ( !out.good() ) { utility_exit_with_message( "ERROR: Unable to open output file : '" + filename + "'" ); } serialize( out ); out.close(); } void SilentStructStore::print( std::ostream & out ) const { SilentFileOptions opts; SilentFileData sfd( opts ); core::Size count=0; out << "----------------------------------------------" << std::endl; for ( auto const & it : store_ ) { out << count << " "; runtime_assert( it != nullptr ); it->print_scores( out ); } out << "----------------------------------------------" << std::endl; } core::Size SilentStructStore::mem_footprint() const { core::Size total = 0; for ( auto const & it : store_ ) { total += it->mem_footprint(); } return total; } void SilentStructStore::sort_by( std::string field ) { if ( store_.size() == 0 ) return; sort_SilentStructOPs sort_by_field = field; std::sort( store_.begin(), store_.end(), sort_by_field ); } void SilentStructStore::all_add_energy( std::string scorename, core::Real value, core::Real weight ) { for ( auto & it : store_ ) { it->add_energy( scorename, value, weight ); } } void SilentStructStore::all_sort_silent_scores() { for ( auto & it : store_ ) { it->sort_silent_scores( ); } } // TOOLS std::string encode_alphanum(unsigned long number, int pad_width=0, char pad_char = '0') { std::string code = ""; const static char *codes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const static int codes_len = 52; int count_len = 0; while ( number > 0 ) { unsigned int digit = number % codes_len; code = codes[digit] + code; count_len++; number /= codes_len; } while ( count_len < pad_width ) { code = pad_char + code; count_len++; } return code; } // without locking this is not really threadsafe. But how to otherwise proved a *globally* // unique number ? A singleton wont help either, just code overhead. std::string generate_unique_structure_id(){ static long unique_count=0; int mpi_rank = 0; int mpi_npes = 0; #ifdef USEMPI MPI_Comm_rank( MPI_COMM_WORLD, ( int* )( &mpi_rank ) ); MPI_Comm_size( MPI_COMM_WORLD, ( int* )( &mpi_npes ) ); #endif int width = int(floor(log(float(mpi_npes))/log(62.0)) + 1.0); // 62 is the base of the coded number below. unique_count++; return encode_alphanum( unique_count ) + encode_alphanum( mpi_rank, width, '0' ); } } }
[ "achitturi17059@gmail.com" ]
achitturi17059@gmail.com
278abc7cfdd360a7cc694c50ca6945b9b899a266
2080b9fa32311ca8bb194c49e9a490cd93557587
/EquationEditor/EquationEditor/Application.h
9b97b1bd2012505b915006ffd6d33b2abc02b481
[]
no_license
IlyaGusev/Plotter
19c6b0250777305ff237596c3f3b65758bd847b8
bb9fbb55d354c7c4fb21dbb759b215e32011118d
refs/heads/master
2021-01-10T16:29:54.510330
2015-12-13T12:36:05
2015-12-13T12:36:05
46,665,007
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,501
h
#pragma once // // CLASS: CApplication : IUIApplication // // PURPOSE: реализует интерфейс, который позволяет управлять событиями Framework // // COMMENTS: // // Реализует интерфейс необходимый для взаимодействия // Содержит создание, удаление // class CApplication : public IUIApplication // базовый IUIApplication. { public: // Статический метод создания экземпляра объекта. static HRESULT CreateInstance(__deref_out IUIApplication **ppApplication); STDMETHOD_(ULONG, AddRef()); STDMETHOD_(ULONG, Release()); STDMETHOD(QueryInterface(REFIID iid, void** ppv)); STDMETHOD(OnCreateUICommand)(UINT nCmdID, __in UI_COMMANDTYPE typeID, __deref_out IUICommandHandler** ppCommandHandler); STDMETHOD(OnViewChanged)(UINT viewId, __in UI_VIEWTYPE typeId, __in IUnknown* pView, UI_VIEWVERB verb, INT uReasonCode); STDMETHOD(OnDestroyUICommand)(UINT32 commandId, __in UI_COMMANDTYPE typeID, __in_opt IUICommandHandler* commandHandler); private: CApplication() : m_cRef(1) , m_pCommandHandler(NULL) { } ~CApplication() { if (m_pCommandHandler) { m_pCommandHandler->Release(); m_pCommandHandler = NULL; } } LONG m_cRef; // Счетчик ссылок. IUICommandHandler * m_pCommandHandler; // Ссылка на обработчик команд };
[ "phoenixilya@gmail.com" ]
phoenixilya@gmail.com
fd3dbeec6758e11a236a483021345441cb0f1259
47a16a6fd9e3daf9208fcaee046bdaf716f760eb
/code/685.cpp
5ab347d8f3fd2b75513d5c63169c0a2cbdecaeb9
[ "MIT" ]
permissive
Nightwish-cn/my_leetcode
ba9bf05487b60ac1d1277fb4bf1741da4556f87a
40f206e346f3f734fb28f52b9cde0e0041436973
refs/heads/master
2022-11-29T03:32:54.069824
2020-08-08T14:46:47
2020-08-08T14:46:47
287,178,162
0
0
null
null
null
null
UTF-8
C++
false
false
2,123
cpp
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool isLeaf(TreeNode* root) { return root->left == NULL && root->right == NULL; } struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: vector<int> to[1005]; int du[1005], s, t, n, tot; bool vis[1005]; bool dfs(int cur){ ++tot; if (cur == s){ for (int v: to[cur]){ if (v == t) continue; // 这条边已经被删了 if (!vis[v]) vis[v] = true, dfs(v); else return false; } }else { for (int v: to[cur]){ if (!vis[v]) vis[v] = true, dfs(v); else return false; } } return true; } bool ok(){ int rt = -1; for (int i = 1; i <= n; ++i) if (!du[i]){ if (rt < 0) rt = i; else return false; } if (rt < 0) return false; memset(vis, 0, sizeof(vis)); tot = 0; vis[rt] = true; if (!dfs(rt) || tot < n) return false; return true; } vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) { for (auto& e: edges) to[e[0]].push_back(e[1]), ++du[e[1]]; n = edges.size(); for (int i = n - 1; i >= 0; --i){ s = edges[i][0], t = edges[i][1]; --du[t]; if (ok()) return edges[i]; ++du[t]; } return vector<int>(); } }; Solution sol; void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
[ "979115525@qq.com" ]
979115525@qq.com
7e54f10ee9fa83445c7575559b17120e16bbb674
fe37736e41a063aec709bf0e269e3984eb590cde
/Lossy-image-compression/stats.cpp
99fb27ded25fc6aa30c2ab7bb82da0f322e58c00
[]
no_license
dhirenkakkar/csubc
f22c9fd281cc8e6ae60d085e2a3e49b3c94bb503
01d91dfd3b880f7f2af08be35a747ebc8c731fb0
refs/heads/master
2020-12-21T22:36:46.178782
2020-01-29T00:28:33
2020-01-29T00:28:33
236,586,383
0
0
null
null
null
null
UTF-8
C++
false
false
6,462
cpp
#include "stats.h" stats::stats(PNG & im){ // intiliazing private lists double prevSat = 0; double prevLum = 0; double prevHueX = 0; double prevHueY = 0; int onesize = 0; //initiliaze sumSat sumSat.resize(im.width()); sumLum.resize(im.width()); sumHueX.resize(im.width()); sumHueY.resize(im.width()); hist.resize(im.width()); for (int i = 0; i < im.width(); i++) { sumSat[i].resize(im.height()); sumLum[i].resize(im.height()); sumHueX[i].resize(im.height()); sumHueY[i].resize(im.height()); hist[i].resize(im.height()); for (int j = 0; j < im.height(); j++) { hist[i][j].resize(36); HSLAPixel * curr = im.getPixel(i, j); int hue = (int) atan2(sin(curr->h * PI/180), cos(curr->h * PI/180)) * 180/PI; if (hue < 0) { hue = hue + 360; } if (i== 0 && j== 0) { HSLAPixel * curr = im.getPixel(i, j); sumSat[i][j] = curr->s; sumLum[i][j] = curr->l; sumHueX[i][j] = cos(curr->h*PI/180); sumHueY[i][j] = sin(curr->h*PI/180); hist[i][j][hue/10]++; } else if (i==0) { HSLAPixel * curr = im.getPixel(i,j); sumSat[i][j] = sumSat[i][j-1] + curr->s; sumLum[i][j] = sumLum[i][j-1] + curr->l; sumHueX[i][j] = sumHueX[i][j-1] + cos(curr->h*PI/180); sumHueY[i][j] = sumHueY[i][j-1] + sin(curr->h*PI/180); hist[i][j]=hist[i][j-1]; hist[i][j][hue/10]++; } else if (j==0) { HSLAPixel * curr = im.getPixel(i,j); sumSat[i][j] = sumSat[i-1][j] + curr->s; sumLum[i][j] = sumLum[i-1][j] + curr->l; sumHueX[i][j] = sumHueX[i-1][j] + cos(curr->h*PI/180); sumHueY[i][j] = sumHueY[i-1][j] + sin(curr->h*PI/180); hist[i][j]=hist[i-1][j]; hist[i][j][hue/10]++; } else { HSLAPixel * curr = im.getPixel(i,j); sumSat[i][j] = sumSat[i-1][j] + sumSat[i][j-1] - sumSat[i-1][j-1] + curr->s; sumLum[i][j] = sumLum[i-1][j] + sumLum[i][j-1] - sumLum[i-1][j-1] + curr->l; sumHueX[i][j] = sumHueX[i-1][j] + sumHueX[i][j-1] - sumHueX[i-1][j-1] + cos(curr->h*PI/180); sumHueY[i][j] = sumHueY[i-1][j] + sumHueY[i][j-1] - sumHueY[i-1][j-1] + sin(curr->h*PI/180); for (int k = 0; k < 36; k++) { hist[i][j][k] = hist[i-1][j][k] + hist[i][j-1][k] - hist[i-1][j-1][k]; } hist[i][j][hue/10]++; } } } } long stats::rectArea(pair<int,int> ul, pair<int,int> lr){ long width = (long) (lr.first - ul.first)+1; long height = (long) (lr.second - ul.second)+1; return width*height; } HSLAPixel stats::getAvg(pair<int,int> ul, pair<int,int> lr){ HSLAPixel retVal = HSLAPixel(); if ((ul.first==0) && (ul.second == 0)) { retVal.h = (atan2((sumHueY[lr.first][lr.second])/rectArea(ul, lr), (sumHueX[lr.first][lr.second])/rectArea(ul, lr)) * 180/PI); retVal.s = (sumSat[lr.first][lr.second])/rectArea(ul, lr); retVal.l = (sumLum[lr.first][lr.second])/rectArea(ul, lr); retVal.a = 1.0; } else if (ul.first == 0) { retVal.h = (atan2((sumHueY[lr.first][lr.second] - sumHueY[lr.first][ul.second-1])/rectArea(ul, lr) , (sumHueX[lr.first][lr.second] - sumHueX[lr.first][ul.second-1])/rectArea(ul, lr)) * 180/PI); retVal.s = (sumSat[lr.first][lr.second] - sumSat[lr.first][ul.second-1])/rectArea(ul, lr); retVal.l = (sumLum[lr.first][lr.second] - sumLum[lr.first][ul.second-1])/rectArea(ul, lr); retVal.a = 1.0; } else if (ul.second == 0) { retVal.h = (atan2((sumHueY[lr.first][lr.second] - sumHueY[ul.first-1][lr.second])/rectArea(ul,lr), (sumHueX[lr.first][lr.second] - sumHueX[ul.first-1][lr.second])/rectArea(ul, lr)) * 180/PI); retVal.s = (sumSat[lr.first][lr.second] - sumSat[ul.first-1][lr.second])/rectArea(ul, lr); retVal.l = (sumLum[lr.first][lr.second] - sumLum[ul.first-1][lr.second])/rectArea(ul, lr); retVal.a = 1.0; } else { retVal.h = (atan2((sumHueY[lr.first][lr.second] - sumHueY[ul.first-1][lr.second] - (sumHueY[lr.first][ul.second-1] - sumHueY[ul.first-1][ul.second-1]))/rectArea(ul, lr), (sumHueX[lr.first][lr.second] - sumHueX[ul.first-1][lr.second] - (sumHueX[lr.first][ul.second-1] - sumHueX[ul.first-1][ul.second-1]))/rectArea(ul, lr)) * 180/PI); retVal.s = (sumSat[lr.first][lr.second] - sumSat[ul.first-1][lr.second] - (sumSat[lr.first][ul.second-1] - sumSat[ul.first-1][ul.second-1]))/rectArea(ul, lr); retVal.l = (sumLum[lr.first][lr.second] - sumLum[ul.first-1][lr.second] - (sumLum[lr.first][ul.second-1] - sumLum[ul.first-1][ul.second-1]))/rectArea(ul, lr); retVal.a = 1.0; } // retVal->h = (atan2(sumHueY[lr.first][lr.second], sumHueX[lr.first][lr.second])*180/PI); // retVal->s = sumSat[lr.first][lr.second]/rectArea(ul, lr); // retVal->l = sumLum[lr.first][lr.second]/rectArea(ul, lr); // retVal->a = 1.0; return retVal; } vector<int> stats::buildHist(pair<int,int> ul, pair<int,int> lr){ // vector<int> secondhisto = hist[ul.first-1][ul.second-1]; // vector<int> firsthisto = hist[lr.first][lr.second]; // vector<int> thirdhisto = hist[ul.first-1][lr.second]; // vector<int> fourthhisto = hist[lr.first][ul.second-1]; vector<int> retVec(36); if ((ul.first == 0) && (ul.second == 0)) { return hist[lr.first][lr.second]; } else if (ul.first == 0) { for (int k = 0; k < 36; k++) { retVec[k] = hist[lr.first][lr.second][k] - hist[lr.first][ul.second-1][k]; } } else if (ul.second == 0) { for (int k = 0; k < 36; k++) { retVec[k] = hist[lr.first][lr.second][k] - hist[ul.first-1][lr.second][k]; } } else { for (int k = 0; k < 36; k++) { retVec[k] = hist[lr.first][lr.second][k] - hist[ul.first-1][lr.second][k] - hist[lr.first][ul.second-1][k] + hist[ul.first-1][ul.second-1][k]; } } return retVec; } // takes a distribution and returns entropy // partially implemented so as to avoid rounding issues. double stats::entropy(vector<int> & distn,int area){ double entropy = 0.; for (int i = 0; i < 36; i++) { if (distn[i] > 0 ) { entropy += ((double) distn[i]/(double) area) * log2((double) distn[i]/(double) area); } } return -1 * entropy; } double stats::entropy(pair<int,int> ul, pair<int,int> lr){ int area = (int) rectArea(ul, lr); vector<int> histo = buildHist(ul,lr); return entropy(histo, area); }
[ "dhiren@motionmetrics.com" ]
dhiren@motionmetrics.com
45ef1217f03509572fdd83ea1131aeef0798221c
cb7f4e9e4be108167ba6403e30ebb15c540677f8
/backend_t/backends/vc/sse/const_data.h
b3bc8d9eddfea65b35eb9405483f8f2db3c147f8
[]
no_license
nicholasferguson/Portable_SIMD
9aee993d97668985533625b5dce8c9b41af6167c
2d2ec5bf89890a618759dabb59fbd9b2a989f839
refs/heads/master
2021-01-12T17:24:51.220527
2017-10-18T23:35:43
2017-10-18T23:35:43
68,247,847
1
0
null
null
null
null
UTF-8
C++
false
false
3,289
h
/* This file is part of the Vc library. {{{ Copyright © 2012-2015 Matthias Kretz <kretz@kde.org> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of contributing organizations nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. }}}*/ #ifndef VC_SSE_CONST_DATA_H_ #define VC_SSE_CONST_DATA_H_ #include "../common/data.h" #include "macros.h" namespace Vc_VERSIONED_NAMESPACE { namespace SSE { alignas(16) extern const unsigned int _IndexesFromZero4[4]; alignas(16) extern const unsigned short _IndexesFromZero8[8]; alignas(16) extern const unsigned char _IndexesFromZero16[16]; struct c_general { alignas(64) static const int absMaskFloat[4]; alignas(16) static const unsigned int signMaskFloat[4]; alignas(16) static const unsigned int highMaskFloat[4]; alignas(16) static const short minShort[8]; alignas(16) static const unsigned short one16[8]; alignas(16) static const unsigned int one32[4]; alignas(16) static const float oneFloat[4]; alignas(16) static const unsigned long long highMaskDouble[2]; alignas(16) static const double oneDouble[2]; alignas(16) static const long long absMaskDouble[2]; alignas(16) static const unsigned long long signMaskDouble[2]; alignas(16) static const unsigned long long frexpMask[2]; }; template<typename T> struct c_trig { alignas(64) static const T data[]; }; template<typename T> struct c_log { enum VectorSize { Size = 16 / sizeof(T) }; static Vc_ALWAYS_INLINE Vc_CONST const float *d(int i) { return reinterpret_cast<const float *>(&data[i * Size]); } alignas(64) static const unsigned int data[]; }; template<> struct c_log<double> { enum VectorSize { Size = 16 / sizeof(double) }; static Vc_ALWAYS_INLINE Vc_CONST const double *d(int i) { return reinterpret_cast<const double *>(&data[i * Size]); } alignas(64) static const unsigned long long data[]; }; } // namespace SSE } // namespace Vc #endif // VC_SSE_CONST_DATA_H_
[ "nicholasferguson@wingarch.com" ]
nicholasferguson@wingarch.com
7be84f73222941f50fcbf3a20b901b7fe2fa9c15
fb6d70a911d49440a056019acccd0434e7779eea
/Sable/src/Editor/Panels/MenuBarPanel.cpp
8373aa3730b2bae5b22d9648f1000cb3c9ea1bc9
[]
no_license
PizzaCutter/Shake_Engine_CPP
b29b566df369fa4eaad3cdbe08da916ff50caef1
9d479fd9ec600e4b271489c82ae4dd38b1666a34
refs/heads/master
2022-12-25T10:58:05.192374
2020-10-11T11:47:57
2020-10-11T11:47:57
268,881,248
0
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
#include "MenuBarPanel.h" #include "imgui/imgui.h" #include "Shake/Core/Application.h" namespace Shake { MenuBarPanel::MenuBarPanel(SharedPtr<SceneX> scene) : BasePanel(scene) { } void MenuBarPanel::OnImGuiRender() { if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Docking")) { // Disabling fullscreen would allow the window to be moved to the front of other windows, // which we can't undo at the moment without finer window depth/z control. //ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant); if (ImGui::MenuItem("Exit", "", (ImGuiDockNodeFlags_None & ImGuiDockNodeFlags_NoSplit) != 0)) { Shake::Application::Get().Close(); } ImGui::EndMenu(); } ImGui::EndMenuBar(); } } }
[ "robin.smekens.930@gmail.com" ]
robin.smekens.930@gmail.com
7772edf197bbab16f1d0fd7321d9e3283ac12d0e
a1aa4b5d77366dedb40b6bd6970783741afb50c0
/Mysystem/widget.h
1d0a1ce2bf0f0d944cbe86e12f5d52f44dbb76a5
[]
no_license
pointer20qt/HouKai
da18ba00ed0064915d2720b5f29f46eef0d40d06
89e3829a9e82e6e652a5e0a29c504dac84a981db
refs/heads/master
2021-01-01T12:54:59.512894
2020-02-19T09:14:20
2020-02-19T09:14:20
239,288,539
0
0
null
null
null
null
UTF-8
C++
false
false
423
h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QTextEdit> #include <QCheckBox> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0,QString sno=NULL); ~Widget(); void display(QString sql); void displayClass(); void displaySno(); QString sno; private slots: private: Ui::Widget *ui; }; #endif // WIDGET_H
[ "98740786@qq.com" ]
98740786@qq.com
43ecb72f50691faa354e0cfa4da599006f933e04
648089f53d566d29fb2262e632af416a80483394
/Red-Black Tree/Red-Black Tree/Main.cpp
54aa8bdcef56fdb73f2609839fe30af7c3a8d7cb
[]
no_license
payamohajeri/DS
2b338c758f4946df67e2c4ca4af3b1332ad88910
a76fb94b8ac2c201824239ad874f46e9b7c4f28d
refs/heads/master
2016-09-08T01:29:31.100946
2014-06-24T16:45:14
2014-06-24T16:45:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
#include "RedBlackTree.h" #include <iostream> using namespace std; int main() { RedBlackTree myRBT(100); myRBT.insert(200); myRBT.insert(300); myRBT.insert(50); myRBT.insert(75); myRBT.insert(400); myRBT.insert(350); myRBT.insert(25); myRBT.insert(55); myRBT.remove(55); myRBT.remove(50); myRBT.insert(110); myRBT.insert(95); myRBT.remove(100); myRBT.remove(75); myRBT.remove(200); myRBT.preorder(); return 0; }
[ "payam_p70@yahoo.com" ]
payam_p70@yahoo.com
ffc229b7a32d44e0e2763f51ea2f120529f86a8a
391b179ee31222971629624a9a51e8a98c87db41
/src/si_base/math/vfloat4.h
08a2b0d1b84b623726f1aabcdc695c32c7873c95
[ "MIT" ]
permissive
acuvue1102/si_graphics
0e697d910852a3ba2e9564ce09dd6ffe49a3da80
f285a5358fdb8f5b831fba0d7cae423ee79b36c5
refs/heads/master
2021-06-03T01:19:30.678522
2020-02-07T15:27:53
2020-02-07T15:27:53
18,243,761
0
0
null
null
null
null
UTF-8
C++
false
false
3,684
h
#pragma once #include <xmmintrin.h> #include <cstdint> #include "si_base/math/math_declare.h" namespace SI { class alignas(16) Vfloat4 { public: Vfloat4(); Vfloat4(const Vfloat4& v); Vfloat4(float x, float y, float z, float w); Vfloat4(Vfloat x, Vfloat y, Vfloat z, Vfloat w); Vfloat4(Vfloat3 xyz, Vfloat w); Vfloat4(Vfloat3 xyz, float w); explicit Vfloat4(float value); explicit Vfloat4(Vfloat_arg value); explicit Vfloat4(const float* v); explicit Vfloat4(__m128 v); public: void SetX(Vfloat_arg x); void SetY(Vfloat_arg y); void SetZ(Vfloat_arg z); void SetW(Vfloat_arg w); void SetElement(uint32_t elementIndex, Vfloat_arg e); void Set(float value); void Set(Vfloat_arg value); void Set(const float* v); void Set(float x, float y, float z, float w); void Set(Vfloat_arg x, Vfloat_arg y, Vfloat_arg z, Vfloat_arg w); public: Vfloat X() const; Vfloat Y() const; Vfloat Z() const; Vfloat W() const; float Xf() const; float Yf() const; float Zf() const; float Wf() const; Vfloat GetElement(uint32_t elementIndex) const; // 要素を入れ替えるSwizzle関数. templateの方はSIMD使えるので早い. template<uint32_t xIndex, uint32_t yIndex, uint32_t zIndex, uint32_t wIndex> Vfloat4 Swizzle() const; Vfloat4 Swizzle(uint32_t xIndex, uint32_t yIndex, uint32_t zIndex, uint32_t wIndex) const; Vfloat3 XYZ() const; Vfloat4 XYZ0() const; Vfloat4 XYZ1() const; public: Vfloat4 Multiply(Vfloat4x4_arg m) const; Vfloat LengthSqr() const; Vfloat Length() const; Vfloat4 Normalize() const; Vfloat4 NormalizeFast() const; public: Vfloat4& operator=(const Vfloat4& v); Vfloat4 operator-() const; const Vfloat operator[](size_t i) const; // [] operatorは代入を許可しないようにしておく. Vfloat4 operator+(Vfloat4_arg v) const; Vfloat4 operator-(Vfloat4_arg v) const; Vfloat4 operator*(Vfloat4_arg v) const; Vfloat4 operator/(Vfloat4_arg v) const; Vfloat4 operator*(Vfloat_arg f) const; Vfloat4 operator/(Vfloat_arg f) const; Vfloat4 operator*(float f) const; Vfloat4 operator/(float f) const; Vfloat4 operator*(Vfloat4x4_arg m) const; Vfloat4 operator*(Vfloat4x3_arg m) const; Vfloat4& operator+=(Vfloat4_arg v); Vfloat4& operator-=(Vfloat4_arg v); Vfloat4& operator*=(Vfloat4_arg v); Vfloat4& operator/=(Vfloat4_arg v); Vfloat4& operator*=(float f); Vfloat4& operator/=(float f); bool operator==(const Vfloat4& v) const; bool operator!=(const Vfloat4& v) const; public: static Vfloat4 Zero(); static Vfloat4 One(); static Vfloat4 AxisX(); static Vfloat4 AxisY(); static Vfloat4 AxisZ(); static Vfloat4 AxisW(); public: __m128 Get128() const; private: __m128 m_v; }; Vfloat4 operator*(Vfloat f, Vfloat4_arg v); Vfloat4 operator/(Vfloat f, Vfloat4_arg v); Vfloat4 operator*(float f, Vfloat4_arg v); Vfloat4 operator/(float f, Vfloat4_arg v); namespace Math { Vfloat4 Min (Vfloat4_arg a, Vfloat4_arg b); Vfloat4 Max (Vfloat4_arg a, Vfloat4_arg b); Vfloat HorizontalMin (Vfloat4_arg a); Vfloat HorizontalMax (Vfloat4_arg a); Vfloat HorizontalAdd (Vfloat4_arg a); Vfloat HorizontalMul (Vfloat4_arg a); Vfloat4 Abs (Vfloat4_arg a); Vfloat4 Sqrt (Vfloat4_arg a); Vfloat4 Rsqrt (Vfloat4_arg a); Vfloat4 Rcp (Vfloat4_arg a); Vfloat LengthSqr (Vfloat4_arg a); Vfloat Length (Vfloat4_arg a); Vfloat4 Normalize (Vfloat4_arg a); Vfloat4 NormalizeFast (Vfloat4_arg a); Vfloat4 Floor (Vfloat4_arg a); } // namespace Math } #include "si_base/math/inl/vfloat4.inl"
[ "mktaxi.kg11.02@gmail.com" ]
mktaxi.kg11.02@gmail.com
5dcdfd2e0d0452d24fd9969c209081cd9def07f6
0ae19202ccf1aec551a5d875d4a1ee99e891e0d4
/1.Classes&Inheritance/Monster.h
f439a58a37159554845d660e4db4ffc927a7df40
[]
no_license
JamGrif/Computer-Games-Programming-Exercises
442ad2404d63232f100879bfeef4550f8ea66630
5f15e4e2eb38614e4dd8a59c01a6d078de192a15
refs/heads/master
2020-07-31T14:38:29.358668
2019-10-07T20:41:12
2019-10-07T20:41:12
210,635,287
0
0
null
null
null
null
UTF-8
C++
false
false
206
h
#pragma once #include "Creature.h" class Monster : public Creature { public: Monster(int x, int y, std::string Name); void Chase(int heroX, int heroY); bool Eaten(int heroX, int heroY); private: };
[ "40271350+JamGrif@users.noreply.github.com" ]
40271350+JamGrif@users.noreply.github.com
97d1739bae9f0861d2e5a6c3f909a88ff4688631
4f58c2962c2af1124fcabbf309ea7be8ffb51ca4
/src/plugins/httpdatastream/HttpDataStreamFactory.cpp
f3b895243d28de159bf747a4dbbf39d14c981fa0
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
donovan68/musikcube
e324c19c702e4dec5e3cb90f24ca8fa488782e55
37cd0da85f1dfdcf61c477762458f5268be73f77
refs/heads/master
2020-06-17T23:26:06.104608
2019-07-08T00:59:03
2019-07-08T01:55:15
196,097,729
0
1
BSD-3-Clause
2019-07-09T23:29:56
2019-07-09T23:29:56
null
UTF-8
C++
false
false
2,488
cpp
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2019 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include <string> #include <algorithm> #include "HttpDataStreamFactory.h" #include "HttpDataStream.h" HttpDataStreamFactory::HttpDataStreamFactory() { } HttpDataStreamFactory::~HttpDataStreamFactory() { } bool HttpDataStreamFactory::CanRead(const char *uri) { std::string str(uri); std::transform(str.begin(), str.end(), str.begin(), ::tolower); return str.find("http://") == 0 || str.find("https://") == 0; } IDataStream* HttpDataStreamFactory::Open(const char *uri, unsigned int options) { HttpDataStream* stream = new HttpDataStream(); if (stream->Open(uri, options)) { return stream; } delete stream; return nullptr; } void HttpDataStreamFactory::Release() { delete this; }
[ "casey.langen@gmail.com" ]
casey.langen@gmail.com
a2c33d4072f716fd44b66ec6708b7e037491d1b0
1285691298031674155e6121db38b9156231c240
/include/ManagerDatabase/table_gen/Series.h
bc18af89ebdceade7f434d0f2eed80a0595b3b95
[]
no_license
maituduy/mysql_cpp
29511eecdc72cfb98c9f8c347c3b938c2c95dede
df1907b84bf968f18d27b66b0c561d2fbd9f38a1
refs/heads/master
2022-05-23T16:45:30.390974
2020-04-28T04:45:54
2020-04-28T04:45:54
259,532,537
0
0
null
null
null
null
UTF-8
C++
false
false
19,749
h
// generated by ./ddl2cpp /home/mxw/Desktop/out/series.sql /home/mxw/Desktop/out/table_gen/Series table #ifndef TABLE_SERIES_H #define TABLE_SERIES_H #include <sqlpp11/table.h> #include <sqlpp11/data_types.h> #include <sqlpp11/char_sequence.h> namespace table { namespace Series_ { struct Pk { struct _alias_t { static constexpr const char _literal[] = "pk"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T pk; T& operator()() { return pk; } const T& operator()() const { return pk; } }; }; using _traits = sqlpp::make_traits<sqlpp::bigint, sqlpp::tag::must_not_insert, sqlpp::tag::must_not_update, sqlpp::tag::can_be_null>; }; struct StudyFk { struct _alias_t { static constexpr const char _literal[] = "study_fk"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T studyFk; T& operator()() { return studyFk; } const T& operator()() const { return studyFk; } }; }; using _traits = sqlpp::make_traits<sqlpp::bigint, sqlpp::tag::can_be_null>; }; struct MppsFk { struct _alias_t { static constexpr const char _literal[] = "mpps_fk"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T mppsFk; T& operator()() { return mppsFk; } const T& operator()() const { return mppsFk; } }; }; using _traits = sqlpp::make_traits<sqlpp::bigint, sqlpp::tag::can_be_null>; }; struct InstCodeFk { struct _alias_t { static constexpr const char _literal[] = "inst_code_fk"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T instCodeFk; T& operator()() { return instCodeFk; } const T& operator()() const { return instCodeFk; } }; }; using _traits = sqlpp::make_traits<sqlpp::bigint, sqlpp::tag::can_be_null>; }; struct SeriesIuid { struct _alias_t { static constexpr const char _literal[] = "series_iuid"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T seriesIuid; T& operator()() { return seriesIuid; } const T& operator()() const { return seriesIuid; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::require_insert>; }; struct SeriesNo { struct _alias_t { static constexpr const char _literal[] = "series_no"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T seriesNo; T& operator()() { return seriesNo; } const T& operator()() const { return seriesNo; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct Modality { struct _alias_t { static constexpr const char _literal[] = "modality"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T modality; T& operator()() { return modality; } const T& operator()() const { return modality; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct BodyPart { struct _alias_t { static constexpr const char _literal[] = "body_part"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T bodyPart; T& operator()() { return bodyPart; } const T& operator()() const { return bodyPart; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct Laterality { struct _alias_t { static constexpr const char _literal[] = "laterality"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T laterality; T& operator()() { return laterality; } const T& operator()() const { return laterality; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct SeriesDesc { struct _alias_t { static constexpr const char _literal[] = "series_desc"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T seriesDesc; T& operator()() { return seriesDesc; } const T& operator()() const { return seriesDesc; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct Institution { struct _alias_t { static constexpr const char _literal[] = "institution"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T institution; T& operator()() { return institution; } const T& operator()() const { return institution; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct StationName { struct _alias_t { static constexpr const char _literal[] = "station_name"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T stationName; T& operator()() { return stationName; } const T& operator()() const { return stationName; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct Department { struct _alias_t { static constexpr const char _literal[] = "department"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T department; T& operator()() { return department; } const T& operator()() const { return department; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct PerfPhysician { struct _alias_t { static constexpr const char _literal[] = "perf_physician"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T perfPhysician; T& operator()() { return perfPhysician; } const T& operator()() const { return perfPhysician; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct PerfPhysFnSx { struct _alias_t { static constexpr const char _literal[] = "perf_phys_fn_sx"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T perfPhysFnSx; T& operator()() { return perfPhysFnSx; } const T& operator()() const { return perfPhysFnSx; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct PerfPhysGnSx { struct _alias_t { static constexpr const char _literal[] = "perf_phys_gn_sx"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T perfPhysGnSx; T& operator()() { return perfPhysGnSx; } const T& operator()() const { return perfPhysGnSx; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct PerfPhysIName { struct _alias_t { static constexpr const char _literal[] = "perf_phys_i_name"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T perfPhysIName; T& operator()() { return perfPhysIName; } const T& operator()() const { return perfPhysIName; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct PerfPhysPName { struct _alias_t { static constexpr const char _literal[] = "perf_phys_p_name"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T perfPhysPName; T& operator()() { return perfPhysPName; } const T& operator()() const { return perfPhysPName; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct PpsStart { struct _alias_t { static constexpr const char _literal[] = "pps_start"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T ppsStart; T& operator()() { return ppsStart; } const T& operator()() const { return ppsStart; } }; }; using _traits = sqlpp::make_traits<sqlpp::time_point, sqlpp::tag::can_be_null>; }; struct PpsIuid { struct _alias_t { static constexpr const char _literal[] = "pps_iuid"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T ppsIuid; T& operator()() { return ppsIuid; } const T& operator()() const { return ppsIuid; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct SeriesCustom1 { struct _alias_t { static constexpr const char _literal[] = "series_custom1"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T seriesCustom1; T& operator()() { return seriesCustom1; } const T& operator()() const { return seriesCustom1; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct SeriesCustom2 { struct _alias_t { static constexpr const char _literal[] = "series_custom2"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T seriesCustom2; T& operator()() { return seriesCustom2; } const T& operator()() const { return seriesCustom2; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct SeriesCustom3 { struct _alias_t { static constexpr const char _literal[] = "series_custom3"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T seriesCustom3; T& operator()() { return seriesCustom3; } const T& operator()() const { return seriesCustom3; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct NumInstances { struct _alias_t { static constexpr const char _literal[] = "num_instances"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T numInstances; T& operator()() { return numInstances; } const T& operator()() const { return numInstances; } }; }; using _traits = sqlpp::make_traits<sqlpp::integer, sqlpp::tag::can_be_null>; }; struct SrcAet { struct _alias_t { static constexpr const char _literal[] = "src_aet"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T srcAet; T& operator()() { return srcAet; } const T& operator()() const { return srcAet; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct ExtRetrAet { struct _alias_t { static constexpr const char _literal[] = "ext_retr_aet"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T extRetrAet; T& operator()() { return extRetrAet; } const T& operator()() const { return extRetrAet; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct RetrieveAets { struct _alias_t { static constexpr const char _literal[] = "retrieve_aets"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T retrieveAets; T& operator()() { return retrieveAets; } const T& operator()() const { return retrieveAets; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct FilesetIuid { struct _alias_t { static constexpr const char _literal[] = "fileset_iuid"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T filesetIuid; T& operator()() { return filesetIuid; } const T& operator()() const { return filesetIuid; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct FilesetId { struct _alias_t { static constexpr const char _literal[] = "fileset_id"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T filesetId; T& operator()() { return filesetId; } const T& operator()() const { return filesetId; } }; }; using _traits = sqlpp::make_traits<sqlpp::varchar, sqlpp::tag::can_be_null>; }; struct Availability { struct _alias_t { static constexpr const char _literal[] = "availability"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T availability; T& operator()() { return availability; } const T& operator()() const { return availability; } }; }; using _traits = sqlpp::make_traits<sqlpp::integer, sqlpp::tag::require_insert>; }; struct SeriesStatus { struct _alias_t { static constexpr const char _literal[] = "series_status"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T seriesStatus; T& operator()() { return seriesStatus; } const T& operator()() const { return seriesStatus; } }; }; using _traits = sqlpp::make_traits<sqlpp::integer, sqlpp::tag::require_insert>; }; struct CreatedTime { struct _alias_t { static constexpr const char _literal[] = "created_time"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T createdTime; T& operator()() { return createdTime; } const T& operator()() const { return createdTime; } }; }; using _traits = sqlpp::make_traits<sqlpp::time_point, sqlpp::tag::can_be_null>; }; struct UpdatedTime { struct _alias_t { static constexpr const char _literal[] = "updated_time"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T updatedTime; T& operator()() { return updatedTime; } const T& operator()() const { return updatedTime; } }; }; using _traits = sqlpp::make_traits<sqlpp::time_point, sqlpp::tag::can_be_null>; }; struct SeriesAttrs { struct _alias_t { static constexpr const char _literal[] = "series_attrs"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T seriesAttrs; T& operator()() { return seriesAttrs; } const T& operator()() const { return seriesAttrs; } }; }; using _traits = sqlpp::make_traits<sqlpp::blob, sqlpp::tag::can_be_null>; }; } // namespace Series_ struct Series: sqlpp::table_t<Series, Series_::Pk, Series_::StudyFk, Series_::MppsFk, Series_::InstCodeFk, Series_::SeriesIuid, Series_::SeriesNo, Series_::Modality, Series_::BodyPart, Series_::Laterality, Series_::SeriesDesc, Series_::Institution, Series_::StationName, Series_::Department, Series_::PerfPhysician, Series_::PerfPhysFnSx, Series_::PerfPhysGnSx, Series_::PerfPhysIName, Series_::PerfPhysPName, Series_::PpsStart, Series_::PpsIuid, Series_::SeriesCustom1, Series_::SeriesCustom2, Series_::SeriesCustom3, Series_::NumInstances, Series_::SrcAet, Series_::ExtRetrAet, Series_::RetrieveAets, Series_::FilesetIuid, Series_::FilesetId, Series_::Availability, Series_::SeriesStatus, Series_::CreatedTime, Series_::UpdatedTime, Series_::SeriesAttrs> { struct _alias_t { static constexpr const char _literal[] = "series"; using _name_t = sqlpp::make_char_sequence<sizeof(_literal), _literal>; template<typename T> struct _member_t { T series; T& operator()() { return series; } const T& operator()() const { return series; } }; }; }; } // namespace table #endif
[ "maituduy1998@gmail.com" ]
maituduy1998@gmail.com
b6f09b2ab41ea84e7bd2e48e8915f47e5d5b0a2c
8c777d62435addb7c5657f4a0e722505e70dcbc1
/openSocket/T2.cpp
87142520f6a68b6d83af69ca2eb6d3bb25bbbcc6
[]
no_license
davidmc/w3metasite
4e35601d68996dae92e6b7e85ae86aa1bb1a9093
c8b98d0dd585a069a16116dea267fabf845ebc13
refs/heads/master
2016-09-05T10:47:09.368012
2010-01-01T19:44:13
2010-01-01T19:44:13
455,231
1
0
null
null
null
null
UTF-8
C++
false
false
535
cpp
/* NEW TEST HARNESS T2.cpp ======================= The compile is easy: g++ T2.cpp -o T2 */ #include <iostream> #include <iomanip> // STEP 1). // Initial include of all headers under test // needed to define classes #include "oc_SMTP.h" // Forces inclusion of test code #define IN_T2_TESTHARNESS using namespace std; int main( int argc, char ** argv ) { // STEP 2). // Second include of files under test for actual test code. #include "oc_SMTP.h" return 0; } // STEP 3). // include .cpp files, if any here
[ "w3sysdesign@gmail.com" ]
w3sysdesign@gmail.com
05db0e593464bd9e12bb83b0753ea1da6e261777
78299cd4622959e0804010edc6fc693c5d53c210
/src_blade/thread/blocking_queue.h
1682b1adebe9b42e229e438f8eef05e723b56fc5
[]
no_license
sunqk13022/SimpleLog
638ac667bd1c46a3675ed6a9cad0b7bffcad9831
419a330c7174a4d256e33c6ad3b40c8b93a9f592
refs/heads/master
2021-01-10T03:10:52.829185
2016-02-24T05:46:43
2016-02-24T05:46:43
51,690,796
0
0
null
null
null
null
UTF-8
C++
false
false
953
h
#ifndef THREAD_BLOCKING_QUEUE_H_ #define THREAD_BLOCKING_QUEUE_H_ #include "condition.h" #include "mutex.h" #include <boost/noncopyable.hpp> #include <deque> #include <assert.h> namespace simple_log { template<typename T> class BlockingQueue : public boost::noncopyable { public: BlockingQueue() : mutex_(), notEmpty_(mutex_), queue_() { } void put(const T& x) { MutexLockGuard lock(mutex_); queue_.push_back(x); notEmpty_.notify(); } T take() { MutexLockGuard lock(mutex_); while (queue_.empty()) { notEmpty_.wait(); } assert(!queue_.empty()); T front(queue_.front()); queue_.pop_front(); return front; } size_t size() const { MutexLockGuard lock(mutex_); return queue_.size(); } private: mutable MutexLock mutex_; Condition notEmpty_; std::deque<T> queue_; }; // class BlockingQueue } // namespace simple_log #endif // THREAD_BLOCKING_QUEUE_H_
[ "sunqiankun@test1.bcon.bjdt.qihoo.net" ]
sunqiankun@test1.bcon.bjdt.qihoo.net
c722233e3c40a7232b6831b2b4f76106bc5135d1
453986fa19c4548dcbec023dfc3788f60902b776
/External/wxWidgets-2.9.2/tests/sizers/wrapsizer.cpp
9ca561f4c2af3409d747aef864eba192dd4d6408
[]
no_license
beanhome/dev
53bd30867564701d3aec5f5024dac9a11bf06a78
8b01ff6e6a2f3d0cc0c20fb5fa7be33d8d7eda6f
refs/heads/master
2023-03-15T22:19:32.984486
2023-02-21T21:46:52
2023-02-21T21:46:52
8,661,198
0
0
null
null
null
null
UTF-8
C++
false
false
4,054
cpp
/////////////////////////////////////////////////////////////////////////////// // Name: tests/sizers/wrapsizer.cpp // Purpose: Unit tests for wxWrapSizer // Author: Catalin Raceanu // Created: 2010-10-23 // RCS-ID: $Id$ // Copyright: (c) 2010 wxWidgets development team /////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #include "testprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/app.h" #endif // WX_PRECOMP #include "wx/wrapsizer.h" #include "asserthelper.h" // ---------------------------------------------------------------------------- // test class // ---------------------------------------------------------------------------- class WrapSizerTestCase : public CppUnit::TestCase { public: WrapSizerTestCase() { } virtual void setUp(); virtual void tearDown(); private: CPPUNIT_TEST_SUITE( WrapSizerTestCase ); CPPUNIT_TEST( CalcMin ); CPPUNIT_TEST_SUITE_END(); void CalcMin(); wxWindow *m_win; wxSizer *m_sizer; DECLARE_NO_COPY_CLASS(WrapSizerTestCase) }; // register in the unnamed registry so that these tests are run by default CPPUNIT_TEST_SUITE_REGISTRATION( WrapSizerTestCase ); // also include in its own registry so that these tests can be run alone CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( WrapSizerTestCase, "WrapSizerTestCase" ); // ---------------------------------------------------------------------------- // test initialization // ---------------------------------------------------------------------------- void WrapSizerTestCase::setUp() { m_win = new wxWindow(wxTheApp->GetTopWindow(), wxID_ANY); m_win->SetClientSize(180, 240); m_sizer = new wxWrapSizer(wxHORIZONTAL); m_win->SetSizer(m_sizer); } void WrapSizerTestCase::tearDown() { delete m_win; m_win = NULL; m_sizer = NULL; } // ---------------------------------------------------------------------------- // tests themselves // ---------------------------------------------------------------------------- void WrapSizerTestCase::CalcMin() { const wxSize sizeTotal = m_win->GetClientSize(); wxSize sizeMinExpected; // With a single child the min size must be the same as child size. const wxSize sizeChild1 = wxSize(sizeTotal.x/2 - 10, sizeTotal.y/4); sizeMinExpected = sizeChild1; wxWindow * const child1 = new wxWindow(m_win, wxID_ANY, wxDefaultPosition, sizeChild1); child1->SetBackgroundColour(*wxRED); m_sizer->Add(child1); m_win->Layout(); CPPUNIT_ASSERT_EQUAL( sizeMinExpected, m_sizer->CalcMin() ); // If both children can fit in the same row, the minimal size of the sizer // is determined by the sum of their minimal horizontal dimensions and // the maximum of their minimal vertical dimensions. const wxSize sizeChild2 = wxSize(sizeTotal.x/2 + 10, sizeTotal.y/3); sizeMinExpected.x += sizeChild2.x; sizeMinExpected.y = wxMax(sizeChild1.y, sizeChild2.y); wxWindow * const child2 = new wxWindow(m_win, wxID_ANY, wxDefaultPosition, sizeChild2); child2->SetBackgroundColour(*wxYELLOW); m_sizer->Add(child2); m_win->Layout(); CPPUNIT_ASSERT_EQUAL( sizeMinExpected, m_sizer->CalcMin() ); // Three children will take at least two rows so the minimal size in // vertical direction must increase. const wxSize sizeChild3 = wxSize(sizeTotal.x/2, sizeTotal.y/5); sizeMinExpected.y += sizeChild3.y; wxWindow * const child3 = new wxWindow(m_win, wxID_ANY, wxDefaultPosition, sizeChild3); child3->SetBackgroundColour(*wxGREEN); m_sizer->Add(child3); m_win->Layout(); CPPUNIT_ASSERT_EQUAL( sizeMinExpected, m_sizer->CalcMin() ); }
[ "beanhome@98103730-226b-4492-ba33-9fb5e5d430b8" ]
beanhome@98103730-226b-4492-ba33-9fb5e5d430b8
8a630739347c591dbbc79dc49a67bed260392275
c4ef71b435dbcb71a84539f652698a955b6cb737
/kernels/xeonphi/bvh4mb/bvh4mb_builder.h
fd2f150ea3b752d23bc56b6c07c94d1c1f61e280
[ "Apache-2.0" ]
permissive
jamesvecore/embree
e4241c20d1b11e3de64bd58e22c658d117e8d6fe
b1fd4b6f2abfd3edd69ae30ca81b9acd0e78ec84
refs/heads/master
2021-01-15T09:28:46.934407
2014-01-31T11:20:59
2014-01-31T11:20:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,894
h
// ======================================================================== // // Copyright 2009-2013 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #ifndef __EMBREE_BVH4MB_BUILDER_MIC_H__ #define __EMBREE_BVH4MB_BUILDER_MIC_H__ #include "bvh4i/bvh4i_builder.h" #include "bvh4mb.h" namespace embree { /*! derived binned-SAH builder supporting virtual geometry */ class BVH4mbBuilder : public BVH4iBuilder { public: /*! creates the builder */ static Builder* create (void* accel, BuildSource* source, void* geometry, size_t mode = BVH4I_BUILDER_DEFAULT); BVH4mbBuilder(BVH4mb* bvh, BuildSource* source, void* geometry) : BVH4iBuilder((BVH4i*)bvh,source,geometry) { numNodesToAllocate = 2 * BVH4i::N; /* 8 */ } virtual void allocateData(const size_t threadCount, const size_t newNumPrimitives); virtual void convertQBVHLayout(const size_t threadIndex, const size_t threadCount); virtual void createAccel(const size_t threadIndex, const size_t threadCount); virtual void printBuilderName(); virtual size_t getNumPrimitives(); virtual void computePrimRefs(const size_t threadIndex, const size_t threadCount); /* parallel refit bvh4mb tree */ void generate_subtrees(const size_t index,const size_t depth, size_t &subtrees); BBox3f refit_toplevel(const size_t index,const size_t depth); BBox3f refit_subtree(const size_t index); /* scalar refit */ void refit(const size_t index); /* check bvh4mb tree */ void check_tree(const unsigned index); protected: AtomicCounter atomicID; size_t subtrees; TASK_FUNCTION(BVH4mbBuilder,refitBVH4MB); TASK_FUNCTION(BVH4mbBuilder,createTriangle01AccelMB); TASK_FUNCTION(BVH4mbBuilder,convertToSOALayoutMB); TASK_FUNCTION(BVH4mbBuilder,computePrimRefsTrianglesMB); }; } #endif
[ "carsten.benthin@intel.com" ]
carsten.benthin@intel.com
234fada630d5ee2479ef7743f879d0c9cec8dda7
d26e7f93104ed237bb9a41d77f524992dc753974
/CellMGR.h
660b64d57ccfd5cd0207fe4d46861c5b10ceee89
[]
no_license
YuMurata/DXOselo
4b73089c9c3078e5db131c3d8a4bb5ded1e46374
42450d4ebffdf3be28404441622f7c295e0832f1
refs/heads/master
2021-01-21T11:30:05.212766
2017-03-17T07:58:17
2017-03-17T07:58:17
83,577,622
0
0
null
null
null
null
UTF-8
C++
false
false
1,261
h
#pragma once #include<DxFunc.h> using namespace std; class CellMGR:public ImageMGR { private: vector<vector<BaseImage>> cells; int handle; BoardSize board_size; ImagRate rate; public: CellMGR(const BoardSize &board_size) :board_size(board_size) { this->handle = LoadGraph("Image/cell.bmp"); TCoordinate<int> coord; int dum; GetScreenState(&coord.x, &coord.y, &dum); ImagSize size; GetGraphSizeF(this->handle, &size.x, &size.y); this->rate = TCoordinate<double>(1.)*coord / board_size / size; } void Init() { this->images = vector<BaseImage>(this->board_size.x*this->board_size.y); CellCoord coord; for (coord.y = 0; coord.y < board_size.y; ++coord.y) { for (coord.x = 0; coord.x < board_size.x; ++coord.x) { this->PutPieceAt(coord); } } } void PutPieceAt(const CellCoord &coord) { auto &cell = this->images[coord.y*board_size.x+coord.x]; auto imag_coord = this->CellToImag(coord); cell.Init(imag_coord, this->handle, this->rate); } ImagCoord CellToImag(const CellCoord &coord) { ImagSize ret; GetGraphSizeF(this->handle, &ret.x, &ret.y); return ret * coord*this->rate; } ImagSize GetSize() { return this->images.front().GetAppSize(); } void UpDate(const Input &input) {} };
[ "purin7635@gmail.com" ]
purin7635@gmail.com
0e11b47e5310a938c1bb280a7c0de6597e87ab06
2c899d743edbe59677d42df8ac8bcc1fe0160460
/DSNApiLibrary/chat.cpp
0420fb5fe65cd656f0bd3d9d0156a822c99fe1f1
[ "MIT" ]
permissive
LaurieHarding-Russell/Decentralized-Social-Network
04ac97c7d021049ad4615ddaab7174bf43ab8e51
64a4365820b1b4008cc0a1e7af24feb5b64b8166
refs/heads/master
2021-01-01T15:51:04.099300
2018-02-19T02:26:07
2018-02-19T02:26:07
28,011,203
1
1
null
2014-12-18T02:19:05
2014-12-14T22:58:36
C++
UTF-8
C++
false
false
1,977
cpp
/* Chat.cpp */ #include "chat.h" Chat::Chat(std::string a){ address =a; failedState= 0; // If everything works failedState will chage to 20. if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) != -1) { // Creating TCP socket failedState =1; // Not connected yet. memset(&client, 0, sizeof(client)); client.sin_family = AF_INET; // Type=Internet/IP client.sin_addr.s_addr = inet_addr(address.c_str()); // IP address client.sin_port = htons(HOSTSOCK); // server port if (connect(sock,(struct sockaddr *) &client,sizeof(client)) != -1) { // Try to connect failedState =20; // We are connected! }else{ perror("socket Error"); // For testing. Failed to connect. } } } Chat::Chat(int socket,std::string a){ address =a; sock=socket; failedState =20; } int Chat::sendMessage(std::string message){ rLock.lock(); if(failedState>=20){ // Fatal errors are bellow 20. if (send(sock, message.c_str(), message.length(), 0) != message.length()){ failedState == 30; // Message failed to send all bytes. } } int returnFS= failedState; rLock.unlock(); return returnFS; } void Chat::messageCheckLoop(){ char buffer[BUFFSIZE]; int size; rLock.lock(); while(failedState>=20){ rLock.unlock(); if((size=recv(sock, buffer, BUFFSIZE-1, 0)) >= 1) { // Check for new bytes messageLock.lock(); message =message +buffer; messageLock.unlock(); } rLock.lock(); } rLock.unlock(); } int Chat::getState(){ int temp; rLock.lock(); temp = failedState; rLock.unlock(); return temp; } std::string Chat::getMessage(){ std::string returnS; messageLock.lock(); returnS= message; // get message message =""; // clear message; messageLock.unlock(); return returnS; } void Chat::endMessageCheckLoop(){ rLock.lock(); failedState =0; // End it. rLock.unlock(); } Chat::~Chat(){ #ifdef _WIN32 closesocket(sock); #elif __linux__ close(sock); // Disconnect #endif }
[ "lauriehardingrussell@gmail.com" ]
lauriehardingrussell@gmail.com
8cefc0ac3427b6f25596cbfe15df7ed340b9e5bc
d84156aed6991854d3ff400293283866a92820fa
/tools/external/wabt/src/binary-reader.cc
736e2099727e3dde69fbd469d4848993a37b6999
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cyberway/cyberway.cdt
e6ba7f02d8bf7947fdd73956c8d5cb8522910a12
4e6a8cb1045d4c63b9dadfe9d255e95241ee0532
refs/heads/master
2021-08-06T06:14:08.813687
2020-04-15T04:53:08
2020-04-15T04:53:08
154,245,607
5
0
MIT
2020-04-15T04:53:09
2018-10-23T01:58:55
C++
UTF-8
C++
false
false
72,520
cc
/* * Copyright 2016 WebAssembly Community Group participants * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/binary-reader.h" #include <cassert> #include <cinttypes> #include <cstdarg> #include <cstdint> #include <cstdio> #include <cstring> #include <vector> #include "config.h" #include "src/binary-reader-logging.h" #include "src/binary.h" #include "src/leb128.h" #include "src/stream.h" #include "src/utf8.h" #if HAVE_ALLOCA #include <alloca.h> #endif #define ERROR_UNLESS(expr, ...) \ do { \ if (!(expr)) { \ PrintError(__VA_ARGS__); \ return Result::Error; \ } \ } while (0) #define ERROR_UNLESS_OPCODE_ENABLED(opcode) \ do { \ if (!opcode.IsEnabled(options_->features)) { \ return ReportUnexpectedOpcode(opcode); \ } \ } while (0) #define CALLBACK0(member) \ ERROR_UNLESS(Succeeded(delegate_->member()), #member " callback failed") #define CALLBACK(member, ...) \ ERROR_UNLESS(Succeeded(delegate_->member(__VA_ARGS__)), \ #member " callback failed") namespace wabt { namespace { class BinaryReader { public: BinaryReader(const void* data, size_t size, BinaryReaderDelegate* delegate, const ReadBinaryOptions* options); Result ReadModule(); private: template <typename T, T BinaryReader::*member> struct ValueRestoreGuard { explicit ValueRestoreGuard(BinaryReader* this_) : this_(this_), previous_value_(this_->*member) {} ~ValueRestoreGuard() { this_->*member = previous_value_; } BinaryReader* this_; T previous_value_; }; void WABT_PRINTF_FORMAT(2, 3) PrintError(const char* format, ...); Result ReadOpcode(Opcode* out_value, const char* desc) WABT_WARN_UNUSED; template <typename T> Result ReadT(T* out_value, const char* type_name, const char* desc) WABT_WARN_UNUSED; Result ReadU8(uint8_t* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadU32(uint32_t* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadF32(uint32_t* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadF64(uint64_t* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadV128(v128* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadU32Leb128(uint32_t* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadS32Leb128(uint32_t* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadS64Leb128(uint64_t* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadType(Type* out_value, const char* desc) WABT_WARN_UNUSED; Result ReadStr(string_view* out_str, const char* desc) WABT_WARN_UNUSED; Result ReadBytes(const void** out_data, Address* out_data_size, const char* desc) WABT_WARN_UNUSED; Result ReadIndex(Index* index, const char* desc) WABT_WARN_UNUSED; Result ReadOffset(Offset* offset, const char* desc) WABT_WARN_UNUSED; Result ReadCount(Index* index, const char* desc) WABT_WARN_UNUSED; bool IsConcreteType(Type); bool IsBlockType(Type); Index NumTotalFuncs(); Index NumTotalTables(); Index NumTotalMemories(); Index NumTotalGlobals(); Result ReadI32InitExpr(Index index) WABT_WARN_UNUSED; Result ReadInitExpr(Index index, bool require_i32 = false) WABT_WARN_UNUSED; Result ReadTable(Type* out_elem_type, Limits* out_elem_limits) WABT_WARN_UNUSED; Result ReadMemory(Limits* out_page_limits) WABT_WARN_UNUSED; Result ReadGlobalHeader(Type* out_type, bool* out_mutable) WABT_WARN_UNUSED; Result ReadExceptionType(TypeVector& sig) WABT_WARN_UNUSED; Result ReadFunctionBody(Offset end_offset) WABT_WARN_UNUSED; Result ReadNameSection(Offset section_size) WABT_WARN_UNUSED; Result ReadRelocSection(Offset section_size) WABT_WARN_UNUSED; Result ReadLinkingSection(Offset section_size) WABT_WARN_UNUSED; Result ReadCustomSection(Offset section_size) WABT_WARN_UNUSED; Result ReadTypeSection(Offset section_size) WABT_WARN_UNUSED; Result ReadImportSection(Offset section_size) WABT_WARN_UNUSED; Result ReadFunctionSection(Offset section_size) WABT_WARN_UNUSED; Result ReadTableSection(Offset section_size) WABT_WARN_UNUSED; Result ReadMemorySection(Offset section_size) WABT_WARN_UNUSED; Result ReadGlobalSection(Offset section_size) WABT_WARN_UNUSED; Result ReadExportSection(Offset section_size) WABT_WARN_UNUSED; Result ReadStartSection(Offset section_size) WABT_WARN_UNUSED; Result ReadElemSection(Offset section_size) WABT_WARN_UNUSED; Result ReadCodeSection(Offset section_size) WABT_WARN_UNUSED; Result ReadDataSection(Offset section_size) WABT_WARN_UNUSED; Result ReadExceptionSection(Offset section_size) WABT_WARN_UNUSED; Result ReadSections() WABT_WARN_UNUSED; Result ReportUnexpectedOpcode(Opcode opcode, const char* message = nullptr); size_t read_end_ = 0; // Either the section end or data_size. BinaryReaderDelegate::State state_; BinaryReaderLogging logging_delegate_; BinaryReaderDelegate* delegate_ = nullptr; TypeVector param_types_; TypeVector result_types_; std::vector<Index> target_depths_; const ReadBinaryOptions* options_ = nullptr; BinarySection last_known_section_ = BinarySection::Invalid; bool did_read_names_section_ = false; bool reading_custom_section_ = false; Index num_signatures_ = 0; Index num_imports_ = 0; Index num_func_imports_ = 0; Index num_table_imports_ = 0; Index num_memory_imports_ = 0; Index num_global_imports_ = 0; Index num_exception_imports_ = 0; Index num_function_signatures_ = 0; Index num_tables_ = 0; Index num_memories_ = 0; Index num_globals_ = 0; Index num_exports_ = 0; Index num_function_bodies_ = 0; Index num_exceptions_ = 0; using ReadEndRestoreGuard = ValueRestoreGuard<size_t, &BinaryReader::read_end_>; }; BinaryReader::BinaryReader(const void* data, size_t size, BinaryReaderDelegate* delegate, const ReadBinaryOptions* options) : read_end_(size), state_(static_cast<const uint8_t*>(data), size), logging_delegate_(options->log_stream, delegate), delegate_(options->log_stream ? &logging_delegate_ : delegate), options_(options), last_known_section_(BinarySection::Invalid) { delegate->OnSetState(&state_); } void WABT_PRINTF_FORMAT(2, 3) BinaryReader::PrintError(const char* format, ...) { ErrorLevel error_level = reading_custom_section_ && !options_->fail_on_custom_section_error ? ErrorLevel::Warning : ErrorLevel::Error; WABT_SNPRINTF_ALLOCA(buffer, length, format); bool handled = delegate_->OnError(error_level, buffer); if (!handled) { // Not great to just print, but we don't want to eat the error either. fprintf(stderr, "%07" PRIzx ": %s: %s\n", state_.offset, GetErrorLevelName(error_level), buffer); } } Result BinaryReader::ReportUnexpectedOpcode(Opcode opcode, const char* message) { const char* maybe_space = " "; if (!message) { message = maybe_space = ""; } if (opcode.HasPrefix()) { PrintError("unexpected opcode%s%s: %d %d (0x%x 0x%x)", maybe_space, message, opcode.GetPrefix(), opcode.GetCode(), opcode.GetPrefix(), opcode.GetCode()); } else { PrintError("unexpected opcode%s%s: %d (0x%x)", maybe_space, message, opcode.GetCode(), opcode.GetCode()); } return Result::Error; } Result BinaryReader::ReadOpcode(Opcode* out_value, const char* desc) { uint8_t value = 0; CHECK_RESULT(ReadU8(&value, desc)); if (Opcode::IsPrefixByte(value)) { uint32_t code; CHECK_RESULT(ReadU32Leb128(&code, desc)); *out_value = Opcode::FromCode(value, code); } else { *out_value = Opcode::FromCode(value); } return Result::Ok; } template <typename T> Result BinaryReader::ReadT(T* out_value, const char* type_name, const char* desc) { if (state_.offset + sizeof(T) > read_end_) { PrintError("unable to read %s: %s", type_name, desc); return Result::Error; } memcpy(out_value, state_.data + state_.offset, sizeof(T)); state_.offset += sizeof(T); return Result::Ok; } Result BinaryReader::ReadU8(uint8_t* out_value, const char* desc) { return ReadT(out_value, "uint8_t", desc); } Result BinaryReader::ReadU32(uint32_t* out_value, const char* desc) { return ReadT(out_value, "uint32_t", desc); } Result BinaryReader::ReadF32(uint32_t* out_value, const char* desc) { return ReadT(out_value, "float", desc); } Result BinaryReader::ReadF64(uint64_t* out_value, const char* desc) { return ReadT(out_value, "double", desc); } Result BinaryReader::ReadV128(v128* out_value, const char* desc) { return ReadT(out_value, "v128", desc); } Result BinaryReader::ReadU32Leb128(uint32_t* out_value, const char* desc) { const uint8_t* p = state_.data + state_.offset; const uint8_t* end = state_.data + read_end_; size_t bytes_read = wabt::ReadU32Leb128(p, end, out_value); ERROR_UNLESS(bytes_read > 0, "unable to read u32 leb128: %s", desc); state_.offset += bytes_read; return Result::Ok; } Result BinaryReader::ReadS32Leb128(uint32_t* out_value, const char* desc) { const uint8_t* p = state_.data + state_.offset; const uint8_t* end = state_.data + read_end_; size_t bytes_read = wabt::ReadS32Leb128(p, end, out_value); ERROR_UNLESS(bytes_read > 0, "unable to read i32 leb128: %s", desc); state_.offset += bytes_read; return Result::Ok; } Result BinaryReader::ReadS64Leb128(uint64_t* out_value, const char* desc) { const uint8_t* p = state_.data + state_.offset; const uint8_t* end = state_.data + read_end_; size_t bytes_read = wabt::ReadS64Leb128(p, end, out_value); ERROR_UNLESS(bytes_read > 0, "unable to read i64 leb128: %s", desc); state_.offset += bytes_read; return Result::Ok; } Result BinaryReader::ReadType(Type* out_value, const char* desc) { uint32_t type = 0; CHECK_RESULT(ReadS32Leb128(&type, desc)); *out_value = static_cast<Type>(type); return Result::Ok; } Result BinaryReader::ReadStr(string_view* out_str, const char* desc) { uint32_t str_len = 0; CHECK_RESULT(ReadU32Leb128(&str_len, "string length")); ERROR_UNLESS(state_.offset + str_len <= read_end_, "unable to read string: %s", desc); *out_str = string_view( reinterpret_cast<const char*>(state_.data) + state_.offset, str_len); state_.offset += str_len; ERROR_UNLESS(IsValidUtf8(out_str->data(), out_str->length()), "invalid utf-8 encoding: %s", desc); return Result::Ok; } Result BinaryReader::ReadBytes(const void** out_data, Address* out_data_size, const char* desc) { uint32_t data_size = 0; CHECK_RESULT(ReadU32Leb128(&data_size, "data size")); ERROR_UNLESS(state_.offset + data_size <= read_end_, "unable to read data: %s", desc); *out_data = static_cast<const uint8_t*>(state_.data) + state_.offset; *out_data_size = data_size; state_.offset += data_size; return Result::Ok; } Result BinaryReader::ReadIndex(Index* index, const char* desc) { uint32_t value; CHECK_RESULT(ReadU32Leb128(&value, desc)); *index = value; return Result::Ok; } Result BinaryReader::ReadOffset(Offset* offset, const char* desc) { uint32_t value; CHECK_RESULT(ReadU32Leb128(&value, desc)); *offset = value; return Result::Ok; } Result BinaryReader::ReadCount(Index* count, const char* desc) { CHECK_RESULT(ReadIndex(count, desc)); // This check assumes that each item follows in this section, and takes at // least 1 byte. It's possible that this check passes but reading fails // later. It is still useful to check here, though, because it early-outs // when an erroneous large count is used, before allocating memory for it. size_t section_remaining = read_end_ - state_.offset; if (*count > section_remaining) { PrintError("invalid %s %" PRIindex ", only %" PRIzd " bytes left in section", desc, *count, section_remaining); return Result::Error; } return Result::Ok; } static bool is_valid_external_kind(uint8_t kind) { return kind < kExternalKindCount; } bool BinaryReader::IsConcreteType(Type type) { switch (type) { case Type::I32: case Type::I64: case Type::F32: case Type::F64: return true; case Type::V128: return options_->features.simd_enabled(); default: return false; } } bool BinaryReader::IsBlockType(Type type) { if (IsConcreteType(type) || type == Type::Void) { return true; } if (!(options_->features.multi_value_enabled() && IsTypeIndex(type))) { return false; } return GetTypeIndex(type) < num_signatures_; } Index BinaryReader::NumTotalFuncs() { return num_func_imports_ + num_function_signatures_; } Index BinaryReader::NumTotalTables() { return num_table_imports_ + num_tables_; } Index BinaryReader::NumTotalMemories() { return num_memory_imports_ + num_memories_; } Index BinaryReader::NumTotalGlobals() { return num_global_imports_ + num_globals_; } Result BinaryReader::ReadI32InitExpr(Index index) { return ReadInitExpr(index, true); } Result BinaryReader::ReadInitExpr(Index index, bool require_i32) { Opcode opcode; CHECK_RESULT(ReadOpcode(&opcode, "opcode")); switch (opcode) { case Opcode::I32Const: { uint32_t value = 0; CHECK_RESULT(ReadS32Leb128(&value, "init_expr i32.const value")); CALLBACK(OnInitExprI32ConstExpr, index, value); break; } case Opcode::I64Const: { uint64_t value = 0; CHECK_RESULT(ReadS64Leb128(&value, "init_expr i64.const value")); CALLBACK(OnInitExprI64ConstExpr, index, value); break; } case Opcode::F32Const: { uint32_t value_bits = 0; CHECK_RESULT(ReadF32(&value_bits, "init_expr f32.const value")); CALLBACK(OnInitExprF32ConstExpr, index, value_bits); break; } case Opcode::F64Const: { uint64_t value_bits = 0; CHECK_RESULT(ReadF64(&value_bits, "init_expr f64.const value")); CALLBACK(OnInitExprF64ConstExpr, index, value_bits); break; } case Opcode::V128Const: { ERROR_UNLESS_OPCODE_ENABLED(opcode); v128 value_bits; ZeroMemory(value_bits); CHECK_RESULT(ReadV128(&value_bits, "init_expr v128.const value")); CALLBACK(OnInitExprV128ConstExpr, index, value_bits); break; } case Opcode::GetGlobal: { Index global_index; CHECK_RESULT(ReadIndex(&global_index, "init_expr get_global index")); CALLBACK(OnInitExprGetGlobalExpr, index, global_index); break; } case Opcode::End: return Result::Ok; default: return ReportUnexpectedOpcode(opcode, "in initializer expression"); } if (require_i32 && opcode != Opcode::I32Const && opcode != Opcode::GetGlobal) { PrintError("expected i32 init_expr"); return Result::Error; } CHECK_RESULT(ReadOpcode(&opcode, "opcode")); ERROR_UNLESS(opcode == Opcode::End, "expected END opcode after initializer expression"); return Result::Ok; } Result BinaryReader::ReadTable(Type* out_elem_type, Limits* out_elem_limits) { CHECK_RESULT(ReadType(out_elem_type, "table elem type")); ERROR_UNLESS(*out_elem_type == Type::Anyfunc, "table elem type must by anyfunc"); uint32_t flags; uint32_t initial; uint32_t max = 0; CHECK_RESULT(ReadU32Leb128(&flags, "table flags")); CHECK_RESULT(ReadU32Leb128(&initial, "table initial elem count")); bool has_max = flags & WABT_BINARY_LIMITS_HAS_MAX_FLAG; bool is_shared = flags & WABT_BINARY_LIMITS_IS_SHARED_FLAG; ERROR_UNLESS(!is_shared, "tables may not be shared"); if (has_max) { CHECK_RESULT(ReadU32Leb128(&max, "table max elem count")); ERROR_UNLESS(initial <= max, "table initial elem count must be <= max elem count"); } out_elem_limits->has_max = has_max; out_elem_limits->initial = initial; out_elem_limits->max = max; return Result::Ok; } Result BinaryReader::ReadMemory(Limits* out_page_limits) { uint32_t flags; uint32_t initial; uint32_t max = 0; CHECK_RESULT(ReadU32Leb128(&flags, "memory flags")); CHECK_RESULT(ReadU32Leb128(&initial, "memory initial page count")); ERROR_UNLESS(initial <= WABT_MAX_PAGES, "invalid memory initial size"); bool has_max = flags & WABT_BINARY_LIMITS_HAS_MAX_FLAG; bool is_shared = flags & WABT_BINARY_LIMITS_IS_SHARED_FLAG; ERROR_UNLESS(!is_shared || has_max, "shared memory must have a max size"); if (has_max) { CHECK_RESULT(ReadU32Leb128(&max, "memory max page count")); ERROR_UNLESS(max <= WABT_MAX_PAGES, "invalid memory max size"); ERROR_UNLESS(initial <= max, "memory initial size must be <= max size"); } out_page_limits->has_max = has_max; out_page_limits->is_shared = is_shared; out_page_limits->initial = initial; out_page_limits->max = max; return Result::Ok; } Result BinaryReader::ReadGlobalHeader(Type* out_type, bool* out_mutable) { Type global_type = Type::Void; uint8_t mutable_ = 0; CHECK_RESULT(ReadType(&global_type, "global type")); ERROR_UNLESS(IsConcreteType(global_type), "invalid global type: %#x", static_cast<int>(global_type)); CHECK_RESULT(ReadU8(&mutable_, "global mutability")); ERROR_UNLESS(mutable_ <= 1, "global mutability must be 0 or 1"); *out_type = global_type; *out_mutable = mutable_; return Result::Ok; } Result BinaryReader::ReadFunctionBody(Offset end_offset) { bool seen_end_opcode = false; while (state_.offset < end_offset) { Opcode opcode; CHECK_RESULT(ReadOpcode(&opcode, "opcode")); CALLBACK(OnOpcode, opcode); switch (opcode) { case Opcode::Unreachable: CALLBACK0(OnUnreachableExpr); CALLBACK0(OnOpcodeBare); break; case Opcode::Block: { Type sig_type; CHECK_RESULT(ReadType(&sig_type, "block signature type")); ERROR_UNLESS(IsBlockType(sig_type), "expected valid block signature type"); CALLBACK(OnBlockExpr, sig_type); CALLBACK(OnOpcodeBlockSig, sig_type); break; } case Opcode::Loop: { Type sig_type; CHECK_RESULT(ReadType(&sig_type, "loop signature type")); ERROR_UNLESS(IsBlockType(sig_type), "expected valid block signature type"); CALLBACK(OnLoopExpr, sig_type); CALLBACK(OnOpcodeBlockSig, sig_type); break; } case Opcode::If: { Type sig_type; CHECK_RESULT(ReadType(&sig_type, "if signature type")); ERROR_UNLESS(IsBlockType(sig_type), "expected valid block signature type"); CALLBACK(OnIfExpr, sig_type); CALLBACK(OnOpcodeBlockSig, sig_type); break; } case Opcode::Else: CALLBACK0(OnElseExpr); CALLBACK0(OnOpcodeBare); break; case Opcode::Select: CALLBACK0(OnSelectExpr); CALLBACK0(OnOpcodeBare); break; case Opcode::Br: { Index depth; CHECK_RESULT(ReadIndex(&depth, "br depth")); CALLBACK(OnBrExpr, depth); CALLBACK(OnOpcodeIndex, depth); break; } case Opcode::BrIf: { Index depth; CHECK_RESULT(ReadIndex(&depth, "br_if depth")); CALLBACK(OnBrIfExpr, depth); CALLBACK(OnOpcodeIndex, depth); break; } case Opcode::BrTable: { Index num_targets; CHECK_RESULT(ReadIndex(&num_targets, "br_table target count")); target_depths_.resize(num_targets); for (Index i = 0; i < num_targets; ++i) { Index target_depth; CHECK_RESULT(ReadIndex(&target_depth, "br_table target depth")); target_depths_[i] = target_depth; } Index default_target_depth; CHECK_RESULT( ReadIndex(&default_target_depth, "br_table default target depth")); Index* target_depths = num_targets ? target_depths_.data() : nullptr; CALLBACK(OnBrTableExpr, num_targets, target_depths, default_target_depth); break; } case Opcode::Return: CALLBACK0(OnReturnExpr); CALLBACK0(OnOpcodeBare); break; case Opcode::Nop: CALLBACK0(OnNopExpr); CALLBACK0(OnOpcodeBare); break; case Opcode::Drop: CALLBACK0(OnDropExpr); CALLBACK0(OnOpcodeBare); break; case Opcode::End: if (state_.offset == end_offset) { seen_end_opcode = true; CALLBACK0(OnEndFunc); } else { CALLBACK0(OnEndExpr); } break; case Opcode::I32Const: { uint32_t value; CHECK_RESULT(ReadS32Leb128(&value, "i32.const value")); CALLBACK(OnI32ConstExpr, value); CALLBACK(OnOpcodeUint32, value); break; } case Opcode::I64Const: { uint64_t value; CHECK_RESULT(ReadS64Leb128(&value, "i64.const value")); CALLBACK(OnI64ConstExpr, value); CALLBACK(OnOpcodeUint64, value); break; } case Opcode::F32Const: { uint32_t value_bits = 0; CHECK_RESULT(ReadF32(&value_bits, "f32.const value")); CALLBACK(OnF32ConstExpr, value_bits); CALLBACK(OnOpcodeF32, value_bits); break; } case Opcode::F64Const: { uint64_t value_bits = 0; CHECK_RESULT(ReadF64(&value_bits, "f64.const value")); CALLBACK(OnF64ConstExpr, value_bits); CALLBACK(OnOpcodeF64, value_bits); break; } case Opcode::V128Const: { ERROR_UNLESS_OPCODE_ENABLED(opcode); v128 value_bits; ZeroMemory(value_bits); CHECK_RESULT(ReadV128(&value_bits, "v128.const value")); CALLBACK(OnV128ConstExpr, value_bits); CALLBACK(OnOpcodeV128, value_bits); break; } case Opcode::GetGlobal: { Index global_index; CHECK_RESULT(ReadIndex(&global_index, "get_global global index")); CALLBACK(OnGetGlobalExpr, global_index); CALLBACK(OnOpcodeIndex, global_index); break; } case Opcode::GetLocal: { Index local_index; CHECK_RESULT(ReadIndex(&local_index, "get_local local index")); CALLBACK(OnGetLocalExpr, local_index); CALLBACK(OnOpcodeIndex, local_index); break; } case Opcode::SetGlobal: { Index global_index; CHECK_RESULT(ReadIndex(&global_index, "set_global global index")); CALLBACK(OnSetGlobalExpr, global_index); CALLBACK(OnOpcodeIndex, global_index); break; } case Opcode::SetLocal: { Index local_index; CHECK_RESULT(ReadIndex(&local_index, "set_local local index")); CALLBACK(OnSetLocalExpr, local_index); CALLBACK(OnOpcodeIndex, local_index); break; } case Opcode::Call: { Index func_index; CHECK_RESULT(ReadIndex(&func_index, "call function index")); ERROR_UNLESS(func_index < NumTotalFuncs(), "invalid call function index: %" PRIindex, func_index); CALLBACK(OnCallExpr, func_index); CALLBACK(OnOpcodeIndex, func_index); break; } case Opcode::CallIndirect: { Index sig_index; CHECK_RESULT(ReadIndex(&sig_index, "call_indirect signature index")); ERROR_UNLESS(sig_index < num_signatures_, "invalid call_indirect signature index"); uint32_t reserved; CHECK_RESULT(ReadU32Leb128(&reserved, "call_indirect reserved")); ERROR_UNLESS(reserved == 0, "call_indirect reserved value must be 0"); CALLBACK(OnCallIndirectExpr, sig_index); CALLBACK(OnOpcodeUint32Uint32, sig_index, reserved); break; } case Opcode::TeeLocal: { Index local_index; CHECK_RESULT(ReadIndex(&local_index, "tee_local local index")); CALLBACK(OnTeeLocalExpr, local_index); CALLBACK(OnOpcodeIndex, local_index); break; } case Opcode::I32Load8S: case Opcode::I32Load8U: case Opcode::I32Load16S: case Opcode::I32Load16U: case Opcode::I64Load8S: case Opcode::I64Load8U: case Opcode::I64Load16S: case Opcode::I64Load16U: case Opcode::I64Load32S: case Opcode::I64Load32U: case Opcode::I32Load: case Opcode::I64Load: case Opcode::F32Load: case Opcode::F64Load: case Opcode::V128Load: { uint32_t alignment_log2; CHECK_RESULT(ReadU32Leb128(&alignment_log2, "load alignment")); Address offset; CHECK_RESULT(ReadU32Leb128(&offset, "load offset")); CALLBACK(OnLoadExpr, opcode, alignment_log2, offset); CALLBACK(OnOpcodeUint32Uint32, alignment_log2, offset); break; } case Opcode::I32Store8: case Opcode::I32Store16: case Opcode::I64Store8: case Opcode::I64Store16: case Opcode::I64Store32: case Opcode::I32Store: case Opcode::I64Store: case Opcode::F32Store: case Opcode::F64Store: case Opcode::V128Store: { uint32_t alignment_log2; CHECK_RESULT(ReadU32Leb128(&alignment_log2, "store alignment")); Address offset; CHECK_RESULT(ReadU32Leb128(&offset, "store offset")); CALLBACK(OnStoreExpr, opcode, alignment_log2, offset); CALLBACK(OnOpcodeUint32Uint32, alignment_log2, offset); break; } case Opcode::MemorySize: { uint32_t reserved; CHECK_RESULT(ReadU32Leb128(&reserved, "memory.size reserved")); ERROR_UNLESS(reserved == 0, "memory.size reserved value must be 0"); CALLBACK0(OnMemorySizeExpr); CALLBACK(OnOpcodeUint32, reserved); break; } case Opcode::MemoryGrow: { uint32_t reserved; CHECK_RESULT(ReadU32Leb128(&reserved, "memory.grow reserved")); ERROR_UNLESS(reserved == 0, "memory.grow reserved value must be 0"); CALLBACK0(OnMemoryGrowExpr); CALLBACK(OnOpcodeUint32, reserved); break; } case Opcode::I32Add: case Opcode::I32Sub: case Opcode::I32Mul: case Opcode::I32DivS: case Opcode::I32DivU: case Opcode::I32RemS: case Opcode::I32RemU: case Opcode::I32And: case Opcode::I32Or: case Opcode::I32Xor: case Opcode::I32Shl: case Opcode::I32ShrU: case Opcode::I32ShrS: case Opcode::I32Rotr: case Opcode::I32Rotl: case Opcode::I64Add: case Opcode::I64Sub: case Opcode::I64Mul: case Opcode::I64DivS: case Opcode::I64DivU: case Opcode::I64RemS: case Opcode::I64RemU: case Opcode::I64And: case Opcode::I64Or: case Opcode::I64Xor: case Opcode::I64Shl: case Opcode::I64ShrU: case Opcode::I64ShrS: case Opcode::I64Rotr: case Opcode::I64Rotl: case Opcode::F32Add: case Opcode::F32Sub: case Opcode::F32Mul: case Opcode::F32Div: case Opcode::F32Min: case Opcode::F32Max: case Opcode::F32Copysign: case Opcode::F64Add: case Opcode::F64Sub: case Opcode::F64Mul: case Opcode::F64Div: case Opcode::F64Min: case Opcode::F64Max: case Opcode::F64Copysign: case Opcode::I8X16Add: case Opcode::I16X8Add: case Opcode::I32X4Add: case Opcode::I64X2Add: case Opcode::I8X16Sub: case Opcode::I16X8Sub: case Opcode::I32X4Sub: case Opcode::I64X2Sub: case Opcode::I8X16Mul: case Opcode::I16X8Mul: case Opcode::I32X4Mul: case Opcode::I8X16AddSaturateS: case Opcode::I8X16AddSaturateU: case Opcode::I16X8AddSaturateS: case Opcode::I16X8AddSaturateU: case Opcode::I8X16SubSaturateS: case Opcode::I8X16SubSaturateU: case Opcode::I16X8SubSaturateS: case Opcode::I16X8SubSaturateU: case Opcode::I8X16Shl: case Opcode::I16X8Shl: case Opcode::I32X4Shl: case Opcode::I64X2Shl: case Opcode::I8X16ShrS: case Opcode::I8X16ShrU: case Opcode::I16X8ShrS: case Opcode::I16X8ShrU: case Opcode::I32X4ShrS: case Opcode::I32X4ShrU: case Opcode::I64X2ShrS: case Opcode::I64X2ShrU: case Opcode::V128And: case Opcode::V128Or: case Opcode::V128Xor: case Opcode::F32X4Min: case Opcode::F64X2Min: case Opcode::F32X4Max: case Opcode::F64X2Max: case Opcode::F32X4Add: case Opcode::F64X2Add: case Opcode::F32X4Sub: case Opcode::F64X2Sub: case Opcode::F32X4Div: case Opcode::F64X2Div: case Opcode::F32X4Mul: case Opcode::F64X2Mul: ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK(OnBinaryExpr, opcode); CALLBACK0(OnOpcodeBare); break; case Opcode::I32Eq: case Opcode::I32Ne: case Opcode::I32LtS: case Opcode::I32LeS: case Opcode::I32LtU: case Opcode::I32LeU: case Opcode::I32GtS: case Opcode::I32GeS: case Opcode::I32GtU: case Opcode::I32GeU: case Opcode::I64Eq: case Opcode::I64Ne: case Opcode::I64LtS: case Opcode::I64LeS: case Opcode::I64LtU: case Opcode::I64LeU: case Opcode::I64GtS: case Opcode::I64GeS: case Opcode::I64GtU: case Opcode::I64GeU: case Opcode::F32Eq: case Opcode::F32Ne: case Opcode::F32Lt: case Opcode::F32Le: case Opcode::F32Gt: case Opcode::F32Ge: case Opcode::F64Eq: case Opcode::F64Ne: case Opcode::F64Lt: case Opcode::F64Le: case Opcode::F64Gt: case Opcode::F64Ge: case Opcode::I8X16Eq: case Opcode::I16X8Eq: case Opcode::I32X4Eq: case Opcode::F32X4Eq: case Opcode::F64X2Eq: case Opcode::I8X16Ne: case Opcode::I16X8Ne: case Opcode::I32X4Ne: case Opcode::F32X4Ne: case Opcode::F64X2Ne: case Opcode::I8X16LtS: case Opcode::I8X16LtU: case Opcode::I16X8LtS: case Opcode::I16X8LtU: case Opcode::I32X4LtS: case Opcode::I32X4LtU: case Opcode::F32X4Lt: case Opcode::F64X2Lt: case Opcode::I8X16LeS: case Opcode::I8X16LeU: case Opcode::I16X8LeS: case Opcode::I16X8LeU: case Opcode::I32X4LeS: case Opcode::I32X4LeU: case Opcode::F32X4Le: case Opcode::F64X2Le: case Opcode::I8X16GtS: case Opcode::I8X16GtU: case Opcode::I16X8GtS: case Opcode::I16X8GtU: case Opcode::I32X4GtS: case Opcode::I32X4GtU: case Opcode::F32X4Gt: case Opcode::F64X2Gt: case Opcode::I8X16GeS: case Opcode::I8X16GeU: case Opcode::I16X8GeS: case Opcode::I16X8GeU: case Opcode::I32X4GeS: case Opcode::I32X4GeU: case Opcode::F32X4Ge: case Opcode::F64X2Ge: ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK(OnCompareExpr, opcode); CALLBACK0(OnOpcodeBare); break; case Opcode::I32Clz: case Opcode::I32Ctz: case Opcode::I32Popcnt: case Opcode::I64Clz: case Opcode::I64Ctz: case Opcode::I64Popcnt: case Opcode::F32Abs: case Opcode::F32Neg: case Opcode::F32Ceil: case Opcode::F32Floor: case Opcode::F32Trunc: case Opcode::F32Nearest: case Opcode::F32Sqrt: case Opcode::F64Abs: case Opcode::F64Neg: case Opcode::F64Ceil: case Opcode::F64Floor: case Opcode::F64Trunc: case Opcode::F64Nearest: case Opcode::F64Sqrt: case Opcode::I8X16Splat: case Opcode::I16X8Splat: case Opcode::I32X4Splat: case Opcode::I64X2Splat: case Opcode::F32X4Splat: case Opcode::F64X2Splat: case Opcode::I8X16Neg: case Opcode::I16X8Neg: case Opcode::I32X4Neg: case Opcode::I64X2Neg: case Opcode::V128Not: case Opcode::I8X16AnyTrue: case Opcode::I16X8AnyTrue: case Opcode::I32X4AnyTrue: case Opcode::I64X2AnyTrue: case Opcode::I8X16AllTrue: case Opcode::I16X8AllTrue: case Opcode::I32X4AllTrue: case Opcode::I64X2AllTrue: case Opcode::F32X4Neg: case Opcode::F64X2Neg: case Opcode::F32X4Abs: case Opcode::F64X2Abs: case Opcode::F32X4Sqrt: case Opcode::F64X2Sqrt: ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK(OnUnaryExpr, opcode); CALLBACK0(OnOpcodeBare); break; case Opcode::V128BitSelect: ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK(OnTernaryExpr, opcode); CALLBACK0(OnOpcodeBare); break; case Opcode::I8X16ExtractLaneS: case Opcode::I8X16ExtractLaneU: case Opcode::I16X8ExtractLaneS: case Opcode::I16X8ExtractLaneU: case Opcode::I32X4ExtractLane: case Opcode::I64X2ExtractLane: case Opcode::F32X4ExtractLane: case Opcode::F64X2ExtractLane: case Opcode::I8X16ReplaceLane: case Opcode::I16X8ReplaceLane: case Opcode::I32X4ReplaceLane: case Opcode::I64X2ReplaceLane: case Opcode::F32X4ReplaceLane: case Opcode::F64X2ReplaceLane: { ERROR_UNLESS_OPCODE_ENABLED(opcode); uint8_t lane_val; CHECK_RESULT(ReadU8(&lane_val, "Lane idx")); CALLBACK(OnSimdLaneOpExpr, opcode, lane_val); CALLBACK(OnOpcodeUint64, lane_val); break; } case Opcode::V8X16Shuffle: { ERROR_UNLESS_OPCODE_ENABLED(opcode); v128 value; CHECK_RESULT(ReadV128(&value, "Lane idx [16]")); CALLBACK(OnSimdShuffleOpExpr, opcode, value); CALLBACK(OnOpcodeV128, value); break; } case Opcode::I32TruncSF32: case Opcode::I32TruncSF64: case Opcode::I32TruncUF32: case Opcode::I32TruncUF64: case Opcode::I32WrapI64: case Opcode::I64TruncSF32: case Opcode::I64TruncSF64: case Opcode::I64TruncUF32: case Opcode::I64TruncUF64: case Opcode::I64ExtendSI32: case Opcode::I64ExtendUI32: case Opcode::F32ConvertSI32: case Opcode::F32ConvertUI32: case Opcode::F32ConvertSI64: case Opcode::F32ConvertUI64: case Opcode::F32DemoteF64: case Opcode::F32ReinterpretI32: case Opcode::F64ConvertSI32: case Opcode::F64ConvertUI32: case Opcode::F64ConvertSI64: case Opcode::F64ConvertUI64: case Opcode::F64PromoteF32: case Opcode::F64ReinterpretI64: case Opcode::I32ReinterpretF32: case Opcode::I64ReinterpretF64: case Opcode::I32Eqz: case Opcode::I64Eqz: case Opcode::F32X4ConvertSI32X4: case Opcode::F32X4ConvertUI32X4: case Opcode::F64X2ConvertSI64X2: case Opcode::F64X2ConvertUI64X2: case Opcode::I32X4TruncSF32X4Sat: case Opcode::I32X4TruncUF32X4Sat: case Opcode::I64X2TruncSF64X2Sat: case Opcode::I64X2TruncUF64X2Sat: ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK(OnConvertExpr, opcode); CALLBACK0(OnOpcodeBare); break; case Opcode::Try: { ERROR_UNLESS_OPCODE_ENABLED(opcode); Type sig_type; CHECK_RESULT(ReadType(&sig_type, "try signature type")); ERROR_UNLESS(IsBlockType(sig_type), "expected valid block signature type"); CALLBACK(OnTryExpr, sig_type); CALLBACK(OnOpcodeBlockSig, sig_type); break; } case Opcode::Catch: { ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK0(OnCatchExpr); CALLBACK0(OnOpcodeBare); break; } case Opcode::Rethrow: { ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK0(OnRethrowExpr); CALLBACK0(OnOpcodeBare); break; } case Opcode::Throw: { ERROR_UNLESS_OPCODE_ENABLED(opcode); Index index; CHECK_RESULT(ReadIndex(&index, "exception index")); CALLBACK(OnThrowExpr, index); CALLBACK(OnOpcodeIndex, index); break; } case Opcode::IfExcept: { ERROR_UNLESS_OPCODE_ENABLED(opcode); Type sig_type; CHECK_RESULT(ReadType(&sig_type, "if signature type")); ERROR_UNLESS(IsBlockType(sig_type), "expected valid block signature type"); Index except_index; CHECK_RESULT(ReadIndex(&except_index, "exception index")); CALLBACK(OnIfExceptExpr, sig_type, except_index); break; } case Opcode::I32Extend8S: case Opcode::I32Extend16S: case Opcode::I64Extend8S: case Opcode::I64Extend16S: case Opcode::I64Extend32S: ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK(OnUnaryExpr, opcode); CALLBACK0(OnOpcodeBare); break; case Opcode::I32TruncSSatF32: case Opcode::I32TruncUSatF32: case Opcode::I32TruncSSatF64: case Opcode::I32TruncUSatF64: case Opcode::I64TruncSSatF32: case Opcode::I64TruncUSatF32: case Opcode::I64TruncSSatF64: case Opcode::I64TruncUSatF64: ERROR_UNLESS_OPCODE_ENABLED(opcode); CALLBACK(OnConvertExpr, opcode); CALLBACK0(OnOpcodeBare); break; case Opcode::AtomicWake: { uint32_t alignment_log2; CHECK_RESULT(ReadU32Leb128(&alignment_log2, "load alignment")); Address offset; CHECK_RESULT(ReadU32Leb128(&offset, "load offset")); CALLBACK(OnAtomicWakeExpr, opcode, alignment_log2, offset); CALLBACK(OnOpcodeUint32Uint32, alignment_log2, offset); break; } case Opcode::I32AtomicWait: case Opcode::I64AtomicWait: { uint32_t alignment_log2; CHECK_RESULT(ReadU32Leb128(&alignment_log2, "load alignment")); Address offset; CHECK_RESULT(ReadU32Leb128(&offset, "load offset")); CALLBACK(OnAtomicWaitExpr, opcode, alignment_log2, offset); CALLBACK(OnOpcodeUint32Uint32, alignment_log2, offset); break; } case Opcode::I32AtomicLoad8U: case Opcode::I32AtomicLoad16U: case Opcode::I64AtomicLoad8U: case Opcode::I64AtomicLoad16U: case Opcode::I64AtomicLoad32U: case Opcode::I32AtomicLoad: case Opcode::I64AtomicLoad: { uint32_t alignment_log2; CHECK_RESULT(ReadU32Leb128(&alignment_log2, "load alignment")); Address offset; CHECK_RESULT(ReadU32Leb128(&offset, "load offset")); CALLBACK(OnAtomicLoadExpr, opcode, alignment_log2, offset); CALLBACK(OnOpcodeUint32Uint32, alignment_log2, offset); break; } case Opcode::I32AtomicStore8: case Opcode::I32AtomicStore16: case Opcode::I64AtomicStore8: case Opcode::I64AtomicStore16: case Opcode::I64AtomicStore32: case Opcode::I32AtomicStore: case Opcode::I64AtomicStore: { uint32_t alignment_log2; CHECK_RESULT(ReadU32Leb128(&alignment_log2, "store alignment")); Address offset; CHECK_RESULT(ReadU32Leb128(&offset, "store offset")); CALLBACK(OnAtomicStoreExpr, opcode, alignment_log2, offset); CALLBACK(OnOpcodeUint32Uint32, alignment_log2, offset); break; } case Opcode::I32AtomicRmwAdd: case Opcode::I64AtomicRmwAdd: case Opcode::I32AtomicRmw8UAdd: case Opcode::I32AtomicRmw16UAdd: case Opcode::I64AtomicRmw8UAdd: case Opcode::I64AtomicRmw16UAdd: case Opcode::I64AtomicRmw32UAdd: case Opcode::I32AtomicRmwSub: case Opcode::I64AtomicRmwSub: case Opcode::I32AtomicRmw8USub: case Opcode::I32AtomicRmw16USub: case Opcode::I64AtomicRmw8USub: case Opcode::I64AtomicRmw16USub: case Opcode::I64AtomicRmw32USub: case Opcode::I32AtomicRmwAnd: case Opcode::I64AtomicRmwAnd: case Opcode::I32AtomicRmw8UAnd: case Opcode::I32AtomicRmw16UAnd: case Opcode::I64AtomicRmw8UAnd: case Opcode::I64AtomicRmw16UAnd: case Opcode::I64AtomicRmw32UAnd: case Opcode::I32AtomicRmwOr: case Opcode::I64AtomicRmwOr: case Opcode::I32AtomicRmw8UOr: case Opcode::I32AtomicRmw16UOr: case Opcode::I64AtomicRmw8UOr: case Opcode::I64AtomicRmw16UOr: case Opcode::I64AtomicRmw32UOr: case Opcode::I32AtomicRmwXor: case Opcode::I64AtomicRmwXor: case Opcode::I32AtomicRmw8UXor: case Opcode::I32AtomicRmw16UXor: case Opcode::I64AtomicRmw8UXor: case Opcode::I64AtomicRmw16UXor: case Opcode::I64AtomicRmw32UXor: case Opcode::I32AtomicRmwXchg: case Opcode::I64AtomicRmwXchg: case Opcode::I32AtomicRmw8UXchg: case Opcode::I32AtomicRmw16UXchg: case Opcode::I64AtomicRmw8UXchg: case Opcode::I64AtomicRmw16UXchg: case Opcode::I64AtomicRmw32UXchg: { uint32_t alignment_log2; CHECK_RESULT(ReadU32Leb128(&alignment_log2, "memory alignment")); Address offset; CHECK_RESULT(ReadU32Leb128(&offset, "memory offset")); CALLBACK(OnAtomicRmwExpr, opcode, alignment_log2, offset); CALLBACK(OnOpcodeUint32Uint32, alignment_log2, offset); break; } case Opcode::I32AtomicRmwCmpxchg: case Opcode::I64AtomicRmwCmpxchg: case Opcode::I32AtomicRmw8UCmpxchg: case Opcode::I32AtomicRmw16UCmpxchg: case Opcode::I64AtomicRmw8UCmpxchg: case Opcode::I64AtomicRmw16UCmpxchg: case Opcode::I64AtomicRmw32UCmpxchg: { uint32_t alignment_log2; CHECK_RESULT(ReadU32Leb128(&alignment_log2, "memory alignment")); Address offset; CHECK_RESULT(ReadU32Leb128(&offset, "memory offset")); CALLBACK(OnAtomicRmwCmpxchgExpr, opcode, alignment_log2, offset); CALLBACK(OnOpcodeUint32Uint32, alignment_log2, offset); break; } default: return ReportUnexpectedOpcode(opcode); } } ERROR_UNLESS(state_.offset == end_offset, "function body longer than given size"); ERROR_UNLESS(seen_end_opcode, "function body must end with END opcode"); return Result::Ok; } Result BinaryReader::ReadNameSection(Offset section_size) { CALLBACK(BeginNamesSection, section_size); Index i = 0; uint32_t previous_subsection_type = 0; while (state_.offset < read_end_) { uint32_t name_type; Offset subsection_size; CHECK_RESULT(ReadU32Leb128(&name_type, "name type")); if (i != 0) { ERROR_UNLESS(name_type != previous_subsection_type, "duplicate sub-section"); ERROR_UNLESS(name_type >= previous_subsection_type, "out-of-order sub-section"); } previous_subsection_type = name_type; CHECK_RESULT(ReadOffset(&subsection_size, "subsection size")); size_t subsection_end = state_.offset + subsection_size; ERROR_UNLESS(subsection_end <= read_end_, "invalid sub-section size: extends past end"); ReadEndRestoreGuard guard(this); read_end_ = subsection_end; switch (static_cast<NameSectionSubsection>(name_type)) { case NameSectionSubsection::Module: CALLBACK(OnModuleNameSubsection, i, name_type, subsection_size); if (subsection_size) { string_view name; CHECK_RESULT(ReadStr(&name, "module name")); CALLBACK(OnModuleName, name); } break; case NameSectionSubsection::Function: CALLBACK(OnFunctionNameSubsection, i, name_type, subsection_size); if (subsection_size) { Index num_names; CHECK_RESULT(ReadCount(&num_names, "name count")); CALLBACK(OnFunctionNamesCount, num_names); Index last_function_index = kInvalidIndex; for (Index j = 0; j < num_names; ++j) { Index function_index; string_view function_name; CHECK_RESULT(ReadIndex(&function_index, "function index")); ERROR_UNLESS(function_index != last_function_index, "duplicate function name: %u", function_index); ERROR_UNLESS(last_function_index == kInvalidIndex || function_index > last_function_index, "function index out of order: %u", function_index); last_function_index = function_index; ERROR_UNLESS(function_index < NumTotalFuncs(), "invalid function index: %" PRIindex, function_index); CHECK_RESULT(ReadStr(&function_name, "function name")); CALLBACK(OnFunctionName, function_index, function_name); } } break; case NameSectionSubsection::Local: CALLBACK(OnLocalNameSubsection, i, name_type, subsection_size); if (subsection_size) { Index num_funcs; CHECK_RESULT(ReadCount(&num_funcs, "function count")); CALLBACK(OnLocalNameFunctionCount, num_funcs); Index last_function_index = kInvalidIndex; for (Index j = 0; j < num_funcs; ++j) { Index function_index; CHECK_RESULT(ReadIndex(&function_index, "function index")); ERROR_UNLESS(function_index < NumTotalFuncs(), "invalid function index: %u", function_index); ERROR_UNLESS(last_function_index == kInvalidIndex || function_index > last_function_index, "locals function index out of order: %u", function_index); last_function_index = function_index; Index num_locals; CHECK_RESULT(ReadCount(&num_locals, "local count")); CALLBACK(OnLocalNameLocalCount, function_index, num_locals); Index last_local_index = kInvalidIndex; for (Index k = 0; k < num_locals; ++k) { Index local_index; string_view local_name; CHECK_RESULT(ReadIndex(&local_index, "named index")); ERROR_UNLESS(local_index != last_local_index, "duplicate local index: %u", local_index); ERROR_UNLESS(last_local_index == kInvalidIndex || local_index > last_local_index, "local index out of order: %u", local_index); last_local_index = local_index; CHECK_RESULT(ReadStr(&local_name, "name")); CALLBACK(OnLocalName, function_index, local_index, local_name); } } } break; default: // Unknown subsection, skip it. state_.offset = subsection_end; break; } ++i; ERROR_UNLESS(state_.offset == subsection_end, "unfinished sub-section (expected end: 0x%" PRIzx ")", subsection_end); } CALLBACK0(EndNamesSection); return Result::Ok; } Result BinaryReader::ReadRelocSection(Offset section_size) { CALLBACK(BeginRelocSection, section_size); uint32_t section_index; CHECK_RESULT(ReadU32Leb128(&section_index, "section index")); Index num_relocs; CHECK_RESULT(ReadCount(&num_relocs, "relocation count")); CALLBACK(OnRelocCount, num_relocs, section_index); for (Index i = 0; i < num_relocs; ++i) { Offset offset; Index index; uint32_t reloc_type, addend = 0; CHECK_RESULT(ReadU32Leb128(&reloc_type, "relocation type")); CHECK_RESULT(ReadOffset(&offset, "offset")); CHECK_RESULT(ReadIndex(&index, "index")); RelocType type = static_cast<RelocType>(reloc_type); switch (type) { case RelocType::MemoryAddressLEB: case RelocType::MemoryAddressSLEB: case RelocType::MemoryAddressI32: case RelocType::FunctionOffsetI32: case RelocType::SectionOffsetI32: CHECK_RESULT(ReadS32Leb128(&addend, "addend")); break; default: break; } CALLBACK(OnReloc, type, offset, index, addend); } CALLBACK0(EndRelocSection); return Result::Ok; } Result BinaryReader::ReadLinkingSection(Offset section_size) { CALLBACK(BeginLinkingSection, section_size); uint32_t version; CHECK_RESULT(ReadU32Leb128(&version, "version")); ERROR_UNLESS(version == 1, "invalid linking metadata version: %u", version); while (state_.offset < read_end_) { uint32_t linking_type; Offset subsection_size; CHECK_RESULT(ReadU32Leb128(&linking_type, "type")); CHECK_RESULT(ReadOffset(&subsection_size, "subsection size")); size_t subsection_end = state_.offset + subsection_size; ERROR_UNLESS(subsection_end <= read_end_, "invalid sub-section size: extends past end"); ReadEndRestoreGuard guard(this); read_end_ = subsection_end; uint32_t count; switch (static_cast<LinkingEntryType>(linking_type)) { case LinkingEntryType::SymbolTable: CHECK_RESULT(ReadU32Leb128(&count, "sym count")); CALLBACK(OnSymbolCount, count); for (Index i = 0; i < count; ++i) { string_view name; uint32_t flags = 0; uint32_t kind = 0; CHECK_RESULT(ReadU32Leb128(&kind, "sym type")); CHECK_RESULT(ReadU32Leb128(&flags, "sym flags")); SymbolType sym_type = static_cast<SymbolType>(kind); CALLBACK(OnSymbol, i, sym_type, flags); switch (sym_type) { case SymbolType::Function: case SymbolType::Global: { uint32_t index = 0; CHECK_RESULT(ReadU32Leb128(&index, "index")); if ((flags & WABT_SYMBOL_FLAG_UNDEFINED) == 0) CHECK_RESULT(ReadStr(&name, "symbol name")); if (sym_type == SymbolType::Function) { CALLBACK(OnFunctionSymbol, i, flags, name, index); } else { CALLBACK(OnGlobalSymbol, i, flags, name, index); } break; } case SymbolType::Data: { uint32_t segment = 0; uint32_t offset = 0; uint32_t size = 0; CHECK_RESULT(ReadStr(&name, "symbol name")); if ((flags & WABT_SYMBOL_FLAG_UNDEFINED) == 0) { CHECK_RESULT(ReadU32Leb128(&segment, "segment")); CHECK_RESULT(ReadU32Leb128(&offset, "offset")); CHECK_RESULT(ReadU32Leb128(&size, "size")); } CALLBACK(OnDataSymbol, i, flags, name, segment, offset, size); break; } case SymbolType::Section: { uint32_t index = 0; CHECK_RESULT(ReadU32Leb128(&index, "index")); CALLBACK(OnSectionSymbol, i, flags, index); break; } } } break; case LinkingEntryType::SegmentInfo: CHECK_RESULT(ReadU32Leb128(&count, "info count")); CALLBACK(OnSegmentInfoCount, count); for (Index i = 0; i < count; i++) { string_view name; uint32_t alignment; uint32_t flags; CHECK_RESULT(ReadStr(&name, "segment name")); CHECK_RESULT(ReadU32Leb128(&alignment, "segment alignment")); CHECK_RESULT(ReadU32Leb128(&flags, "segment flags")); CALLBACK(OnSegmentInfo, i, name, alignment, flags); } break; case LinkingEntryType::InitFunctions: CHECK_RESULT(ReadU32Leb128(&count, "info count")); CALLBACK(OnInitFunctionCount, count); while (count--) { uint32_t priority; uint32_t func; CHECK_RESULT(ReadU32Leb128(&priority, "priority")); CHECK_RESULT(ReadU32Leb128(&func, "function index")); CALLBACK(OnInitFunction, priority, func); } break; default: // Unknown subsection, skip it. state_.offset = subsection_end; break; } ERROR_UNLESS(state_.offset == subsection_end, "unfinished sub-section (expected end: 0x%" PRIzx ")", subsection_end); } CALLBACK0(EndLinkingSection); return Result::Ok; } Result BinaryReader::ReadExceptionType(TypeVector& sig) { Index num_values; CHECK_RESULT(ReadCount(&num_values, "exception type count")); sig.resize(num_values); for (Index j = 0; j < num_values; ++j) { Type value_type; CHECK_RESULT(ReadType(&value_type, "exception value type")); ERROR_UNLESS(IsConcreteType(value_type), "excepted valid exception value type (got %d)", static_cast<int>(value_type)); sig[j] = value_type; } return Result::Ok; } Result BinaryReader::ReadExceptionSection(Offset section_size) { CALLBACK(BeginExceptionSection, section_size); CHECK_RESULT(ReadCount(&num_exceptions_, "exception count")); CALLBACK(OnExceptionCount, num_exceptions_); for (Index i = 0; i < num_exceptions_; ++i) { TypeVector sig; CHECK_RESULT(ReadExceptionType(sig)); CALLBACK(OnExceptionType, i, sig); } CALLBACK(EndExceptionSection); return Result::Ok; } Result BinaryReader::ReadCustomSection(Offset section_size) { string_view section_name; CHECK_RESULT(ReadStr(&section_name, "section name")); CALLBACK(BeginCustomSection, section_size, section_name); ValueRestoreGuard<bool, &BinaryReader::reading_custom_section_> guard(this); reading_custom_section_ = true; if (options_->read_debug_names && section_name == WABT_BINARY_SECTION_NAME) { CHECK_RESULT(ReadNameSection(section_size)); did_read_names_section_ = true; } else if (section_name.rfind(WABT_BINARY_SECTION_RELOC, 0) == 0) { // Reloc sections always begin with "reloc." CHECK_RESULT(ReadRelocSection(section_size)); } else if (section_name == WABT_BINARY_SECTION_LINKING) { CHECK_RESULT(ReadLinkingSection(section_size)); } else if (options_->features.exceptions_enabled() && section_name == WABT_BINARY_SECTION_EXCEPTION) { CHECK_RESULT(ReadExceptionSection(section_size)); } else { // This is an unknown custom section, skip it. state_.offset = read_end_; } CALLBACK0(EndCustomSection); return Result::Ok; } Result BinaryReader::ReadTypeSection(Offset section_size) { CALLBACK(BeginTypeSection, section_size); CHECK_RESULT(ReadCount(&num_signatures_, "type count")); CALLBACK(OnTypeCount, num_signatures_); for (Index i = 0; i < num_signatures_; ++i) { Type form; CHECK_RESULT(ReadType(&form, "type form")); ERROR_UNLESS(form == Type::Func, "unexpected type form (got " PRItypecode ")", WABT_PRINTF_TYPE_CODE(form)); Index num_params; CHECK_RESULT(ReadCount(&num_params, "function param count")); param_types_.resize(num_params); for (Index j = 0; j < num_params; ++j) { Type param_type; CHECK_RESULT(ReadType(&param_type, "function param type")); ERROR_UNLESS(IsConcreteType(param_type), "expected valid param type (got " PRItypecode ")", WABT_PRINTF_TYPE_CODE(param_type)); param_types_[j] = param_type; } Index num_results; CHECK_RESULT(ReadCount(&num_results, "function result count")); ERROR_UNLESS(num_results <= 1 || options_->features.multi_value_enabled(), "result count must be 0 or 1"); result_types_.resize(num_results); for (Index j = 0; j < num_results; ++j) { Type result_type; CHECK_RESULT(ReadType(&result_type, "function result type")); ERROR_UNLESS(IsConcreteType(result_type), "expected valid result type (got " PRItypecode ")", WABT_PRINTF_TYPE_CODE(result_type)); result_types_[j] = result_type; } Type* param_types = num_params ? param_types_.data() : nullptr; Type* result_types = num_results ? result_types_.data() : nullptr; CALLBACK(OnType, i, num_params, param_types, num_results, result_types); } CALLBACK0(EndTypeSection); return Result::Ok; } Result BinaryReader::ReadImportSection(Offset section_size) { CALLBACK(BeginImportSection, section_size); CHECK_RESULT(ReadCount(&num_imports_, "import count")); CALLBACK(OnImportCount, num_imports_); for (Index i = 0; i < num_imports_; ++i) { string_view module_name; CHECK_RESULT(ReadStr(&module_name, "import module name")); string_view field_name; CHECK_RESULT(ReadStr(&field_name, "import field name")); uint8_t kind; CHECK_RESULT(ReadU8(&kind, "import kind")); switch (static_cast<ExternalKind>(kind)) { case ExternalKind::Func: { Index sig_index; CHECK_RESULT(ReadIndex(&sig_index, "import signature index")); ERROR_UNLESS(sig_index < num_signatures_, "invalid import signature index"); CALLBACK(OnImport, i, module_name, field_name); CALLBACK(OnImportFunc, i, module_name, field_name, num_func_imports_, sig_index); num_func_imports_++; break; } case ExternalKind::Table: { Type elem_type; Limits elem_limits; CHECK_RESULT(ReadTable(&elem_type, &elem_limits)); CALLBACK(OnImport, i, module_name, field_name); CALLBACK(OnImportTable, i, module_name, field_name, num_table_imports_, elem_type, &elem_limits); num_table_imports_++; break; } case ExternalKind::Memory: { Limits page_limits; CHECK_RESULT(ReadMemory(&page_limits)); CALLBACK(OnImport, i, module_name, field_name); CALLBACK(OnImportMemory, i, module_name, field_name, num_memory_imports_, &page_limits); num_memory_imports_++; break; } case ExternalKind::Global: { Type type; bool mutable_; CHECK_RESULT(ReadGlobalHeader(&type, &mutable_)); CALLBACK(OnImport, i, module_name, field_name); CALLBACK(OnImportGlobal, i, module_name, field_name, num_global_imports_, type, mutable_); num_global_imports_++; break; } case ExternalKind::Except: { ERROR_UNLESS(options_->features.exceptions_enabled(), "invalid import exception kind: exceptions not allowed"); TypeVector sig; CHECK_RESULT(ReadExceptionType(sig)); CALLBACK(OnImport, i, module_name, field_name); CALLBACK(OnImportException, i, module_name, field_name, num_exception_imports_, sig); num_exception_imports_++; break; } } } CALLBACK0(EndImportSection); return Result::Ok; } Result BinaryReader::ReadFunctionSection(Offset section_size) { CALLBACK(BeginFunctionSection, section_size); CHECK_RESULT( ReadCount(&num_function_signatures_, "function signature count")); CALLBACK(OnFunctionCount, num_function_signatures_); for (Index i = 0; i < num_function_signatures_; ++i) { Index func_index = num_func_imports_ + i; Index sig_index; CHECK_RESULT(ReadIndex(&sig_index, "function signature index")); ERROR_UNLESS(sig_index < num_signatures_, "invalid function signature index: %" PRIindex, sig_index); CALLBACK(OnFunction, func_index, sig_index); } CALLBACK0(EndFunctionSection); return Result::Ok; } Result BinaryReader::ReadTableSection(Offset section_size) { CALLBACK(BeginTableSection, section_size); CHECK_RESULT(ReadCount(&num_tables_, "table count")); ERROR_UNLESS(num_tables_ <= 1, "table count (%" PRIindex ") must be 0 or 1", num_tables_); CALLBACK(OnTableCount, num_tables_); for (Index i = 0; i < num_tables_; ++i) { Index table_index = num_table_imports_ + i; Type elem_type; Limits elem_limits; CHECK_RESULT(ReadTable(&elem_type, &elem_limits)); CALLBACK(OnTable, table_index, elem_type, &elem_limits); } CALLBACK0(EndTableSection); return Result::Ok; } Result BinaryReader::ReadMemorySection(Offset section_size) { CALLBACK(BeginMemorySection, section_size); CHECK_RESULT(ReadCount(&num_memories_, "memory count")); ERROR_UNLESS(num_memories_ <= 1, "memory count must be 0 or 1"); CALLBACK(OnMemoryCount, num_memories_); for (Index i = 0; i < num_memories_; ++i) { Index memory_index = num_memory_imports_ + i; Limits page_limits; CHECK_RESULT(ReadMemory(&page_limits)); CALLBACK(OnMemory, memory_index, &page_limits); } CALLBACK0(EndMemorySection); return Result::Ok; } Result BinaryReader::ReadGlobalSection(Offset section_size) { CALLBACK(BeginGlobalSection, section_size); CHECK_RESULT(ReadCount(&num_globals_, "global count")); CALLBACK(OnGlobalCount, num_globals_); for (Index i = 0; i < num_globals_; ++i) { Index global_index = num_global_imports_ + i; Type global_type; bool mutable_; CHECK_RESULT(ReadGlobalHeader(&global_type, &mutable_)); CALLBACK(BeginGlobal, global_index, global_type, mutable_); CALLBACK(BeginGlobalInitExpr, global_index); CHECK_RESULT(ReadInitExpr(global_index)); CALLBACK(EndGlobalInitExpr, global_index); CALLBACK(EndGlobal, global_index); } CALLBACK0(EndGlobalSection); return Result::Ok; } Result BinaryReader::ReadExportSection(Offset section_size) { CALLBACK(BeginExportSection, section_size); CHECK_RESULT(ReadCount(&num_exports_, "export count")); CALLBACK(OnExportCount, num_exports_); for (Index i = 0; i < num_exports_; ++i) { string_view name; CHECK_RESULT(ReadStr(&name, "export item name")); uint8_t kind = 0; CHECK_RESULT(ReadU8(&kind, "export kind")); ERROR_UNLESS(is_valid_external_kind(kind), "invalid export external kind: %d", kind); Index item_index; CHECK_RESULT(ReadIndex(&item_index, "export item index")); switch (static_cast<ExternalKind>(kind)) { case ExternalKind::Func: ERROR_UNLESS(item_index < NumTotalFuncs(), "invalid export func index: %" PRIindex, item_index); break; case ExternalKind::Table: ERROR_UNLESS(item_index < NumTotalTables(), "invalid export table index: %" PRIindex, item_index); break; case ExternalKind::Memory: ERROR_UNLESS(item_index < NumTotalMemories(), "invalid export memory index: %" PRIindex, item_index); break; case ExternalKind::Global: ERROR_UNLESS(item_index < NumTotalGlobals(), "invalid export global index: %" PRIindex, item_index); break; case ExternalKind::Except: // Note: Can't check if index valid, exceptions section comes later. ERROR_UNLESS(options_->features.exceptions_enabled(), "invalid export exception kind: exceptions not allowed"); break; } CALLBACK(OnExport, i, static_cast<ExternalKind>(kind), item_index, name); } CALLBACK0(EndExportSection); return Result::Ok; } Result BinaryReader::ReadStartSection(Offset section_size) { CALLBACK(BeginStartSection, section_size); Index func_index; CHECK_RESULT(ReadIndex(&func_index, "start function index")); ERROR_UNLESS(func_index < NumTotalFuncs(), "invalid start function index: %" PRIindex, func_index); CALLBACK(OnStartFunction, func_index); CALLBACK0(EndStartSection); return Result::Ok; } Result BinaryReader::ReadElemSection(Offset section_size) { CALLBACK(BeginElemSection, section_size); Index num_elem_segments; CHECK_RESULT(ReadCount(&num_elem_segments, "elem segment count")); CALLBACK(OnElemSegmentCount, num_elem_segments); ERROR_UNLESS(num_elem_segments == 0 || NumTotalTables() > 0, "elem section without table section"); for (Index i = 0; i < num_elem_segments; ++i) { Index table_index; CHECK_RESULT(ReadIndex(&table_index, "elem segment table index")); CALLBACK(BeginElemSegment, i, table_index); CALLBACK(BeginElemSegmentInitExpr, i); CHECK_RESULT(ReadI32InitExpr(i)); CALLBACK(EndElemSegmentInitExpr, i); Index num_function_indexes; CHECK_RESULT( ReadCount(&num_function_indexes, "elem segment function index count")); CALLBACK(OnElemSegmentFunctionIndexCount, i, num_function_indexes); for (Index j = 0; j < num_function_indexes; ++j) { Index func_index; CHECK_RESULT(ReadIndex(&func_index, "elem segment function index")); CALLBACK(OnElemSegmentFunctionIndex, i, func_index); } CALLBACK(EndElemSegment, i); } CALLBACK0(EndElemSection); return Result::Ok; } Result BinaryReader::ReadCodeSection(Offset section_size) { CALLBACK(BeginCodeSection, section_size); CHECK_RESULT(ReadCount(&num_function_bodies_, "function body count")); ERROR_UNLESS(num_function_signatures_ == num_function_bodies_, "function signature count != function body count"); CALLBACK(OnFunctionBodyCount, num_function_bodies_); for (Index i = 0; i < num_function_bodies_; ++i) { Index func_index = num_func_imports_ + i; Offset func_offset = state_.offset; state_.offset = func_offset; CALLBACK(BeginFunctionBody, func_index); uint32_t body_size; CHECK_RESULT(ReadU32Leb128(&body_size, "function body size")); Offset body_start_offset = state_.offset; Offset end_offset = body_start_offset + body_size; uint64_t total_locals = 0; Index num_local_decls; CHECK_RESULT(ReadCount(&num_local_decls, "local declaration count")); CALLBACK(OnLocalDeclCount, num_local_decls); for (Index k = 0; k < num_local_decls; ++k) { Index num_local_types; CHECK_RESULT(ReadIndex(&num_local_types, "local type count")); ERROR_UNLESS(num_local_types > 0, "local count must be > 0"); total_locals += num_local_types; ERROR_UNLESS(total_locals < UINT32_MAX, "local count must be < 0x10000000"); Type local_type; CHECK_RESULT(ReadType(&local_type, "local type")); ERROR_UNLESS(IsConcreteType(local_type), "expected valid local type"); CALLBACK(OnLocalDecl, k, num_local_types, local_type); } CHECK_RESULT(ReadFunctionBody(end_offset)); CALLBACK(EndFunctionBody, func_index); } CALLBACK0(EndCodeSection); return Result::Ok; } Result BinaryReader::ReadDataSection(Offset section_size) { CALLBACK(BeginDataSection, section_size); Index num_data_segments; CHECK_RESULT(ReadCount(&num_data_segments, "data segment count")); CALLBACK(OnDataSegmentCount, num_data_segments); ERROR_UNLESS(num_data_segments == 0 || NumTotalMemories() > 0, "data section without memory section"); for (Index i = 0; i < num_data_segments; ++i) { Index memory_index; CHECK_RESULT(ReadIndex(&memory_index, "data segment memory index")); CALLBACK(BeginDataSegment, i, memory_index); CALLBACK(BeginDataSegmentInitExpr, i); CHECK_RESULT(ReadI32InitExpr(i)); CALLBACK(EndDataSegmentInitExpr, i); Address data_size; const void* data; CHECK_RESULT(ReadBytes(&data, &data_size, "data segment data")); CALLBACK(OnDataSegmentData, i, data, data_size); CALLBACK(EndDataSegment, i); } CALLBACK0(EndDataSection); return Result::Ok; } Result BinaryReader::ReadSections() { Result result = Result::Ok; while (state_.offset < state_.size) { uint32_t section_code; Offset section_size; CHECK_RESULT(ReadU32Leb128(&section_code, "section code")); CHECK_RESULT(ReadOffset(&section_size, "section size")); ReadEndRestoreGuard guard(this); read_end_ = state_.offset + section_size; if (section_code >= kBinarySectionCount) { PrintError("invalid section code: %u; max is %u", section_code, kBinarySectionCount - 1); return Result::Error; } BinarySection section = static_cast<BinarySection>(section_code); ERROR_UNLESS(read_end_ <= state_.size, "invalid section size: extends past end"); ERROR_UNLESS(last_known_section_ == BinarySection::Invalid || section == BinarySection::Custom || section > last_known_section_, "section %s out of order", GetSectionName(section)); ERROR_UNLESS(!did_read_names_section_ || section == BinarySection::Custom, "%s section can not occur after Name section", GetSectionName(section)); CALLBACK(BeginSection, section, section_size); bool stop_on_first_error = options_->stop_on_first_error; Result section_result = Result::Error; switch (section) { case BinarySection::Custom: section_result = ReadCustomSection(section_size); if (options_->fail_on_custom_section_error) { result |= section_result; } else { stop_on_first_error = false; } break; case BinarySection::Type: section_result = ReadTypeSection(section_size); result |= section_result; break; case BinarySection::Import: section_result = ReadImportSection(section_size); result |= section_result; break; case BinarySection::Function: section_result = ReadFunctionSection(section_size); result |= section_result; break; case BinarySection::Table: section_result = ReadTableSection(section_size); result |= section_result; break; case BinarySection::Memory: section_result = ReadMemorySection(section_size); result |= section_result; break; case BinarySection::Global: section_result = ReadGlobalSection(section_size); result |= section_result; break; case BinarySection::Export: section_result = ReadExportSection(section_size); result |= section_result; break; case BinarySection::Start: section_result = ReadStartSection(section_size); result |= section_result; break; case BinarySection::Elem: section_result = ReadElemSection(section_size); result |= section_result; break; case BinarySection::Code: section_result = ReadCodeSection(section_size); result |= section_result; break; case BinarySection::Data: section_result = ReadDataSection(section_size); result |= section_result; break; case BinarySection::Invalid: WABT_UNREACHABLE; } if (Failed(section_result)) { if (stop_on_first_error) { return Result::Error; } // If we're continuing after failing to read this section, move the // offset to the expected section end. This way we may be able to read // further sections. state_.offset = read_end_; } ERROR_UNLESS(state_.offset == read_end_, "unfinished section (expected end: 0x%" PRIzx ")", read_end_); if (section != BinarySection::Custom) { last_known_section_ = section; } } return result; } Result BinaryReader::ReadModule() { uint32_t magic = 0; CHECK_RESULT(ReadU32(&magic, "magic")); ERROR_UNLESS(magic == WABT_BINARY_MAGIC, "bad magic value"); uint32_t version = 0; CHECK_RESULT(ReadU32(&version, "version")); ERROR_UNLESS(version == WABT_BINARY_VERSION, "bad wasm file version: %#x (expected %#x)", version, WABT_BINARY_VERSION); CALLBACK(BeginModule, version); CHECK_RESULT(ReadSections()); CALLBACK0(EndModule); return Result::Ok; } } // end anonymous namespace Result ReadBinary(const void* data, size_t size, BinaryReaderDelegate* delegate, const ReadBinaryOptions* options) { BinaryReader reader(data, size, delegate, options); return reader.ReadModule(); } } // namespace wabt
[ "larrykittinger@gmail.com" ]
larrykittinger@gmail.com
d1f2004a68fd9aac72087eeb32e6a0c1a51ec377
9293c5cdc7e73714d8c6d81142e6a2eb1c53a4f4
/Project/codingtest/codingtest/line_20_05.cpp
64a7a7a5dbbcd529370980b8e3f16061dc7862a7
[]
no_license
jieunpark247/algorithm
d4bceba82775a90d0669e161f6debca2acd3d69d
18853423b69af65a7b6b6ddf3f122934286e0282
refs/heads/master
2023-06-01T12:57:37.882893
2021-06-20T04:54:19
2021-06-20T04:54:19
358,820,357
0
0
null
null
null
null
UTF-8
C++
false
false
1,444
cpp
#include <string> #include <vector> #include<algorithm> #include <stdlib.h> using namespace std; bool compare(const pair<int, string>& a, const pair<int, string>& b) { if (a.first == b.first) return a.second < b.second; return a.first > b.first; } vector<string> solution(vector<vector<string>> dataSource, vector<string> tags) { vector<string> answer; vector<string> v; vector< pair<int, string>> pairV; for (int i = 0; i < dataSource.size(); i++) { for (int j = 0; j < dataSource[i].size(); j++) { for (int z = 0; z < tags.size(); z++) { if (dataSource[i][j] == tags[z]) { v.push_back(dataSource[i][0]); } } } } sort(v.begin(), v.end()); vector<int> word_count; vector<string> unique_word; unique_copy(v.begin(), v.end(), back_inserter(unique_word)); vector<string>::size_type index, equal_word; for (index = 0; index != unique_word.size(); ++index) { equal_word = count(v.begin(), v.end(), unique_word[index]); if (equal_word) word_count.push_back(equal_word); } for (int i = 0; i < unique_word.size(); i++) { pairV.push_back(make_pair(word_count[i], unique_word[i])); } sort(pairV.begin(), pairV.end(), compare); for (int i = 0; i < pairV.size(); i++) { answer.push_back(pairV[i].second); } return answer; }
[ "jieunpark247@gmail.com" ]
jieunpark247@gmail.com
2f1c787ec4ef249f25600235cac2cdbe6d697b3e
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/gen/gen_combined/services/network/public/mojom/tls_socket.mojom-blink.h
e8571bf3210be294f9c6d2c495e5d62379721d84
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,339
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_NETWORK_PUBLIC_MOJOM_TLS_SOCKET_MOJOM_BLINK_H_ #define SERVICES_NETWORK_PUBLIC_MOJOM_TLS_SOCKET_MOJOM_BLINK_H_ #include <stdint.h> #include <limits> #include <type_traits> #include <utility> #include "base/callback.h" #include "base/macros.h" #include "base/optional.h" #include "mojo/public/cpp/bindings/mojo_buildflags.h" #if BUILDFLAG(MOJO_TRACE_ENABLED) #include "base/trace_event/trace_event.h" #endif #include "mojo/public/cpp/bindings/clone_traits.h" #include "mojo/public/cpp/bindings/equals_traits.h" #include "mojo/public/cpp/bindings/lib/serialization.h" #include "mojo/public/cpp/bindings/struct_ptr.h" #include "mojo/public/cpp/bindings/struct_traits.h" #include "mojo/public/cpp/bindings/union_traits.h" #include "services/network/public/mojom/tls_socket.mojom-shared.h" #include "services/network/public/mojom/tls_socket.mojom-blink-forward.h" #include "services/network/public/mojom/ip_endpoint.mojom-blink-forward.h" #include "services/network/public/mojom/ssl_config.mojom-blink-forward.h" #include "mojo/public/cpp/bindings/lib/wtf_clone_equals_util.h" #include "mojo/public/cpp/bindings/lib/wtf_hash_util.h" #include "third_party/blink/renderer/platform/wtf/hash_functions.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "mojo/public/cpp/bindings/associated_interface_ptr.h" #include "mojo/public/cpp/bindings/associated_interface_ptr_info.h" #include "mojo/public/cpp/bindings/associated_interface_request.h" #include "mojo/public/cpp/bindings/interface_ptr.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/lib/control_message_handler.h" #include "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h" #include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h" #include "mojo/public/cpp/bindings/lib/native_enum_serialization.h" #include "mojo/public/cpp/bindings/lib/native_struct_serialization.h" #include "third_party/blink/public/platform/web_common.h" namespace network { namespace mojom { namespace blink { class TLSClientSocketProxy; template <typename ImplRefTraits> class TLSClientSocketStub; class TLSClientSocketRequestValidator; class BLINK_PLATFORM_EXPORT TLSClientSocket : public TLSClientSocketInterfaceBase { public: static const char Name_[]; static constexpr uint32_t Version_ = 0; static constexpr bool PassesAssociatedKinds_ = false; static constexpr bool HasSyncMethods_ = false; using Base_ = TLSClientSocketInterfaceBase; using Proxy_ = TLSClientSocketProxy; template <typename ImplRefTraits> using Stub_ = TLSClientSocketStub<ImplRefTraits>; using RequestValidator_ = TLSClientSocketRequestValidator; using ResponseValidator_ = mojo::PassThroughFilter; enum MethodMinVersions : uint32_t { }; virtual ~TLSClientSocket() {} }; class BLINK_PLATFORM_EXPORT TLSClientSocketProxy : public TLSClientSocket { public: using InterfaceType = TLSClientSocket; explicit TLSClientSocketProxy(mojo::MessageReceiverWithResponder* receiver); private: mojo::MessageReceiverWithResponder* receiver_; }; class BLINK_PLATFORM_EXPORT TLSClientSocketStubDispatch { public: static bool Accept(TLSClientSocket* impl, mojo::Message* message); static bool AcceptWithResponder( TLSClientSocket* impl, mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder); }; template <typename ImplRefTraits = mojo::RawPtrImplRefTraits<TLSClientSocket>> class TLSClientSocketStub : public mojo::MessageReceiverWithResponderStatus { public: using ImplPointerType = typename ImplRefTraits::PointerType; TLSClientSocketStub() {} ~TLSClientSocketStub() override {} void set_sink(ImplPointerType sink) { sink_ = std::move(sink); } ImplPointerType& sink() { return sink_; } bool Accept(mojo::Message* message) override { if (ImplRefTraits::IsNull(sink_)) return false; return TLSClientSocketStubDispatch::Accept( ImplRefTraits::GetRawPointer(&sink_), message); } bool AcceptWithResponder( mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder) override { if (ImplRefTraits::IsNull(sink_)) return false; return TLSClientSocketStubDispatch::AcceptWithResponder( ImplRefTraits::GetRawPointer(&sink_), message, std::move(responder)); } private: ImplPointerType sink_; }; class BLINK_PLATFORM_EXPORT TLSClientSocketRequestValidator : public mojo::MessageReceiver { public: bool Accept(mojo::Message* message) override; }; class BLINK_PLATFORM_EXPORT TLSClientSocketOptions { public: using DataView = TLSClientSocketOptionsDataView; using Data_ = internal::TLSClientSocketOptions_Data; template <typename... Args> static TLSClientSocketOptionsPtr New(Args&&... args) { return TLSClientSocketOptionsPtr( base::in_place, std::forward<Args>(args)...); } template <typename U> static TLSClientSocketOptionsPtr From(const U& u) { return mojo::TypeConverter<TLSClientSocketOptionsPtr, U>::Convert(u); } template <typename U> U To() const { return mojo::TypeConverter<U, TLSClientSocketOptions>::Convert(*this); } TLSClientSocketOptions(); TLSClientSocketOptions( ::network::mojom::blink::SSLVersion version_min, ::network::mojom::blink::SSLVersion version_max, bool send_ssl_info, bool unsafely_skip_cert_verification); ~TLSClientSocketOptions(); // Clone() is a template so it is only instantiated if it is used. Thus, the // bindings generator does not need to know whether Clone() or copy // constructor/assignment are available for members. template <typename StructPtrType = TLSClientSocketOptionsPtr> TLSClientSocketOptionsPtr Clone() const; // Equals() is a template so it is only instantiated if it is used. Thus, the // bindings generator does not need to know whether Equals() or == operator // are available for members. template <typename T, typename std::enable_if<std::is_same< T, TLSClientSocketOptions>::value>::type* = nullptr> bool Equals(const T& other) const; size_t Hash(size_t seed) const; template <typename UserType> static WTF::Vector<uint8_t> Serialize(UserType* input) { return mojo::internal::SerializeImpl< TLSClientSocketOptions::DataView, WTF::Vector<uint8_t>>(input); } template <typename UserType> static mojo::Message SerializeAsMessage(UserType* input) { return mojo::internal::SerializeAsMessageImpl< TLSClientSocketOptions::DataView>(input); } // The returned Message is serialized only if the message is moved // cross-process or cross-language. Otherwise if the message is Deserialized // as the same UserType |input| will just be moved to |output| in // DeserializeFromMessage. template <typename UserType> static mojo::Message WrapAsMessage(UserType input) { return mojo::Message(std::make_unique< internal::TLSClientSocketOptions_UnserializedMessageContext< UserType, TLSClientSocketOptions::DataView>>(0, 0, std::move(input))); } template <typename UserType> static bool Deserialize(const void* data, size_t data_num_bytes, UserType* output) { return mojo::internal::DeserializeImpl<TLSClientSocketOptions::DataView>( data, data_num_bytes, std::vector<mojo::ScopedHandle>(), output, Validate); } template <typename UserType> static bool Deserialize(const WTF::Vector<uint8_t>& input, UserType* output) { return TLSClientSocketOptions::Deserialize( input.size() == 0 ? nullptr : &input.front(), input.size(), output); } template <typename UserType> static bool DeserializeFromMessage(mojo::Message input, UserType* output) { auto context = input.TakeUnserializedContext< internal::TLSClientSocketOptions_UnserializedMessageContext< UserType, TLSClientSocketOptions::DataView>>(); if (context) { *output = std::move(context->TakeData()); return true; } input.SerializeIfNecessary(); return mojo::internal::DeserializeImpl<TLSClientSocketOptions::DataView>( input.payload(), input.payload_num_bytes(), std::move(*input.mutable_handles()), output, Validate); } ::network::mojom::blink::SSLVersion version_min; ::network::mojom::blink::SSLVersion version_max; bool send_ssl_info; bool unsafely_skip_cert_verification; private: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); }; template <typename StructPtrType> TLSClientSocketOptionsPtr TLSClientSocketOptions::Clone() const { return New( mojo::Clone(version_min), mojo::Clone(version_max), mojo::Clone(send_ssl_info), mojo::Clone(unsafely_skip_cert_verification) ); } template <typename T, typename std::enable_if<std::is_same< T, TLSClientSocketOptions>::value>::type*> bool TLSClientSocketOptions::Equals(const T& other_struct) const { if (!mojo::Equals(this->version_min, other_struct.version_min)) return false; if (!mojo::Equals(this->version_max, other_struct.version_max)) return false; if (!mojo::Equals(this->send_ssl_info, other_struct.send_ssl_info)) return false; if (!mojo::Equals(this->unsafely_skip_cert_verification, other_struct.unsafely_skip_cert_verification)) return false; return true; } } // namespace blink } // namespace mojom } // namespace network namespace mojo { template <> struct BLINK_PLATFORM_EXPORT StructTraits<::network::mojom::blink::TLSClientSocketOptions::DataView, ::network::mojom::blink::TLSClientSocketOptionsPtr> { static bool IsNull(const ::network::mojom::blink::TLSClientSocketOptionsPtr& input) { return !input; } static void SetToNull(::network::mojom::blink::TLSClientSocketOptionsPtr* output) { output->reset(); } static decltype(::network::mojom::blink::TLSClientSocketOptions::version_min) version_min( const ::network::mojom::blink::TLSClientSocketOptionsPtr& input) { return input->version_min; } static decltype(::network::mojom::blink::TLSClientSocketOptions::version_max) version_max( const ::network::mojom::blink::TLSClientSocketOptionsPtr& input) { return input->version_max; } static decltype(::network::mojom::blink::TLSClientSocketOptions::send_ssl_info) send_ssl_info( const ::network::mojom::blink::TLSClientSocketOptionsPtr& input) { return input->send_ssl_info; } static decltype(::network::mojom::blink::TLSClientSocketOptions::unsafely_skip_cert_verification) unsafely_skip_cert_verification( const ::network::mojom::blink::TLSClientSocketOptionsPtr& input) { return input->unsafely_skip_cert_verification; } static bool Read(::network::mojom::blink::TLSClientSocketOptions::DataView input, ::network::mojom::blink::TLSClientSocketOptionsPtr* output); }; } // namespace mojo #endif // SERVICES_NETWORK_PUBLIC_MOJOM_TLS_SOCKET_MOJOM_BLINK_H_
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
d998169b49b630d5a702fd37997f787bc4555f7b
5d91ebd041e78fee3888ec55a60c3648a765a22c
/src/examples/revive.h
0acbf0773ab0fc30db65a7930c49ee838d420688
[ "MIT" ]
permissive
karekoho/json
c11f671024670e2fe1f4041dfdedd434e06ac0f4
2c0a0b3fceb17025fcb57d196f1b7442fb963497
refs/heads/master
2023-03-12T03:07:16.960161
2023-03-05T15:58:14
2023-03-05T15:58:14
69,328,757
0
0
MIT
2023-02-20T19:25:02
2016-09-27T07:01:31
C++
UTF-8
C++
false
false
1,736
h
#ifndef REVIVE_H #define REVIVE_H #include <cstring> #include <iostream> #include <format/json.h> using namespace format; /** * This function modifies the parsed json object * by returning modified value * @param key The key in json object * @param val The value to modify * @return */ json::value * fn_reviver (const wchar_t *key, json::value *val) { json::value::value_t type = val->type (); // Replace null value with "n/a" if (wcscmp (key, L"Description") == 0 && type == json::value::null_t) return new json::string (L"n/a"); // Remove the Thumbnail object by returning undefined if (wcscmp (key, L"Thumbnail") == 0) return new json::undefined (); // Otherwise return unchanged value return val; } void revive () { std::wcout << std::endl << "Revive:" << std::endl; // Create json object and pass the reviver function json::json *j = json::json::parse ( L"{\ \"Image\": {\ \"Width\": 800,\ \"Height\": 600,\ \"Title\": \"View from 15th Floor\",\ \"Description\": null,\ \"Thumbnail\": {\ \"Url\": \"http://www.example.com/image/481989943\",\ \"Height\": 125,\ \"Width\": 100\ },\ \"Animated\" : true,\ \"IDs\": [116, 943, 234, 38793]\ }\ }", fn_reviver); // The reviver // stringify () returns pointer to new memory, that must be freed const wchar_t *str_value = j->stringify (); std::wcout << str_value << std::endl; // output: {"Image":{"IDs":[116,943,234,38793],"Description":"n/a", // "Height":600,"Animated":true,"Title":"View from 15th Floor","Width":800}} delete j; delete [] str_value; } #endif // REVIVE_H
[ "kare.koho@yahoo.com" ]
kare.koho@yahoo.com
34c66bd1c9e175636de9f3a378b374e7b43de611
726b3a0e58af1af6f4737acae0260709480e43ac
/RTSP/groupsock/GroupEId.cpp
061adc9f94d5f29f5feb5c95263cb47ecece5297
[]
no_license
leithergit/IPCPlaySDK
f16c64a9cfdcc303c8699128a07062cc0b3812dd
d835a5fe468166bc3d5bdfed2471b54e8ae775d5
refs/heads/master
2021-07-15T09:07:12.434613
2021-03-08T06:50:06
2021-03-08T06:50:06
62,870,570
1
7
null
null
null
null
UTF-8
C++
false
false
3,132
cpp
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // Copyright (c) 1996-2011, Live Networks, Inc. All rights reserved // "Group Endpoint Id" // Implementation #include "GroupEId.hh" #include "strDup.hh" #include <string.h> ////////// Scope ////////// void Scope::assign(u_int8_t ttl, const char* publicKey) { fTTL = ttl; fPublicKey = strDup(publicKey == NULL ? "nokey" : publicKey); } void Scope::clean() { delete[] fPublicKey; fPublicKey = NULL; } Scope::Scope(u_int8_t ttl, const char* publicKey) { assign(ttl, publicKey); } Scope::Scope(const Scope& orig) { assign(orig.ttl(), orig.publicKey()); } Scope& Scope::operator=(const Scope& rightSide) { if (&rightSide != this) { if (publicKey() == NULL || strcmp(publicKey(), rightSide.publicKey()) != 0) { clean(); assign(rightSide.ttl(), rightSide.publicKey()); } else // need to assign TTL only { fTTL = rightSide.ttl(); } } return *this; } Scope::~Scope() { clean(); } unsigned Scope::publicKeySize() const { return fPublicKey == NULL ? 0 : strlen(fPublicKey); } ////////// GroupEId ////////// GroupEId::GroupEId(struct in_addr const& groupAddr, portNumBits portNum, Scope const& scope, unsigned numSuccessiveGroupAddrs) { struct in_addr sourceFilterAddr; sourceFilterAddr.s_addr = ~0; // indicates no source filter init(groupAddr, sourceFilterAddr, portNum, scope, numSuccessiveGroupAddrs); } GroupEId::GroupEId(struct in_addr const& groupAddr, struct in_addr const& sourceFilterAddr, portNumBits portNum, unsigned numSuccessiveGroupAddrs) { init(groupAddr, sourceFilterAddr, portNum, 255, numSuccessiveGroupAddrs); } GroupEId::GroupEId() { } Boolean GroupEId::isSSM() const { return fSourceFilterAddress.s_addr != netAddressBits(~0); } void GroupEId::init(struct in_addr const& groupAddr, struct in_addr const& sourceFilterAddr, portNumBits portNum, Scope const& scope, unsigned numSuccessiveGroupAddrs) { fGroupAddress = groupAddr; fSourceFilterAddress = sourceFilterAddr; fNumSuccessiveGroupAddrs = numSuccessiveGroupAddrs; fPortNum = portNum; fScope = scope; }
[ "leither908@gmail.com" ]
leither908@gmail.com
ffd40591ab6be3f7e0ba70ff03fb406c63bff6eb
665eb7434052dafa57f50561f2b873cd009db49b
/main.cpp
8ed25b86d25ef9edeecd5e35c9cce1c2ee2e1d59
[]
no_license
knitomi90ELTE/BinaryTree
0a86c83effa5b13bb248fd96f78b8332150df4ed
155229469573efb5274145f4b1dc0ae1e2454d3d
refs/heads/master
2021-01-10T08:28:47.374618
2016-01-24T23:09:33
2016-01-24T23:09:33
50,301,382
0
0
null
null
null
null
UTF-8
C++
false
false
521
cpp
#include <iostream> #include "BinTree.h" int main() { BinTree<int>* tree; tree = new BinTree<int>(); tree->insert(30); tree->insert(10); tree->insert(20); tree->insert(40); tree->insert(50); tree->inOrder(tree->root); std::cout << std::endl; tree->preOrder(tree->root); std::cout << std::endl; tree->postOrder(tree->root); std::cout << std::endl; int leafs = tree->countLeafs(tree->root); std::cout << "leaf count: " << leafs << std::endl; return 0; }
[ "knitomi90@inf.elte.hu" ]
knitomi90@inf.elte.hu
b6e8c89affb2b4b3221292db09e00373b0905320
5be1d00e5cdadc6c2214e9f0d747e56aa56ecf04
/Includes/GenICam/GenApi/Persistence.h
be7f65032fcbeb5cdde8d86c8afe54d244174f89
[]
no_license
CandleHouse/MVS_CameraFocus
5476b313585530e8ea1daeea1505b61f34e2d798
32974daef60967ff7981828964319c3f7c038cea
refs/heads/master
2023-06-19T19:05:02.986513
2021-07-19T06:01:14
2021-07-19T06:01:14
387,321,239
7
0
null
null
null
null
UTF-8
C++
false
false
7,765
h
//----------------------------------------------------------------------------- // (c) 2007 by National Instruments // Project: GenApi // Author: Eric Gross // $Header$ // // License: This file is published under the license of the EMVA GenICam Standard Group. // A text file describing the legal terms is included in your installation as 'GenICam_license.pdf'. // If for some reason you are missing this file please contact the EMVA or visit the website // (http://www.genicam.org) for a full copy. // // THIS SOFTWARE IS PROVIDED BY THE EMVA GENICAM STANDARD GROUP "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE EMVA GENICAM STANDARD GROUP // OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- /*! \file \brief Definition of interface IPersistScript and class CFeatureBag \ingroup GenApi_PublicUtilities */ #ifndef _GENICAM_PERSISTENCE_H #define _GENICAM_PERSISTENCE_H #include <GenApi/Types.h> #include <GenApi/Pointer.h> #include <GenApi/GenApiDll.h> #include <list> #include <iostream> using namespace GENICAM_NAMESPACE; namespace GENAPI_NAMESPACE { //! Basic interface to persist values to interface GENAPI_DECL_ABSTRACT IPersistScript { //! sets information about the node map virtual void SetInfo(gcstring &Info) = 0; //! Stores a feature virtual void PersistFeature(IValue& item) = 0; }; //! Bag holding streamable features of a nodetree class GENAPI_DECL CFeatureBag : public IPersistScript { public: //! sets information about the node map virtual void SetInfo(gcstring &Info); //! Stores a feature virtual void PersistFeature(IValue& item); //! Loads the features from the bag to the node tree //! \param pNodeMap The node map //! \param Verify If true, all streamable features are read back //! \param pErrorList If an error occurs during loading the error message is stored in the list and the loading continues /*! For Verify=true the list of names in the feature bag is replayed again. If a node is a selector it's value is set to the value from the feature bag If not the value is read from the camera and compared with the value from the feature bag. */ bool LoadFromBag(INodeMap *pNodeMap, bool Verify = true, gcstring_vector *pErrorList = NULL); /*! \brief Stores the streamable nodes to this feature bag \param pNodeMap The node map to persist \param MaxNumPersistSkriptEntries The max number of entries in the container; -1 means unlimited \return number of entries in the bag */ int64_t StoreToBag(INodeMap *pNodeMap, const int MaxNumPersistSkriptEntries = -1 ); //! compares the content of two feature bags bool operator==(const CFeatureBag &FeatureBag) const; gcstring ToString(); //! fills the bag from a stream friend std::istream& operator >>(std::istream &is, CFeatureBag &FeatureBag); //! puts the bag into a stream friend std::ostream& operator <<(std::ostream &os, const CFeatureBag &FeatureBag); private: //! The features are stored in a list of string pairs = {Name, Value} gcstring_vector m_Names; //! The features are stored in a list of string pairs = {Name, Value} gcstring_vector m_Values; //! String describing the node map gcstring m_Info; }; //! the magic GUID which indicates that the file is a GenApi stream file Must be the first entry #define GENAPI_PERSISTENCE_MAGIC "{05D8C294-F295-4dfb-9D01-096BD04049F4}" //! Helper function ignoring lines starting with comment character '#' // note: this method must be inlined because it uses istream in the parameter list inline std::istream& EatComments(std::istream &is) { if( is.eof() ) return is; char FirstCharacter; FirstCharacter = (char)is.peek(); while( FirstCharacter == '#' ) { is.ignore(1024, '\n'); FirstCharacter = (char)is.peek(); } return is; } //! reads in persistent data from a stream // note: this method must be inlined because it uses istream in the parameter list // note: May not be used as inline if called against a library where it is already compiled. inline std::istream& operator >>(std::istream &is, CFeatureBag &FeatureBag) { if( is.eof() ) throw RUNTIME_EXCEPTION("The stream is eof"); FeatureBag.m_Names.clear(); FeatureBag.m_Values.clear(); const int BufferSize = 1024; char Buffer[BufferSize] = {0}; char Name[BufferSize] = {0}; gcstring Value(""); // Check the magic is.getline(Buffer, BufferSize, '\n'); gcstring FirstLine(Buffer); gcstring MagicGUID(GENAPI_PERSISTENCE_MAGIC); if( gcstring::_npos() == FirstLine.find(MagicGUID) ) throw RUNTIME_EXCEPTION("The stream is not a GenApi feature stream since it is missing the magic GUID in the first line"); EatComments( is ); while( !is.eof() ) { is.getline(Name, BufferSize, '\t'); if (is.fail()) // if reading from stream failed -> stop reading! break; GENICAM_NAMESPACE::getline(is, Value); if (is.fail()) // if reading from stream failed -> stop reading! break; FeatureBag.m_Names.push_back(Name); FeatureBag.m_Values.push_back(Value); Name[0] = '\0'; Value = ""; EatComments( is ); } return is; } //! writes out persistent data to a stream // note: this method must be inlined because it uses ostream in the parameter list // note: May not be used as inline if called against a library where it is already compiled. inline std::ostream& operator <<(std::ostream &os, const CFeatureBag &FeatureBag) { os << "# " GENAPI_PERSISTENCE_MAGIC "\n"; os << "# GenApi persistence file (version " << GENAPI_VERSION_MAJOR << "." << GENAPI_VERSION_MINOR << "." << GENAPI_VERSION_SUBMINOR << ")\n"; os << "# " << FeatureBag.m_Info << "\n"; gcstring_vector::const_iterator pName = FeatureBag.m_Names.begin(); gcstring_vector::const_iterator pValue = FeatureBag.m_Values.begin(); assert(FeatureBag.m_Names.size() == FeatureBag.m_Values.size()); if (FeatureBag.m_Names.size() == FeatureBag.m_Values.size()) { const gcstring_vector::const_iterator endNames = FeatureBag.m_Names.end(); const gcstring_vector::const_iterator endValues = FeatureBag.m_Values.end(); for ( /**/; pName != endNames; ++pName, ++pValue) { gcstring Name(*pName); gcstring Value(*pValue); os << Name << "\t" << Value << "\n"; } } return os; } } #endif //_GENICAM_PERSISTENCE_H
[ "lucstudent@126.com" ]
lucstudent@126.com
b1a4636a29a3ab19eaacdd96a9cd2f1f758e7f2c
a4335d82080124cd0bcc2dd50ade857082eb4b2a
/Release/GacUI.h
15386d6031bbe3e2a2bc2c174b30fc3f18cb66ab
[]
no_license
jun19910629/GacUI
479b27f6be1be770313f16385ee3edaa6d151695
953c1df5fbbd1683028fba2a135f28c40fbec51b
refs/heads/master
2020-03-25T06:16:19.131871
2018-08-03T03:44:16
2018-08-03T03:44:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
818,000
h
/*********************************************************************** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT MODIFY DEVELOPER: Zihan Chen(vczh) ***********************************************************************/ #include "Vlpp.h" #include "VlppWorkflowLibrary.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 { /*********************************************************************** Enumerations ***********************************************************************/ /// <summary> /// Defines an alignment direction. /// </summary> enum class Alignment { /// <summary>Aligned to the left side.</summary> Left=0, /// <summary>Aligned to the top side.</summary> Top=0, /// <summary>Aligned to the center.</summary> Center=1, /// <summary>Aligned to the right side.</summary> Right=2, /// <summary>Aligned to the bottom side.</summary> Bottom=2, }; /// <summary>Axis direction.</summary> enum class AxisDirection { /// <summary>X:left, Y:down.</summary> LeftDown, /// <summary>X:right, Y:down.</summary> RightDown, /// <summary>X:left, Y:up.</summary> LeftUp, /// <summary>X:right, Y:up.</summary> RightUp, /// <summary>X:down, Y:left.</summary> DownLeft, /// <summary>X:down, Y:right.</summary> DownRight, /// <summary>X:up, Y:left.</summary> UpLeft, /// <summary>X:up, Y:right.</summary> UpRight, }; /*********************************************************************** TextPos ***********************************************************************/ /// <summary> /// Represents the position in multiple lines of text. /// </summary> struct TextPos { /// <summary> /// Row number. /// </summary> vint row; /// <summary> /// Column number. If a line has 4 characters, there are 5 available column numbers(from 0 to 4) in this line. /// </summary> vint column; TextPos() :row(0) ,column(0) { } TextPos(vint _row, vint _column) :row(_row) ,column(_column) { } vint Compare(const TextPos& value)const { if(row<value.row) return -1; if(row>value.row) return 1; if(column<value.column) return -1; if(column>value.column) return 1; return 0; } bool operator==(const TextPos& value)const {return Compare(value)==0;} bool operator!=(const TextPos& value)const {return Compare(value)!=0;} bool operator<(const TextPos& value)const {return Compare(value)<0;} bool operator<=(const TextPos& value)const {return Compare(value)<=0;} bool operator>(const TextPos& value)const {return Compare(value)>0;} bool operator>=(const TextPos& value)const {return Compare(value)>=0;} }; /*********************************************************************** GridPos ***********************************************************************/ /// <summary> /// Represents the cell position in a grid. /// </summary> struct GridPos { /// <summary> /// Row number. /// </summary> vint row; /// <summary> /// Column number. If a line has 4 characters, there are 5 available column numbers(from 0 to 4) in this line. /// </summary> vint column; GridPos() :row(0) ,column(0) { } GridPos(vint _row, vint _column) :row(_row) ,column(_column) { } vint Compare(const GridPos& value)const { if(row<value.row) return -1; if(row>value.row) return 1; if(column<value.column) return -1; if(column>value.column) return 1; return 0; } bool operator==(const GridPos& value)const {return Compare(value)==0;} bool operator!=(const GridPos& value)const {return Compare(value)!=0;} bool operator<(const GridPos& value)const {return Compare(value)<0;} bool operator<=(const GridPos& value)const {return Compare(value)<=0;} bool operator>(const GridPos& value)const {return Compare(value)>0;} bool operator>=(const GridPos& value)const {return Compare(value)>=0;} }; /*********************************************************************** Point ***********************************************************************/ /// <summary> /// Represents a position in a two dimensions space. /// </summary> struct Point { /// <summary> /// Position in x dimension. /// </summary> vint x; /// <summary> /// Position in y dimension. /// </summary> vint y; Point() :x(0) ,y(0) { } Point(vint _x, vint _y) :x(_x) ,y(_y) { } bool operator==(Point point)const { return x==point.x && y==point.y; } bool operator!=(Point point)const { return x!=point.x || y!=point.y; } }; /*********************************************************************** Size ***********************************************************************/ /// <summary> /// Represents a size in a two dimensions space. /// </summary> struct Size { /// <summary> /// Size in x dimension. /// </summary> vint x; /// <summary> /// Size in y dimension. /// </summary> vint y; Size() :x(0) ,y(0) { } Size(vint _x, vint _y) :x(_x) ,y(_y) { } bool operator==(Size size)const { return x==size.x && y==size.y; } bool operator!=(Size size)const { return x!=size.x || y!=size.y; } }; /*********************************************************************** Rectangle ***********************************************************************/ /// <summary> /// Represents a bounds in a two dimensions space. /// </summary> struct Rect { /// <summary> /// Left. /// </summary> vint x1; /// <summary> /// Top. /// </summary> vint y1; /// <summary> /// Left + Width. /// </summary> vint x2; /// <summary> /// Top + Height. /// </summary> vint y2; Rect() :x1(0), y1(0), x2(0), y2(0) { } Rect(vint _x1, vint _y1, vint _x2, vint _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) { } bool operator==(Rect rect)const { return x1==rect.x1 && y1==rect.y1 && x2==rect.x2 && y2==rect.y2; } bool operator!=(Rect rect)const { return x1!=rect.x1 || y1!=rect.y1 || x2!=rect.x2 || y2!=rect.y2; } Point LeftTop()const { return Point(x1, y1); } Point RightBottom()const { return Point(x2, y2); } Size GetSize()const { return Size(x2-x1, y2-y1); } vint Left()const { return x1; } vint Right()const { return x2; } vint Width()const { return x2-x1; } vint Top()const { return y1; } vint Bottom()const { return y2; } vint Height()const { return y2-y1; } void Expand(vint x, vint 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(vint x, vint 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; } }; /*********************************************************************** 2D operations ***********************************************************************/ inline Point operator+(Point p, Size s) { return Point(p.x+s.x, p.y+s.y); } inline Point operator+(Size s, Point p) { return Point(p.x+s.x, p.y+s.y); } inline Point operator-(Point p, Size s) { return Point(p.x-s.x, p.y-s.y); } inline Size operator-(Point p1, Point p2) { return Size(p1.x-p2.x, p1.y-p2.y); } inline Size operator+(Size s1, Size s2) { return Size(s1.x+s2.x, s1.y+s2.y); } inline Size operator-(Size s1, Size s2) { return Size(s1.x-s2.x, s1.y-s2.y); } inline Size operator*(Size s, vint i) { return Size(s.x*i, s.y*i); } inline Size operator/(Size s, vint i) { return Size(s.x/i, s.y/i); } inline Point operator+=(Point& s1, Size s2) { s1.x+=s2.x; s1.y+=s2.y; return s1; } inline Point operator-=(Point& s1, Size s2) { s1.x-=s2.x; s1.y-=s2.y; return s1; } inline Size operator+=(Size& s1, Size s2) { s1.x+=s2.x; s1.y+=s2.y; return s1; } inline Size operator-=(Size& s1, Size s2) { s1.x-=s2.x; s1.y-=s2.y; return s1; } /*********************************************************************** Color ***********************************************************************/ /// <summary>Represents a 32bit RGBA color. Values of separate components can be accessed using fields "r", "g", "b" and "a".</summary> 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) { } vint Compare(Color color)const { return value-color.value; } 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;i<value.Length()-1;i++) { index[i]=wcschr(code, value[i+1])-code; if(index[i]<0 || index[i]>15) { 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; } bool operator==(Color color)const {return Compare(color)==0;} bool operator!=(Color color)const {return Compare(color)!=0;} bool operator<(Color color)const {return Compare(color)<0;} bool operator<=(Color color)const {return Compare(color)<=0;} bool operator>(Color color)const {return Compare(color)>0;} bool operator>=(Color color)const {return Compare(color)>=0;} }; /*********************************************************************** Margin ***********************************************************************/ /// <summary> /// Represents a margin in a two dimensions space. /// </summary> struct Margin { /// <summary> /// The left margin. /// </summary> vint left; /// <summary> /// The top margin. /// </summary> vint top; /// <summary> /// The right margin. /// </summary> vint right; /// <summary> /// The bottom margin. /// </summary> vint bottom; Margin() :left(0), top(0), right(0), bottom(0) { } Margin(vint _left, vint _top, vint _right, vint _bottom) :left(_left), top(_top), right(_right), bottom(_bottom) { } bool operator==(Margin margin)const { return left==margin.left && top==margin.top && right==margin.right && bottom==margin.bottom; } bool operator!=(Margin margin)const { return left!=margin.left || top!=margin.top || right!=margin.right || bottom!=margin.bottom; } }; /*********************************************************************** Resources ***********************************************************************/ /// <summary> /// Represents a font configuration. /// </summary> struct FontProperties { /// <summary> /// Font family (or font name, usually). /// </summary> WString fontFamily; /// <summary> /// Font size in pixel. /// </summary> vint size; /// <summary> /// True if the font is bold. /// </summary> bool bold; /// <summary> /// True if the font is italic. /// </summary> bool italic; /// <summary> /// True if the font has a underline. /// </summary> bool underline; /// <summary> /// True if the font has a strikeline. /// </summary> bool strikeline; /// <summary> /// True if the font has anti alias rendering. /// </summary> bool antialias; /// <summary> /// True if the font has anti alias rendering in vertical direction. /// </summary> bool verticalAntialias; FontProperties() :size(0) ,bold(false) ,italic(false) ,underline(false) ,strikeline(false) ,antialias(true) ,verticalAntialias(false) { } vint Compare(const FontProperties& value)const { vint result=0; result=WString::Compare(fontFamily, value.fontFamily); if(result!=0) return result; result=size-value.size; if(result!=0) return result; result=(vint)bold-(vint)value.bold; if(result!=0) return result; result=(vint)italic-(vint)value.italic; if(result!=0) return result; result=(vint)underline-(vint)value.underline; if(result!=0) return result; result=(vint)strikeline-(vint)value.strikeline; if(result!=0) return result; result=(vint)antialias-(vint)value.antialias; if(result!=0) return result; return 0; } bool operator==(const FontProperties& value)const {return Compare(value)==0;} bool operator!=(const FontProperties& value)const {return Compare(value)!=0;} bool operator<(const FontProperties& value)const {return Compare(value)<0;} bool operator<=(const FontProperties& value)const {return Compare(value)<=0;} bool operator>(const FontProperties& value)const {return Compare(value)>0;} bool operator>=(const FontProperties& value)const {return Compare(value)>=0;} }; } } #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 { using namespace reflection; namespace compositions { class GuiGraphicsComposition; extern void InvokeOnCompositionStateChanged(compositions::GuiGraphicsComposition* composition); } namespace elements { class IGuiGraphicsElement; class IGuiGraphicsElementFactory; class IGuiGraphicsRenderer; class IGuiGraphicsRendererFactory; class IGuiGraphicsRenderTarget; /*********************************************************************** Basic Construction ***********************************************************************/ /// <summary> /// 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. /// </summary> class IGuiGraphicsElement : public virtual IDescriptable, public Description<IGuiGraphicsElement> { friend class compositions::GuiGraphicsComposition; protected: virtual void SetOwnerComposition(compositions::GuiGraphicsComposition* composition) = 0; public: /// <summary> /// Access the <see cref="IGuiGraphicsElementFactory"></see> that is used to create this graphics elements. /// </summary> /// <returns>Returns the related factory.</returns> virtual IGuiGraphicsElementFactory* GetFactory() = 0; /// <summary> /// Access the associated <see cref="IGuiGraphicsRenderer"></see> for this graphics element. /// </summary> /// <returns>Returns the related renderer.</returns> virtual IGuiGraphicsRenderer* GetRenderer() = 0; /// <summary> /// Get the owner composition. /// </summary> /// <returns>The owner composition.</returns> virtual compositions::GuiGraphicsComposition* GetOwnerComposition() = 0; }; /// <summary> /// This is the interface for graphics element factories. /// Graphics element factories should be registered using [M:vl.presentation.elements.GuiGraphicsResourceManager.RegisterElementFactory]. /// </summary> class IGuiGraphicsElementFactory : public Interface { public: /// <summary> /// Get the name representing the kind of graphics element to be created. /// </summary> /// <returns>Returns the name of graphics elements.</returns> virtual WString GetElementTypeName()=0; /// <summary> /// Create a <see cref="IGuiGraphicsElement"></see>. /// </summary> /// <returns>Returns the created graphics elements.</returns> virtual IGuiGraphicsElement* Create()=0; }; /// <summary> /// This is the interface for graphics renderers. /// </summary> class IGuiGraphicsRenderer : public Interface { public: /// <summary> /// Access the graphics <see cref="IGuiGraphicsRendererFactory"></see> that is used to create this graphics renderer. /// </summary> /// <returns>Returns the related factory.</returns> virtual IGuiGraphicsRendererFactory* GetFactory()=0; /// <summary> /// Initialize the grpahics renderer by binding a <see cref="IGuiGraphicsElement"></see> to it. /// </summary> /// <param name="element">The graphics element to bind.</param> virtual void Initialize(IGuiGraphicsElement* element)=0; /// <summary> /// Release all resources that used by this renderer. /// </summary> virtual void Finalize()=0; /// <summary> /// Set a <see cref="IGuiGraphicsRenderTarget"></see> to this element. /// </summary> /// <param name="renderTarget">The graphics render target. It can be NULL.</param> virtual void SetRenderTarget(IGuiGraphicsRenderTarget* renderTarget)=0; /// <summary> /// Render the graphics element using a specified bounds. /// </summary> /// <param name="bounds">Bounds to decide the size and position of the binded graphics element.</param> virtual void Render(Rect bounds)=0; /// <summary> /// Notify that the state in the binded graphics element is changed. This function is usually called by the element itself. /// </summary> virtual void OnElementStateChanged()=0; /// <summary> /// Calculate the minimum size using the binded graphics element and its state. /// </summary> /// <returns>The minimum size.</returns> virtual Size GetMinSize()=0; }; /// <summary> /// This is the interface for graphics renderer factories. /// Graphics renderers should be registered using [M:vl.presentation.elements.GuiGraphicsResourceManager.RegisterRendererFactory]. /// </summary> class IGuiGraphicsRendererFactory : public Interface { public: /// <summary> /// Create a <see cref="IGuiGraphicsRenderer"></see>. /// </summary> /// <returns>Returns the created graphics renderer.</returns> virtual IGuiGraphicsRenderer* Create()=0; }; enum RenderTargetFailure { None, ResizeWhileRendering, LostDevice, }; /// <summary> /// This is the interface for graphics renderer targets. /// </summary> class IGuiGraphicsRenderTarget : public Interface { public: /// <summary> /// Notify the target to prepare for rendering. /// </summary> virtual void StartRendering()=0; /// <summary> /// Notify the target to stop rendering. /// </summary> /// <returns>Returns false to recreate render target.</returns> virtual RenderTargetFailure StopRendering()=0; /// <summary> /// Apply a clipper to the render target. /// The result clipper is combined by all clippers in the clipper stack maintained by the render target. /// </summary> /// <param name="clipper">The clipper to push.</param> virtual void PushClipper(Rect clipper)=0; /// <summary> /// Remove the last pushed clipper from the clipper stack. /// </summary> virtual void PopClipper()=0; /// <summary> /// Get the combined clipper /// </summary> /// <returns>The combined clipper</returns> virtual Rect GetClipper()=0; /// <summary> /// Test is the combined clipper is as large as the render target. /// </summary> /// <returns>Return true if the combined clipper is as large as the render target.</returns> 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 { using namespace reflection; namespace elements { /*********************************************************************** Layout Engine ***********************************************************************/ class IGuiGraphicsParagraph; class IGuiGraphicsLayoutProvider; /// <summary>Represents a paragraph of a layouted rich text content.</summary> class IGuiGraphicsParagraph : public IDescriptable, public Description<IGuiGraphicsParagraph> { public: static const vint NullInteractionId = -1; /// <summary>Text style. Items in this enumeration type can be combined.</summary> enum TextStyle { /// <summary>Bold.</summary> Bold=1, /// <summary>Italic.</summary> Italic=2, /// <summary>Underline.</summary> Underline=4, /// <summary>Strikeline.</summary> Strikeline=8, }; /// <summary>Inline object break condition.</summary> enum BreakCondition { /// <summary>Stay together with the previous run if possible.</summary> StickToPreviousRun, /// <summary>Stay together with the next run if possible.</summary> StickToNextRun, /// <summary>Treat as a single run.</summary> Alone, }; /// <summary>Caret relative position.</summary> enum CaretRelativePosition { /// <summary>The first caret position.</summary> CaretFirst, /// <summary>The last caret position.</summary> CaretLast, /// <summary>The first caret position of the current line.</summary> CaretLineFirst, /// <summary>The last caret position of the current line.</summary> CaretLineLast, /// <summary>The relative left caret position.</summary> CaretMoveLeft, /// <summary>The relative right caret position.</summary> CaretMoveRight, /// <summary>The relative up caret position.</summary> CaretMoveUp, /// <summary>The relative down caret position.</summary> CaretMoveDown, }; /// <summary>Inline object properties.</summary> struct InlineObjectProperties { /// <summary>The size of the inline object.</summary> Size size; /// <summary>The baseline of the inline object.If the baseline is at the bottom, then set the baseline to -1.</summary> vint baseline = -1; /// <summary>The break condition of the inline object.</summary> BreakCondition breakCondition; /// <summary>The background image, nullable.</summary> Ptr<IGuiGraphicsElement> backgroundImage; /// <summary>The id for callback. If the value is -1, then no callback will be received .</summary> vint callbackId = -1; InlineObjectProperties() :baseline(-1) { } }; /// <summary>Get the <see cref="IGuiGraphicsLayoutProvider"/> object that created this paragraph.</summary> /// <returns>The layout provider object.</returns> virtual IGuiGraphicsLayoutProvider* GetProvider()=0; /// <summary>Get the associated <see cref="IGuiGraphicsRenderTarget"/> to this paragraph.</summary> /// <returns>The associated render target.</returns> virtual IGuiGraphicsRenderTarget* GetRenderTarget()=0; /// <summary>Get if line auto-wrapping is enabled for this paragraph.</summary> /// <returns>Return true if line auto-wrapping is enabled for this paragraph.</returns> virtual bool GetWrapLine()=0; /// <summary>Set if line auto-wrapping is enabled for this paragraph.</summary> /// <param name="value">True if line auto-wrapping is enabled for this paragraph.</param> virtual void SetWrapLine(bool value)=0; /// <summary>Get the max width for this paragraph. If there is no max width limitation, it returns -1.</summary> /// <returns>The max width for this paragraph.</returns> virtual vint GetMaxWidth()=0; /// <summary>Set the max width for this paragraph. If the max width is set to -1, the max width limitation will be removed.</summary> /// <param name="value">The max width.</param> virtual void SetMaxWidth(vint value)=0; /// <summary>Get the horizontal alignment for this paragraph.</summary> /// <returns>The alignment.</returns> virtual Alignment GetParagraphAlignment()=0; /// <summary>Set the horizontal alignment for this paragraph.</summary> /// <param name="value">The alignment.</param> virtual void SetParagraphAlignment(Alignment value)=0; /// <summary>Replace the font within the specified range.</summary> /// <param name="start">The position of the first character of the specified range.</param> /// <param name="length">The length of the specified range by character.</param> /// <param name="value">The font.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool SetFont(vint start, vint length, const WString& value)=0; /// <summary>Replace the size within the specified range.</summary> /// <param name="start">The position of the first character of the specified range.</param> /// <param name="length">The length of the specified range by character.</param> /// <param name="value">The size.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool SetSize(vint start, vint length, vint value)=0; /// <summary>Replace the text style within the specified range.</summary> /// <param name="start">The position of the first character of the specified range.</param> /// <param name="length">The length of the specified range by character.</param> /// <param name="value">The text style.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool SetStyle(vint start, vint length, TextStyle value)=0; /// <summary>Replace the color within the specified range.</summary> /// <param name="start">The position of the first character of the specified range.</param> /// <param name="length">The length of the specified range by character.</param> /// <param name="value">The color.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool SetColor(vint start, vint length, Color value)=0; /// <summary>Replace the background color within the specified range.</summary> /// <param name="start">The position of the first character of the specified range.</param> /// <param name="length">The length of the specified range by character.</param> /// <param name="value">The background color.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool SetBackgroundColor(vint start, vint length, Color value)=0; /// <summary>Bind an <see cref="IGuiGraphicsElement"/> to a range of text.</summary> /// <param name="start">The position of the first character of the specified range.</param> /// <param name="length">The length of the specified range by character.</param> /// <param name="properties">The properties for the inline object.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool SetInlineObject(vint start, vint length, const InlineObjectProperties& properties)=0; /// <summary>Unbind all inline objects to a range of text.</summary> /// <param name="start">The position of the first character of the specified range.</param> /// <param name="length">The length of the specified range by character.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool ResetInlineObject(vint start, vint length)=0; /// <summary>Get the layouted height of the text. The result depends on rich styled text and the two important properties that can be set using <see cref="SetWrapLine"/> and <see cref="SetMaxWidth"/>.</summary> /// <returns>The layouted height.</returns> virtual vint GetHeight()=0; /// <summary>Make the caret visible so that it will be rendered in the paragraph.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="caret">The caret.</param> /// <param name="color">The color of the caret.</param> /// <param name="frontSide">Set to true to display the caret for the character before it.</param> virtual bool OpenCaret(vint caret, Color color, bool frontSide)=0; /// <summary>Make the caret invisible.</summary> /// <returns>Returns true if this operation succeeded.</returns> virtual bool CloseCaret()=0; /// <summary>Render the graphics element using a specified bounds.</summary> /// <param name="bounds">Bounds to decide the size and position of the binded graphics element.</param> virtual void Render(Rect bounds)=0; /// <summary>Get a new caret from the old caret with a relative position.</summary> /// <returns>The new caret. Returns -1 if failed.</returns> /// <param name="comparingCaret">The caret to compare. If the position is CaretFirst or CaretLast, this argument is ignored.</param> /// <param name="position">The relative position.</param> /// <param name="preferFrontSide">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.</param> virtual vint GetCaret(vint comparingCaret, CaretRelativePosition position, bool& preferFrontSide)=0; /// <summary>Get the bounds of the caret.</summary> /// <returns>The bounds whose width is 0. Returns an empty Rect value if failed.</returns> /// <param name="caret">The caret.</param> /// <param name="frontSide">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.</param> virtual Rect GetCaretBounds(vint caret, bool frontSide)=0; /// <summary>Get the caret from a specified position.</summary> /// <returns>The caret. Returns -1 if failed.</returns> /// <param name="point">The point.</param> virtual vint GetCaretFromPoint(Point point)=0; /// <summary>Get the inline object from a specified position.</summary> /// <returns>The inline object. Returns null if failed.</returns> /// <param name="point">The point.</param> /// <param name="start">Get the start position of this element.</param> /// <param name="length">Get the length of this element.</param> virtual Nullable<InlineObjectProperties> GetInlineObjectFromPoint(Point point, vint& start, vint& length)=0; /// <summary>Get the nearest caret from a text position.</summary> /// <returns>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.</returns> /// <param name="textPos">The caret to compare. If the position is CaretFirst or CaretLast, this argument is ignored.</param> /// <param name="frontSide">Set to true to search in front of the text position, otherwise the opposite position.</param> virtual vint GetNearestCaretFromTextPos(vint textPos, bool frontSide)=0; /// <summary>Test is the caret valid.</summary> /// <returns>Returns true if the caret is valid.</returns> /// <param name="caret">The caret to test.</param> virtual bool IsValidCaret(vint caret)=0; /// <summary>Test is the text position valid.</summary> /// <returns>Returns true if the text position is valid.</returns> /// <param name="textPos">The text position to test.</param> virtual bool IsValidTextPos(vint textPos)=0; }; /// <summary>Paragraph callback</summary> class IGuiGraphicsParagraphCallback : public IDescriptable, public Description<IGuiGraphicsParagraphCallback> { public: /// <summary>Called when an inline object with a valid callback id is being rendered.</summary> /// <returns>Returns the new size of the rendered inline object.</returns> /// <param name="callbackId">The callback id of the inline object</param> /// <param name="location">The location of the inline object, relative to the left-top corner of this paragraph.</param> virtual Size OnRenderInlineObject(vint callbackId, Rect location) = 0; }; /// <summary>Renderer awared rich text document layout engine provider interface.</summary> class IGuiGraphicsLayoutProvider : public IDescriptable, public Description<IGuiGraphicsLayoutProvider> { public: /// <summary>Create a paragraph with internal renderer device dependent objects initialized.</summary> /// <param name="text">The text used to fill the paragraph.</param> /// <param name="renderTarget">The render target that the created paragraph will render to.</param> /// <param name="callback">A callback to receive necessary information when the paragraph is being rendered.</param> /// <returns>The created paragraph object.</returns> virtual Ptr<IGuiGraphicsParagraph> 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 { using namespace reflection; class DocumentModel; class INativeWindow; class INativeWindowListener; class INativeController; class INativeControllerListener; /*********************************************************************** System Object ***********************************************************************/ /// <summary> /// Represents a screen. /// </summary> class INativeScreen : public virtual IDescriptable, Description<INativeScreen> { public: /// <summary> /// Get the bounds of the screen. /// </summary> /// <returns>The bounds of the screen.</returns> virtual Rect GetBounds()=0; /// <summary> /// Get the bounds of the screen client area. /// </summary> /// <returns>The bounds of the screen client area.</returns> virtual Rect GetClientBounds()=0; /// <summary> /// Get the name of the screen. /// </summary> /// <returns>The name of the screen.</returns> virtual WString GetName()=0; /// <summary> /// Test is the screen is a primary screen. /// </summary> /// <returns>Returns true if the screen is a primary screen.</returns> virtual bool IsPrimary()=0; }; /// <summary> /// Represents a cursor. /// </summary> class INativeCursor : public virtual IDescriptable, Description<INativeCursor> { public: /// <summary> /// Represents a predefined cursor type. /// </summary> enum SystemCursorType { /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Small waiting cursor. /// </summary> SmallWaiting, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]large waiting cursor. /// </summary> LargeWaiting, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Arrow cursor. /// </summary> Arrow, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Cross cursor. /// </summary> Cross, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Hand cursor. /// </summary> Hand, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Help cursor. /// </summary> Help, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]I beam cursor. /// </summary> IBeam, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Sizing in all direction cursor. /// </summary> SizeAll, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Sizing NE-SW cursor. /// </summary> SizeNESW, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Sizing N-S cursor. /// </summary> SizeNS, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Sizing NW-SE cursor. /// </summary> SizeNWSE, /// <summary> /// [T:vl.presentation.INativeCursor.SystemCursorType]Sizing W-E cursor. /// </summary> SizeWE, LastSystemCursor=SizeWE, }; static const vint SystemCursorCount=LastSystemCursor+1; public: /// <summary> /// Test is the cursor a system provided cursor. /// </summary> /// <returns>Returns true if the cursor a system provided cursor.</returns> virtual bool IsSystemCursor()=0; /// <summary> /// Get the cursor type if the cursor a system provided cursor. /// </summary> /// <returns>The cursor type.</returns> virtual SystemCursorType GetSystemCursorType()=0; }; /*********************************************************************** Image Object ***********************************************************************/ class INativeImageService; class INativeImage; class INativeImageFrame; /// <summary> /// Represents a customized cache object for an image frame. /// </summary> class INativeImageFrameCache : public Interface { public: /// <summary> /// Called when this cache object is attached to an image frame. /// </summary> /// <param name="frame">The image frame that attached to.</param> virtual void OnAttach(INativeImageFrame* frame)=0; /// <summary> /// Called when this cache object is detached to an image frame. /// </summary> /// <param name="frame">The image frame that detached from.</param> virtual void OnDetach(INativeImageFrame* frame)=0; }; /// <summary> /// Represents an image frame. /// </summary> class INativeImageFrame : public virtual IDescriptable, public Description<INativeImageFrame> { public: /// <summary> /// Get the image that owns this frame. /// </summary> /// <returns>The image that owns this frame.</returns> virtual INativeImage* GetImage()=0; /// <summary> /// Get the size of this frame. /// </summary> /// <returns>The size of this frame.</returns> virtual Size GetSize()=0; /// <summary> /// Attach a customized cache object to this image frame and bind to a key. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="key">The key binded with the customized cache object.</param> /// <param name="cache">The customized cache object.</param> virtual bool SetCache(void* key, Ptr<INativeImageFrameCache> cache)=0; /// <summary> /// Get the attached customized cache object that is already binded to a key. /// </summary> /// <returns>The attached customized cache object.</returns> /// <param name="key">The key binded with the customized cache object.</param> virtual Ptr<INativeImageFrameCache> GetCache(void* key)=0; /// <summary> /// Get the attached customized cache object that is already binded to a key, and then detach it. /// </summary> /// <returns>The detached customized cache object.</returns> /// <param name="key">The key binded with the customized cache object.</param> virtual Ptr<INativeImageFrameCache> RemoveCache(void* key)=0; }; /// <summary> /// Represents an image. /// </summary> class INativeImage : public virtual IDescriptable, public Description<INativeImage> { public: /// <summary> /// Represents an image format. /// </summary> enum FormatType { /// <summary> /// [T:vl.presentation.INativeImage.FormatType]Bitmap format. /// </summary> Bmp, /// <summary> /// [T:vl.presentation.INativeImage.FormatType]GIF format. /// </summary> Gif, /// <summary> /// [T:vl.presentation.INativeImage.FormatType]Icon format. /// </summary> Icon, /// <summary> /// [T:vl.presentation.INativeImage.FormatType]JPEG format. /// </summary> Jpeg, /// <summary> /// [T:vl.presentation.INativeImage.FormatType]PNG format. /// </summary> Png, /// <summary> /// [T:vl.presentation.INativeImage.FormatType]TIFF format. /// </summary> Tiff, /// <summary> /// [T:vl.presentation.INativeImage.FormatType]WMP format. /// </summary> Wmp, /// <summary> /// [T:vl.presentation.INativeImage.FormatType]Unknown format. /// </summary> Unknown, }; /// <summary> /// Get the image service that creates this image. /// </summary> /// <returns>The image service that creates this image.</returns> virtual INativeImageService* GetImageService()=0; /// <summary> /// Get the image format. /// </summary> /// <returns>The image format.</returns> virtual FormatType GetFormat()=0; /// <summary> /// Get the number of frames in this image. /// </summary> /// <returns>The number of frames in this image.</returns> virtual vint GetFrameCount()=0; /// <summary> /// Get the frame in this image by a specified frame index. /// </summary> /// <returns>The frame in this image by a specified frame index.</returns> /// <param name="index">The specified frame index.</param> virtual INativeImageFrame* GetFrame(vint index)=0; /// <summary> /// Save the image to a stream. /// </summary> /// <param name="stream">The stream.</param> /// <param name="formatType">The format of the image.</param> virtual void SaveToStream(stream::IStream& stream, FormatType formatType = FormatType::Unknown) = 0; }; /// <summary> /// Image service. To access this service, use [M:vl.presentation.INativeController.ImageService]. /// </summary> class INativeImageService : public virtual IDescriptable, public Description<INativeImageService> { public: /// <summary> /// Create an image from file. /// </summary> /// <returns>The created image.</returns> /// <param name="path">The file path.</param> virtual Ptr<INativeImage> CreateImageFromFile(const WString& path)=0; /// <summary> /// Create an image from memory. /// </summary> /// <returns>The created image.</returns> /// <param name="buffer">The memory pointer.</param> /// <param name="length">The memory length.</param> virtual Ptr<INativeImage> CreateImageFromMemory(void* buffer, vint length)=0; /// <summary> /// Create an image from stream. /// </summary> /// <returns>The created image.</returns> /// <param name="stream">The stream.</param> virtual Ptr<INativeImage> CreateImageFromStream(stream::IStream& stream)=0; }; /*********************************************************************** Native Window ***********************************************************************/ /// <summary> /// Represents a window. /// </summary> class INativeWindow : public Interface, public Description<INativeWindow> { public: /// <summary> /// Get the bounds of the window. /// </summary> /// <returns>The bounds of the window.</returns> virtual Rect GetBounds()=0; /// <summary> /// Set the bounds of the window. /// </summary> /// <param name="bounds">The bounds of the window.</param> virtual void SetBounds(const Rect& bounds)=0; /// <summary> /// Get the client size of the window. /// </summary> /// <returns>The client size of the window.</returns> virtual Size GetClientSize()=0; /// <summary> /// Set the client size of the window. /// </summary> /// <param name="size">The client size of the window.</param> virtual void SetClientSize(Size size)=0; /// <summary> /// Get the client bounds in screen space. /// </summary> /// <returns>The client bounds in screen space.</returns> virtual Rect GetClientBoundsInScreen()=0; /// <summary> /// Get the title of the window. A title will be displayed as a name of this window. /// </summary> /// <returns>The title of the window.</returns> virtual WString GetTitle()=0; /// <summary> /// Set the title of the window. A title will be displayed as a name of this window. /// </summary> /// <param name="title">The title of the window.</param> virtual void SetTitle(WString title)=0; /// <summary> /// Get the mouse cursor of the window. When the mouse is on the window, the mouse cursor will be rendered. /// </summary> /// <returns>The mouse cursor of the window.</returns> virtual INativeCursor* GetWindowCursor()=0; /// <summary> /// Set the mouse cursor of the window. When the mouse is on the window, the mouse cursor will be rendered. /// </summary> /// <param name="cursor">The mouse cursor of the window.</param> virtual void SetWindowCursor(INativeCursor* cursor)=0; /// <summary> /// 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. /// </summary> /// <returns>The caret point of the window.</returns> virtual Point GetCaretPoint()=0; /// <summary> /// 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. /// </summary> /// <param name="point">The caret point of the window.</param> virtual void SetCaretPoint(Point point)=0; /// <summary> /// 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. /// </summary> /// <returns>The parent window.</returns> virtual INativeWindow* GetParent()=0; /// <summary> /// 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. /// </summary> /// <param name="parent">The parent window.</param> virtual void SetParent(INativeWindow* parent)=0; /// <summary> /// Test is the window always pass the focus to its parent window. /// </summary> /// <returns>Returns true if the window always pass the focus to its parent window.</returns> virtual bool GetAlwaysPassFocusToParent()=0; /// <summary> /// Enable or disble always passing the focus to its parent window. /// </summary> /// <param name="value">True to enable always passing the focus to its parent window.</param> virtual void SetAlwaysPassFocusToParent(bool value)=0; /// <summary> /// Enable the window customized frame mode. /// </summary> virtual void EnableCustomFrameMode()=0; /// <summary> /// Disable the window customized frame mode. /// </summary> virtual void DisableCustomFrameMode()=0; /// <summary> /// Test is the window customized frame mode enabled. /// </summary> /// <returns>Returns true if the window customized frame mode is enabled.</returns> virtual bool IsCustomFrameModeEnabled()=0; /// <summary>Window size state.</summary> enum WindowSizeState { /// <summary>Minimized.</summary> Minimized, /// <summary>Restored.</summary> Restored, /// <summary>Maximized.</summary> Maximized, }; /// <summary> /// Get the window size state. /// </summary> /// <returns>Returns the window size state.</returns> virtual WindowSizeState GetSizeState()=0; /// <summary> /// Show the window. /// </summary> virtual void Show()=0; /// <summary> /// Show the window without activation. /// </summary> virtual void ShowDeactivated()=0; /// <summary> /// Restore the window. /// </summary> virtual void ShowRestored()=0; /// <summary> /// Maximize the window. /// </summary> virtual void ShowMaximized()=0; /// <summary> /// Minimize the window. /// </summary> virtual void ShowMinimized()=0; /// <summary> /// Hide the window. /// </summary> /// <param name="closeWindow">Set to true to really close the window. Or the window will just be hidden. This parameter only affect the main window.</param> virtual void Hide(bool closeWindow)=0; /// <summary> /// Test is the window visible. /// </summary> /// <returns>Returns true if the window is visible.</returns> virtual bool IsVisible()=0; /// <summary> /// Enable the window. /// </summary> virtual void Enable()=0; /// <summary> /// Disable the window. /// </summary> virtual void Disable()=0; /// <summary> /// Test is the window enabled. /// </summary> /// <returns>Returns true if the window is enabled.</returns> virtual bool IsEnabled()=0; /// <summary> /// Set focus to the window. /// </summary> virtual void SetFocus()=0; /// <summary> /// Test is the window focused. /// </summary> /// <returns>Returns true if the window is focused.</returns> virtual bool IsFocused()=0; /// <summary> /// Activate to the window. /// </summary> virtual void SetActivate()=0; /// <summary> /// Test is the window activated. /// </summary> /// <returns>Returns true if the window is activated.</returns> virtual bool IsActivated()=0; /// <summary> /// Show the icon in the task bar. /// </summary> virtual void ShowInTaskBar()=0; /// <summary> /// Hide the icon in the task bar. /// </summary> virtual void HideInTaskBar()=0; /// <summary> /// Test is the window icon appeared in the task bar. /// </summary> /// <returns>Returns true if the window icon appears in the task bar.</returns> virtual bool IsAppearedInTaskBar()=0; /// <summary> /// Enable activation to the window. /// </summary> virtual void EnableActivate()=0; /// <summary> /// Disable activation to the window. /// </summary> virtual void DisableActivate()=0; /// <summary> /// Test is the window allowed to be activated. /// </summary> /// <returns>Returns true if the window is allowed to be activated.</returns> virtual bool IsEnabledActivate()=0; /// <summary> /// Require mouse message capturing to this window. If the capture is required, all mouse message will be send to this window. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> virtual bool RequireCapture()=0; /// <summary> /// Release mouse message capturing to this window. If the capture is required, all mouse message will be send to this window. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> virtual bool ReleaseCapture()=0; /// <summary> /// Test if the window is capturing mouse messages. /// </summary> /// <returns>Returns true if the window is capturing mouse messages.</returns> virtual bool IsCapturing()=0; /// <summary> /// Test is the maximize box visible. /// </summary> /// <returns>Returns true if the maximize box is visible.</returns> virtual bool GetMaximizedBox()=0; /// <summary> /// Make the maximize box visible or invisible. /// </summary> /// <param name="visible">True to make the maximize box visible.</param> virtual void SetMaximizedBox(bool visible)=0; /// <summary> /// Test is the minimize box visible. /// </summary> /// <returns>Returns true if the minimize box is visible.</returns> virtual bool GetMinimizedBox()=0; /// <summary> /// Make the minimize box visible or invisible. /// </summary> /// <param name="visible">True to make the minimize box visible.</param> virtual void SetMinimizedBox(bool visible)=0; /// <summary> /// Test is the border visible. /// </summary> /// <returns>Returns true if the border is visible.</returns> virtual bool GetBorder()=0; /// <summary> /// Make the border visible or invisible. /// </summary> /// <param name="visible">True to make the border visible.</param> virtual void SetBorder(bool visible)=0; /// <summary> /// Test is the size box visible. /// </summary> /// <returns>Returns true if the size box is visible.</returns> virtual bool GetSizeBox()=0; /// <summary> /// Make the size box visible or invisible. /// </summary> /// <param name="visible">True to make the size box visible.</param> virtual void SetSizeBox(bool visible)=0; /// <summary> /// Test is the icon visible. /// </summary> /// <returns>Returns true if the icon is visible.</returns> virtual bool GetIconVisible()=0; /// <summary> /// Make the icon visible or invisible. /// </summary> /// <param name="visible">True to make the icon visible.</param> virtual void SetIconVisible(bool visible)=0; /// <summary> /// Test is the title bar visible. /// </summary> /// <returns>Returns true if the title bar is visible.</returns> virtual bool GetTitleBar()=0; /// <summary> /// Make the title bar visible or invisible. /// </summary> /// <param name="visible">True to make the title bar visible.</param> virtual void SetTitleBar(bool visible)=0; /// <summary> /// Test is the window always on top of the desktop. /// </summary> /// <returns>Returns true if the window is always on top of the desktop.</returns> virtual bool GetTopMost()=0; /// <summary> /// Make the window always or never on top of the desktop. /// </summary> /// <param name="topmost">True to make the window always on top of the desktop.</param> virtual void SetTopMost(bool topmost)=0; /// <summary> /// Supress the system's Alt+X hot key /// </summary> virtual void SupressAlt() = 0; /// <summary> /// Install an message listener. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="listener">The listener to install.</param> virtual bool InstallListener(INativeWindowListener* listener)=0; /// <summary> /// Uninstall an message listener. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="listener">The listener to uninstall.</param> virtual bool UninstallListener(INativeWindowListener* listener)=0; /// <summary> /// Redraw the content of the window. /// </summary> virtual void RedrawContent()=0; }; /// <summary> /// Mouse message information. /// </summary> struct NativeWindowMouseInfo { /// <summary>True if the control button is pressed.</summary> bool ctrl; /// <summary>True if the shift button is pressed.</summary> bool shift; /// <summary>True if the left mouse button is pressed.</summary> bool left; /// <summary>True if the middle mouse button is pressed.</summary> bool middle; /// <summary>True if the right mouse button is pressed.</summary> bool right; /// <summary>The mouse position of x dimension.</summary> vint x; /// <summary>The mouse position of y dimension.</summary> vint y; /// <summary>The delta of the wheel.</summary> vint wheel; /// <summary>True if the mouse is in the non-client area.</summary> bool nonClient; }; /// <summary> /// Key message information. /// </summary> struct NativeWindowKeyInfo { /// <summary>Key code of the key that sends this message, using VKEY_* macros.</summary> vint code; /// <summary>True if the control button is pressed.</summary> bool ctrl; /// <summary>True if the shift button is pressed.</summary> bool shift; /// <summary>True if the alt button is pressed.</summary> bool alt; /// <summary>True if the capslock button is pressed.</summary> bool capslock; }; /// <summary> /// Character message information. /// </summary> struct NativeWindowCharInfo { /// <summary>Character that sends this message.</summary> wchar_t code; /// <summary>True if the control button is pressed.</summary> bool ctrl; /// <summary>True if the shift button is pressed.</summary> bool shift; /// <summary>True if the alt button is pressed.</summary> bool alt; /// <summary>True if the capslock button is pressed.</summary> bool capslock; }; /// <summary> /// Represents a message listener to an <see cref="INativeWindow"/>. /// </summary> class INativeWindowListener : public Interface { public: /// <summary>Hit test result for a native window.</summary> enum HitTestResult { /// <summary>Border that doesn't contain sizing functionalitiy.</summary> BorderNoSizing, /// <summary>Left border.</summary> BorderLeft, /// <summary>Right border.</summary> BorderRight, /// <summary>Top border.</summary> BorderTop, /// <summary>Bottom border.</summary> BorderBottom, /// <summary>Left top border.</summary> BorderLeftTop, /// <summary>Right top border.</summary> BorderRightTop, /// <summary>Left bottom border.</summary> BorderLeftBottom, /// <summary>Right bottom border.</summary> BorderRightBottom, /// <summary>Title</summary> Title, /// <summary>Minimum button.</summary> ButtonMinimum, /// <summary>Maximum button.</summary> ButtonMaximum, /// <summary>Close button.</summary> ButtonClose, /// <summary>Client button.</summary> Client, /// <summary>Icon.</summary> Icon, /// <summary>Let the OS window layer decide.</summary> NoDecision, }; /// <summary> /// Perform a hit test. /// </summary> /// <returns>Returns the hit test result. If "NoDecision" is returned, the native window provider should call the OS window layer to do the hit test.</returns> /// <param name="location">The location to do the hit test. This location is in the window space (not the client space).</param> virtual HitTestResult HitTest(Point location); /// <summary> /// Called when the window is moving. /// </summary> /// <param name="bounds">The bounds. Message handler can change the bounds.</param> /// <param name="fixSizeOnly">True if the message raise only want the message handler to change the size.</param> virtual void Moving(Rect& bounds, bool fixSizeOnly); /// <summary> /// Called when the window is moved. /// </summary> virtual void Moved(); /// <summary> /// Called when the window is enabled. /// </summary> virtual void Enabled(); /// <summary> /// Called when the window is disabled. /// </summary> virtual void Disabled(); /// <summary> /// Called when the window got the focus. /// </summary> virtual void GotFocus(); /// <summary> /// Called when the window lost the focus. /// </summary> virtual void LostFocus(); /// <summary> /// Called when the window is activated. /// </summary> virtual void Activated(); /// <summary> /// Called when the window is deactivated. /// </summary> virtual void Deactivated(); /// <summary> /// Called when the window is opened. /// </summary> virtual void Opened(); /// <summary> /// Called when the window is closing. /// </summary> /// <param name="cancel">Change the value to true to prevent the windows from being closed.</param> virtual void Closing(bool& cancel); /// <summary> /// Called when the window is closed. /// </summary> virtual void Closed(); /// <summary> /// Called when the window is painting. /// </summary> virtual void Paint(); /// <summary> /// Called when the window is destroying. /// </summary> virtual void Destroying(); /// <summary> /// Called when the window is destroyed. /// </summary> virtual void Destroyed(); /// <summary> /// Called when the left mouse button is pressed. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void LeftButtonDown(const NativeWindowMouseInfo& info); /// <summary> /// Called when the left mouse button is released. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void LeftButtonUp(const NativeWindowMouseInfo& info); /// <summary> /// Called when the left mouse button performed a double click. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void LeftButtonDoubleClick(const NativeWindowMouseInfo& info); /// <summary> /// Called when the right mouse button is pressed. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void RightButtonDown(const NativeWindowMouseInfo& info); /// <summary> /// Called when the right mouse button is released. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void RightButtonUp(const NativeWindowMouseInfo& info); /// <summary> /// Called when the right mouse button performed a double click. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void RightButtonDoubleClick(const NativeWindowMouseInfo& info); /// <summary> /// Called when the middle mouse button is pressed. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void MiddleButtonDown(const NativeWindowMouseInfo& info); /// <summary> /// Called when the middle mouse button is released. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void MiddleButtonUp(const NativeWindowMouseInfo& info); /// <summary> /// Called when the middle mouse button performed a double click. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void MiddleButtonDoubleClick(const NativeWindowMouseInfo& info); /// <summary> /// Called when the horizontal mouse wheel scrolls. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void HorizontalWheel(const NativeWindowMouseInfo& info); /// <summary> /// Called when the horizontal vertical wheel scrolls. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void VerticalWheel(const NativeWindowMouseInfo& info); /// <summary> /// Called when the mouse is moving on the window. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void MouseMoving(const NativeWindowMouseInfo& info); /// <summary> /// Called when the mouse entered the window. /// </summary> virtual void MouseEntered(); /// <summary> /// Called when the mouse leaved the window. /// </summary> virtual void MouseLeaved(); /// <summary> /// Called a key is pressed. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void KeyDown(const NativeWindowKeyInfo& info); /// <summary> /// Called a key is released. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void KeyUp(const NativeWindowKeyInfo& info); /// <summary> /// Called a system key is pressed. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void SysKeyDown(const NativeWindowKeyInfo& info); /// <summary> /// Called a system key is released. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void SysKeyUp(const NativeWindowKeyInfo& info); /// <summary> /// Called an input character is generated. /// </summary> /// <param name="info">Detailed information to this message.</param> virtual void Char(const NativeWindowCharInfo& info); }; /*********************************************************************** Native Window Services ***********************************************************************/ /// <summary> /// System resource service. To access this service, use [M:vl.presentation.INativeController.ResourceService]. /// </summary> class INativeResourceService : public virtual IDescriptable, public Description<INativeResourceService> { public: /// <summary> /// Get a cached cursor object using a predefined system cursor type; /// </summary> /// <returns>The cached cursor object.</returns> /// <param name="type">The predefined system cursor type.</param> virtual INativeCursor* GetSystemCursor(INativeCursor::SystemCursorType type)=0; /// <summary> /// Get a cached cursor object using a default system cursor type; /// </summary> /// <returns>The cached cursor object.</returns> virtual INativeCursor* GetDefaultSystemCursor()=0; /// <summary> /// Get the default font configuration of the system. /// </summary> /// <returns>The default font configuration of the system.</returns> virtual FontProperties GetDefaultFont()=0; /// <summary> /// Override the default font configuration for the current process, only available GacUI library. /// </summary> /// <param name="value">The font configuration to override.</param> virtual void SetDefaultFont(const FontProperties& value)=0; }; /// <summary> /// Delay execution controller. /// </summary> class INativeDelay : public virtual IDescriptable, public Description<INativeDelay> { public: /// <summary>Delay execution controller status.</summary> enum ExecuteStatus { /// <summary>Pending.</summary> Pending, /// <summary>Executing.</summary> Executing, /// <summary>Executed.</summary> Executed, /// <summary>Canceled.</summary> Canceled, }; /// <summary>Get the current status.</summary> /// <returns>The current status.</returns> virtual ExecuteStatus GetStatus()=0; /// <summary>If the current task is pending, execute the task after a specified period.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="milliseconds">A specified period.</param> virtual bool Delay(vint milliseconds)=0; /// <summary>If the current task is pending, cancel the task.</summary> /// <returns>Returns true if this operation succeeded.</returns> virtual bool Cancel()=0; }; /// <summary> /// Asynchronized operation service. GacUI is not a thread safe library except for this service. To access this service, use [M:vl.presentation.INativeController.AsyncService]. /// </summary> class INativeAsyncService : public virtual IDescriptable, public Description<INativeAsyncService> { public: /// <summary> /// Test is the current thread the main thread. /// </summary> /// <returns>Returns true if the current thread is the main thread.</returns> /// <param name="window">A window to access the corressponding main thread.</param> virtual bool IsInMainThread(INativeWindow* window)=0; /// <summary> /// Invoke a specified function with an specified argument asynchronisly. /// </summary> /// <param name="proc">The specified function.</param> virtual void InvokeAsync(const Func<void()>& proc)=0; /// <summary> /// Invoke a specified function with an specified argument in the main thread. /// </summary> /// <param name="window">A window to access the corressponding main thread.</param> /// <param name="proc">The specified function.</param> virtual void InvokeInMainThread(INativeWindow* window, const Func<void()>& proc)=0; /// <summary> /// Invoke a specified function with an specified argument in the main thread and wait for the function to complete or timeout. /// </summary> /// <returns>Return true if the function complete. Return false if the function has not completed during a specified period of time.</returns> /// <param name="window">A window to access the corressponding main thread.</param> /// <param name="proc">The specified function.</param> /// <param name="milliseconds">The specified period of time to wait. Set to -1 (default value) to wait forever until the function completed.</param> virtual bool InvokeInMainThreadAndWait(INativeWindow* window, const Func<void()>& proc, vint milliseconds=-1)=0; /// <summary> /// Delay execute a specified function with an specified argument asynchronisly. /// </summary> /// <returns>The Delay execution controller for this task.</returns> /// <param name="proc">The specified function.</param> /// <param name="milliseconds">Time to delay.</param> virtual Ptr<INativeDelay> DelayExecute(const Func<void()>& proc, vint milliseconds)=0; /// <summary> /// Delay execute a specified function with an specified argument in the main thread. /// </summary> /// <returns>The Delay execution controller for this task.</returns> /// <param name="proc">The specified function.</param> /// <param name="milliseconds">Time to delay.</param> virtual Ptr<INativeDelay> DelayExecuteInMainThread(const Func<void()>& proc, vint milliseconds)=0; }; /// <summary> /// Clipboard reader. /// </summary> class INativeClipboardReader : public virtual IDescriptable, public Description<INativeClipboardReader> { public: /// <summary>Test is there a text in the clipboard.</summary> /// <returns>Returns true if there is a text in the clipboard.</returns> virtual bool ContainsText() = 0; /// <summary>Get the text from the clipboard.</summary> /// <returns>The text.</returns> virtual WString GetText() = 0; /// <summary>Test is there a document in the clipboard.</summary> /// <returns>Returns true if there is a document in the clipboard.</returns> virtual bool ContainsDocument() = 0; /// <summary>Get the document from the clipboard.</summary> /// <returns>The document.</returns> virtual Ptr<DocumentModel> GetDocument() = 0; /// <summary>Test is there an image in the clipboard.</summary> /// <returns>Returns true if there is an image in the clipboard.</returns> virtual bool ContainsImage() = 0; /// <summary>Get the image from the clipboard.</summary> /// <returns>The image.</returns> virtual Ptr<INativeImage> GetImage() = 0; }; /// <summary> /// Clipboard writer. /// </summary> class INativeClipboardWriter : public virtual IDescriptable, public Description<INativeClipboardWriter> { public: /// <summary>Prepare a text for the clipboard.</summary> /// <param name="value">The text.</param> virtual void SetText(const WString& value) = 0; /// <summary>Prepare a document for the clipboard.</summary> /// <param name="value">The document.</param> virtual void SetDocument(Ptr<DocumentModel> value) = 0; /// <summary>Prepare an image for the clipboard.</summary> /// <param name="value">The image.</param> virtual void SetImage(Ptr<INativeImage> value) = 0; /// <summary>Send all data to the clipboard.</summary> virtual void Submit() = 0; }; /// <summary> /// Clipboard service. To access this service, use [M:vl.presentation.INativeController.ClipboardService]. /// </summary> class INativeClipboardService : public virtual IDescriptable, public Description<INativeClipboardService> { public: /// <summary>Read clipboard.</summary> /// <returns>The clipboard reader.</returns> virtual Ptr<INativeClipboardReader> ReadClipboard() = 0; /// <summary>Write clipboard.</summary> /// <returns>The clipboard writer.</returns> virtual Ptr<INativeClipboardWriter> WriteClipboard() = 0; }; /// <summary> /// Screen information service. To access this service, use [M:vl.presentation.INativeController.ScreenService]. /// </summary> class INativeScreenService : public virtual IDescriptable, public Description<INativeScreenService> { public: /// <summary> /// Get the number of all available screens. /// </summary> /// <returns>The number of all available screens.</returns> virtual vint GetScreenCount()=0; /// <summary> /// Get the screen object by a specified screen index. /// </summary> /// <returns>The screen object.</returns> /// <param name="index">The specified screen index.</param> virtual INativeScreen* GetScreen(vint index)=0; /// <summary> /// Get the screen object where the main part of the specified window is inside. /// </summary> /// <returns>The screen object.</returns> /// <param name="window">The specified window.</param> virtual INativeScreen* GetScreen(INativeWindow* window)=0; }; /// <summary> /// Window service. To access this service, use [M:vl.presentation.INativeController.WindowService]. /// </summary> class INativeWindowService : public virtual Interface { public: /// <summary> /// Create a window. /// </summary> /// <returns>The created window.</returns> virtual INativeWindow* CreateNativeWindow() = 0; /// <summary> /// Destroy a window. /// </summary> /// <param name="window">The window to destroy.</param> virtual void DestroyNativeWindow(INativeWindow* window) = 0; /// <summary> /// Get the main window. /// </summary> /// <returns>The main window.</returns> virtual INativeWindow* GetMainWindow() = 0; /// <summary> /// Get the window that under a specified position in screen space. /// </summary> /// <returns>The window that under a specified position in screen space.</returns> /// <param name="location">The specified position in screen space.</param> virtual INativeWindow* GetWindow(Point location) = 0; /// <summary> /// Make the specified window a main window, show that window, and wait until the windows is closed. /// </summary> /// <param name="window">The specified window.</param> virtual void Run(INativeWindow* window) = 0; }; /// <summary> /// User input service. To access this service, use [M:vl.presentation.INativeController.InputService]. /// </summary> class INativeInputService : public virtual IDescriptable, public Description<INativeInputService> { public: /// <summary> /// Start to reveive global mouse message. /// </summary> virtual void StartHookMouse()=0; /// <summary> /// Stop to receive global mouse message. /// </summary> virtual void StopHookMouse()=0; /// <summary> /// Test is the global mouse message receiving enabled. /// </summary> /// <returns>Returns true if the global mouse message receiving is enabled.</returns> virtual bool IsHookingMouse()=0; /// <summary> /// Start to reveive global timer message. /// </summary> virtual void StartTimer()=0; /// <summary> /// Stop to receive global timer message. /// </summary> virtual void StopTimer()=0; /// <summary> /// Test is the global timer message receiving enabled. /// </summary> /// <returns>Returns true if the global timer message receiving is enabled.</returns> virtual bool IsTimerEnabled()=0; /// <summary> /// Test is the specified key pressing. /// </summary> /// <returns>Returns true if the specified key is pressing.</returns> /// <param name="code">The key code to test, using VKEY_* macros.</param> virtual bool IsKeyPressing(vint code)=0; /// <summary> /// Test is the specified key toggled. /// </summary> /// <returns>Returns true if the specified key is toggled.</returns> /// <param name="code">The key code to test, using VKEY_* macros.</param> virtual bool IsKeyToggled(vint code)=0; /// <summary> /// Get the name of a key. /// </summary> /// <returns>The name of a key.</returns> /// <param name="code">The key code, using VKEY_* macros.</param> virtual WString GetKeyName(vint code)=0; /// <summary> /// Get the key from a name. /// </summary> /// <returns>The key, returns -1 if the key name doesn't exist.</returns> /// <param name="name">Key name</param> virtual vint GetKey(const WString& name)=0; }; /// <summary> /// Callback service. To access this service, use [M:vl.presentation.INativeController.CallbackService]. /// </summary> class INativeCallbackService : public virtual Interface { public: /// <summary> /// Install a global message listener. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="listener">The global message listener to install.</param> virtual bool InstallListener(INativeControllerListener* listener)=0; /// <summary> /// Uninstall a global message listener. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="listener">The global message listener to uninstall.</param> virtual bool UninstallListener(INativeControllerListener* listener)=0; }; /// <summary> /// Dialog service. To access this service, use [M:vl.presentation.INativeController.DialogService]. /// </summary> class INativeDialogService : public virtual Interface { public: /// <summary> /// Message box button combination for displaying a message box. /// </summary> enum MessageBoxButtonsInput { /// <summary>Display OK.</summary> DisplayOK, /// <summary>Display OK, Cancel.</summary> DisplayOKCancel, /// <summary>Display Yes, No.</summary> DisplayYesNo, /// <summary>Display Yes, No, Cancel.</summary> DisplayYesNoCancel, /// <summary>Display Retry, Cancel.</summary> DisplayRetryCancel, /// <summary>Display Abort, Retry, Ignore.</summary> DisplayAbortRetryIgnore, /// <summary>Display Cancel, TryAgain, Continue.</summary> DisplayCancelTryAgainContinue, }; /// <summary> /// Message box button to indicate what the user selected. /// </summary> enum MessageBoxButtonsOutput { /// <summary>Select OK.</summary> SelectOK, /// <summary>Select Cancel.</summary> SelectCancel, /// <summary>Select Yes.</summary> SelectYes, /// <summary>Select No.</summary> SelectNo, /// <summary>Select Retry.</summary> SelectRetry, /// <summary>Select Abort.</summary> SelectAbort, /// <summary>Select Ignore.</summary> SelectIgnore, /// <summary>Select TryAgain.</summary> SelectTryAgain, /// <summary>Select Continue.</summary> SelectContinue, }; /// <summary> /// Message box default button. /// </summary> enum MessageBoxDefaultButton { /// <summary>First.</summary> DefaultFirst, /// <summary>Second.</summary> DefaultSecond, /// <summary>Third.</summary> DefaultThird, }; /// <summary> /// Message box icons. /// </summary> enum MessageBoxIcons { /// <summary>No icon.</summary> IconNone, /// <summary>Error icon.</summary> IconError, /// <summary>Question icon.</summary> IconQuestion, /// <summary>Warning icon.</summary> IconWarning, /// <summary>Information icon.</summary> IconInformation, }; /// <summary> /// Message box model options. /// </summary> enum MessageBoxModalOptions { /// <summary>Disable the current window.</summary> ModalWindow, /// <summary>Disable all windows in the application.</summary> ModalTask, /// <summary>Top most message box in the whole system.</summary> ModalSystem, }; /// <summary>Show a message box.</summary> /// <returns>Returns the user selected button.</returns> /// <param name="window">The current window. This argument can be null.</param> /// <param name="text">The content of the message box.</param> /// <param name="title">The title of the message box.</param> /// <param name="buttons">The display button combination of the message box.</param> /// <param name="defaultButton">The default button of the message box.</param> /// <param name="icon">The icon of the message box.</param> /// <param name="modal">The modal option of the message box.</param> 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; /// <summary> /// Color dialog custom color options /// </summary> enum ColorDialogCustomColorOptions { /// <summary>Disable the custom color panel.</summary> CustomColorDisabled, /// <summary>Enable the custom color panel.</summary> CustomColorEnabled, /// <summary>Open the custom color panel at the beginning.</summary> CustomColorOpened, }; /// <summary>Show a color dialog.</summary> /// <returns>Returns true if the user selected the OK button.</returns> /// <param name="window">The current window.</param> /// <param name="selection">The color that the user selected.</param> /// <param name="selected">Make the color dialog selected the color specified in the "selection" parameter at the beginning.</param> /// <param name="customColorOptions">Custom color panel options.</param> /// <param name="customColors">The initial 16 colors in custom color boxes. This argument can be null.</param> virtual bool ShowColorDialog(INativeWindow* window, Color& selection, bool selected=false, ColorDialogCustomColorOptions customColorOptions=CustomColorEnabled, Color* customColors=0)=0; /// <summary>Show a font dialog.</summary> /// <returns>Returns true if the user selected the OK button.</returns> /// <param name="window">The current window.</param> /// <param name="selectionFont">The font that the user selected.</param> /// <param name="selectionColor">The color that the user selected.</param> /// <param name="selected">Make the font dialog selected the font specified in the "selectionFont" and "selectionColor" parameters at the beginning.</param> /// <param name="showEffect">Enable the user to edit some extended font properties.</param> /// <param name="forceFontExist">Force the user to select existing font.</param> virtual bool ShowFontDialog(INativeWindow* window, FontProperties& selectionFont, Color& selectionColor, bool selected=false, bool showEffect=true, bool forceFontExist=true)=0; /// <summary> /// File dialog type. /// </summary> enum FileDialogTypes { /// <summary>Open file dialog.</summary> FileDialogOpen, /// <summary>Open file dialog with preview.</summary> FileDialogOpenPreview, /// <summary>Save file dialog.</summary> FileDialogSave, /// <summary>Save file dialog with preview.</summary> FileDialogSavePreview, }; /// <summary> /// File dialog options. /// </summary> enum FileDialogOptions { /// <summary>Allow multiple selection.</summary> FileDialogAllowMultipleSelection = 1, /// <summary>Prevent the user to select unexisting files.</summary> FileDialogFileMustExist = 2, /// <summary>Show the "Read Only" check box.</summary> FileDialogShowReadOnlyCheckBox = 4, /// <summary>Dereference link files.</summary> FileDialogDereferenceLinks = 8, /// <summary>Show the "Network" button.</summary> FileDialogShowNetworkButton = 16, /// <summary>Prompt if a new file is going to be created.</summary> FileDialogPromptCreateFile = 32, /// <summary>Promt if a existing file is going to be overwritten.</summary> FileDialogPromptOverwriteFile = 64, /// <summary>Prevent the user to select an unexisting directory.</summary> FileDialogDirectoryMustExist = 128, /// <summary>Add user selected files to "Recent" directory.</summary> FileDialogAddToRecent = 256, }; /// <summary>Show a file dialog.</summary> /// <returns>Returns true if the user selected the OK button.</returns> /// <param name="window">The current window.</param> /// <param name="selectionFileNames">The file names that the user selected.</param> /// <param name="selectionFilterIndex">The filter that the user selected.</param> /// <param name="dialogType">The type of the file dialog.</param> /// <param name="title">The title of the file dialog.</param> /// <param name="initialFileName">The initial file name.</param> /// <param name="initialDirectory">The initial directory.</param> /// <param name="defaultExtension">The default file extension.</param> /// <param name="filter">The file name filter like L"Text Files|*.txt|All Files|*.*".</param> /// <param name="options">File dialog options. Multiple options can be combined using the "|" operator.</param> virtual bool ShowFileDialog(INativeWindow* window, collections::List<WString>& 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<INativeDialogService::FileDialogOptions>(static_cast<vuint64_t>(a) | static_cast<vuint64_t>(b)); } inline INativeDialogService::FileDialogOptions operator&(INativeDialogService::FileDialogOptions a, INativeDialogService::FileDialogOptions b) { return static_cast<INativeDialogService::FileDialogOptions>(static_cast<vuint64_t>(a) & static_cast<vuint64_t>(b)); } /*********************************************************************** Native Window Controller ***********************************************************************/ /// <summary> /// Global native system service controller. Use [M:vl.presentation.GetCurrentController] to access this controller. /// </summary> class INativeController : public virtual IDescriptable, public Description<INativeController> { public: /// <summary> /// Get the callback service. /// </summary> /// <returns>The callback service</returns> virtual INativeCallbackService* CallbackService()=0; /// <summary> /// Get the system resource service. /// </summary> /// <returns>The system resource service</returns> virtual INativeResourceService* ResourceService()=0; /// <summary> /// Get the asynchronized operation service. /// </summary> /// <returns>The asynchronized operation service</returns> virtual INativeAsyncService* AsyncService()=0; /// <summary> /// Get the clipboard service. /// </summary> /// <returns>The clipboard service</returns> virtual INativeClipboardService* ClipboardService()=0; /// <summary> /// Get the image service. /// </summary> /// <returns>The image service</returns> virtual INativeImageService* ImageService()=0; /// <summary> /// Get the screen information service. /// </summary> /// <returns>The screen information service</returns> virtual INativeScreenService* ScreenService()=0; /// <summary> /// Get the window service. /// </summary> /// <returns>The window service</returns> virtual INativeWindowService* WindowService()=0; /// <summary> /// Get the user input service. /// </summary> /// <returns>The user input service</returns> virtual INativeInputService* InputService()=0; /// <summary> /// Get the dialog service. /// </summary> /// <returns>The user dialog service</returns> virtual INativeDialogService* DialogService()=0; /// <summary> /// Get the file path of the current executable. /// </summary> /// <returns>The file path of the current executable.</returns> virtual WString GetExecutablePath()=0; }; /// <summary> /// Represents a global message listener to an <see cref="INativeController"/>. /// </summary> class INativeControllerListener : public Interface { public: /// <summary> /// Called when the left mouse button is pressed. To receive or not receive this message, use <see cref="INativeInputService::StartHookMouse"/> or <see cref="INativeInputService::StopHookMouse"/>. /// </summary> /// <param name="position">The mouse position in the screen space.</param> virtual void LeftButtonDown(Point position); /// <summary> /// Called when the left mouse button is released. To receive or not receive this message, use <see cref="INativeInputService::StartHookMouse"/> or <see cref="INativeInputService::StopHookMouse"/> /// </summary> /// <param name="position">The mouse position in the screen space.</param> virtual void LeftButtonUp(Point position); /// <summary> /// Called when the right mouse button is pressed. To receive or not receive this message, use <see cref="INativeInputService::StartHookMouse"/> or <see cref="INativeInputService::StopHookMouse"/> /// </summary> /// <param name="position">The mouse position in the screen space.</param> virtual void RightButtonDown(Point position); /// <summary> /// Called when the right mouse button is released. To receive or not receive this message, use <see cref="INativeInputService::StartHookMouse"/> or <see cref="INativeInputService::StopHookMouse"/> /// </summary> /// <param name="position">The mouse position in the screen space.</param> virtual void RightButtonUp(Point position); /// <summary> /// Called when the mouse is moving. To receive or not receive this message, use <see cref="INativeInputService::StartHookMouse"/> or <see cref="INativeInputService::StopHookMouse"/> /// </summary> /// <param name="position">The mouse position in the screen space.</param> virtual void MouseMoving(Point position); /// <summary> /// Called when the global timer message raised. To receive or not receive this message, use <see cref="INativeInputService::StartTimer"/> or <see cref="INativeInputService::StopTimer"/> /// </summary> virtual void GlobalTimer(); /// <summary> /// Called when the content of the clipboard is updated. /// </summary> virtual void ClipboardUpdated(); /// <summary> /// Called when a window is created. /// </summary> /// <param name="window">The created window.</param> virtual void NativeWindowCreated(INativeWindow* window); /// <summary> /// Called when a window is destroying. /// </summary> /// <param name="window">The destroying window.</param> virtual void NativeWindowDestroying(INativeWindow* window); }; /// <summary> /// Get the global native system service controller. /// </summary> /// <returns>The global native system service controller.</returns> extern INativeController* GetCurrentController(); /// <summary> /// Set the global native system service controller. /// </summary> /// <param name="controller">The global native system service controller.</param> extern void SetCurrentController(INativeController* controller); } } /*********************************************************************** Native Window Provider ***********************************************************************/ /* * Virtual Keys, Standard Set */ #define VKEY_LBUTTON 0x01 #define VKEY_RBUTTON 0x02 #define VKEY_CANCEL 0x03 #define VKEY_MBUTTON 0x04 /* NOT contiguous with L & RBUTTON */ #define VKEY_XBUTTON1 0x05 /* NOT contiguous with L & RBUTTON */ #define VKEY_XBUTTON2 0x06 /* NOT contiguous with L & RBUTTON */ /* * 0x07 : unassigned */ #define VKEY_BACK 0x08 #define VKEY_TAB 0x09 /* * 0x0A - 0x0B : reserved */ #define VKEY_CLEAR 0x0C #define VKEY_RETURN 0x0D #define VKEY_SHIFT 0x10 #define VKEY_CONTROL 0x11 #define VKEY_MENU 0x12 #define VKEY_PAUSE 0x13 #define VKEY_CAPITAL 0x14 #define VKEY_KANA 0x15 #define VKEY_HANGEUL 0x15 /* old name - should be here for compatibility */ #define VKEY_HANGUL 0x15 #define VKEY_JUNJA 0x17 #define VKEY_FINAL 0x18 #define VKEY_HANJA 0x19 #define VKEY_KANJI 0x19 #define VKEY_ESCAPE 0x1B #define VKEY_CONVERT 0x1C #define VKEY_NONCONVERT 0x1D #define VKEY_ACCEPT 0x1E #define VKEY_MODECHANGE 0x1F #define VKEY_SPACE 0x20 #define VKEY_PRIOR 0x21 #define VKEY_NEXT 0x22 #define VKEY_END 0x23 #define VKEY_HOME 0x24 #define VKEY_LEFT 0x25 #define VKEY_UP 0x26 #define VKEY_RIGHT 0x27 #define VKEY_DOWN 0x28 #define VKEY_SELECT 0x29 #define VKEY_PRINT 0x2A #define VKEY_EXECUTE 0x2B #define VKEY_SNAPSHOT 0x2C #define VKEY_INSERT 0x2D #define VKEY_DELETE 0x2E #define VKEY_HELP 0x2F /* * VKEY_0 - VKEY_9 are the same as ASCII '0' - '9' (0x30 - 0x39) * 0x40 : unassigned * VKEY_A - VKEY_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) */ #define VKEY_0 0x30 #define VKEY_1 0x31 #define VKEY_2 0x32 #define VKEY_3 0x33 #define VKEY_4 0x34 #define VKEY_5 0x35 #define VKEY_6 0x36 #define VKEY_7 0x37 #define VKEY_8 0x38 #define VKEY_9 0x39 #define VKEY_A 0x41 #define VKEY_B 0x42 #define VKEY_C 0x43 #define VKEY_D 0x44 #define VKEY_E 0x45 #define VKEY_F 0x46 #define VKEY_G 0x47 #define VKEY_H 0x48 #define VKEY_I 0x49 #define VKEY_J 0x4A #define VKEY_K 0x4B #define VKEY_L 0x4C #define VKEY_M 0x4D #define VKEY_N 0x4E #define VKEY_O 0x4F #define VKEY_P 0x50 #define VKEY_Q 0x51 #define VKEY_R 0x52 #define VKEY_S 0x53 #define VKEY_T 0x54 #define VKEY_U 0x55 #define VKEY_V 0x56 #define VKEY_W 0x57 #define VKEY_X 0x58 #define VKEY_Y 0x59 #define VKEY_Z 0x5A #define VKEY_LWIN 0x5B #define VKEY_RWIN 0x5C #define VKEY_APPS 0x5D /* * 0x5E : reserved */ #define VKEY_SLEEP 0x5F #define VKEY_NUMPAD0 0x60 #define VKEY_NUMPAD1 0x61 #define VKEY_NUMPAD2 0x62 #define VKEY_NUMPAD3 0x63 #define VKEY_NUMPAD4 0x64 #define VKEY_NUMPAD5 0x65 #define VKEY_NUMPAD6 0x66 #define VKEY_NUMPAD7 0x67 #define VKEY_NUMPAD8 0x68 #define VKEY_NUMPAD9 0x69 #define VKEY_MULTIPLY 0x6A #define VKEY_ADD 0x6B #define VKEY_SEPARATOR 0x6C #define VKEY_SUBTRACT 0x6D #define VKEY_DECIMAL 0x6E #define VKEY_DIVIDE 0x6F #define VKEY_F1 0x70 #define VKEY_F2 0x71 #define VKEY_F3 0x72 #define VKEY_F4 0x73 #define VKEY_F5 0x74 #define VKEY_F6 0x75 #define VKEY_F7 0x76 #define VKEY_F8 0x77 #define VKEY_F9 0x78 #define VKEY_F10 0x79 #define VKEY_F11 0x7A #define VKEY_F12 0x7B #define VKEY_F13 0x7C #define VKEY_F14 0x7D #define VKEY_F15 0x7E #define VKEY_F16 0x7F #define VKEY_F17 0x80 #define VKEY_F18 0x81 #define VKEY_F19 0x82 #define VKEY_F20 0x83 #define VKEY_F21 0x84 #define VKEY_F22 0x85 #define VKEY_F23 0x86 #define VKEY_F24 0x87 /* * 0x88 - 0x8F : unassigned */ #define VKEY_NUMLOCK 0x90 #define VKEY_SCROLL 0x91 /* * NEC PC-9800 kbd definitions */ #define VKEY_OEM_NEC_EQUAL 0x92 // '=' key on numpad /* * Fujitsu/OASYS kbd definitions */ #define VKEY_OEM_FJ_JISHO 0x92 // 'Dictionary' key #define VKEY_OEM_FJ_MASSHOU 0x93 // 'Unregister word' key #define VKEY_OEM_FJ_TOUROKU 0x94 // 'Register word' key #define VKEY_OEM_FJ_LOYA 0x95 // 'Left OYAYUBI' key #define VKEY_OEM_FJ_ROYA 0x96 // 'Right OYAYUBI' key /* * 0x97 - 0x9F : unassigned */ /* * 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. */ #define VKEY_LSHIFT 0xA0 #define VKEY_RSHIFT 0xA1 #define VKEY_LCONTROL 0xA2 #define VKEY_RCONTROL 0xA3 #define VKEY_LMENU 0xA4 #define VKEY_RMENU 0xA5 #define VKEY_BROWSER_BACK 0xA6 #define VKEY_BROWSER_FORWARD 0xA7 #define VKEY_BROWSER_REFRESH 0xA8 #define VKEY_BROWSER_STOP 0xA9 #define VKEY_BROWSER_SEARCH 0xAA #define VKEY_BROWSER_FAVORITES 0xAB #define VKEY_BROWSER_HOME 0xAC #define VKEY_VOLUME_MUTE 0xAD #define VKEY_VOLUME_DOWN 0xAE #define VKEY_VOLUME_UP 0xAF #define VKEY_MEDIA_NEXT_TRACK 0xB0 #define VKEY_MEDIA_PREV_TRACK 0xB1 #define VKEY_MEDIA_STOP 0xB2 #define VKEY_MEDIA_PLAY_PAUSE 0xB3 #define VKEY_LAUNCH_MAIL 0xB4 #define VKEY_LAUNCH_MEDIA_SELECT 0xB5 #define VKEY_LAUNCH_APP1 0xB6 #define VKEY_LAUNCH_APP2 0xB7 /* * 0xB8 - 0xB9 : reserved */ #define VKEY_OEM_1 0xBA // ';:' for US #define VKEY_OEM_PLUS 0xBB // '+' any country #define VKEY_OEM_COMMA 0xBC // ',' any country #define VKEY_OEM_MINUS 0xBD // '-' any country #define VKEY_OEM_PERIOD 0xBE // '.' any country #define VKEY_OEM_2 0xBF // '/?' for US #define VKEY_OEM_3 0xC0 // '`~' for US /* * 0xC1 - 0xD7 : reserved */ /* * 0xD8 - 0xDA : unassigned */ #define VKEY_OEM_4 0xDB // '[{' for US #define VKEY_OEM_5 0xDC // '\|' for US #define VKEY_OEM_6 0xDD // ']}' for US #define VKEY_OEM_7 0xDE // ''"' for US #define VKEY_OEM_8 0xDF /* * 0xE0 : reserved */ /* * Various extended or enhanced keyboards */ #define VKEY_OEM_AX 0xE1 // 'AX' key on Japanese AX kbd #define VKEY_OEM_102 0xE2 // "<>" or "\|" on RT 102-key kbd. #define VKEY_ICO_HELP 0xE3 // Help key on ICO #define VKEY_ICO_00 0xE4 // 00 key on ICO #define VKEY_PROCESSKEY 0xE5 #define VKEY_ICO_CLEAR 0xE6 #define VKEY_PACKET 0xE7 /* * 0xE8 : unassigned */ /* * Nokia/Ericsson definitions */ #define VKEY_OEM_RESET 0xE9 #define VKEY_OEM_JUMP 0xEA #define VKEY_OEM_PA1 0xEB #define VKEY_OEM_PA2 0xEC #define VKEY_OEM_PA3 0xED #define VKEY_OEM_WSCTRL 0xEE #define VKEY_OEM_CUSEL 0xEF #define VKEY_OEM_ATTN 0xF0 #define VKEY_OEM_FINISH 0xF1 #define VKEY_OEM_COPY 0xF2 #define VKEY_OEM_AUTO 0xF3 #define VKEY_OEM_ENLW 0xF4 #define VKEY_OEM_BACKTAB 0xF5 #define VKEY_ATTN 0xF6 #define VKEY_CRSEL 0xF7 #define VKEY_EXSEL 0xF8 #define VKEY_EREOF 0xF9 #define VKEY_PLAY 0xFA #define VKEY_ZOOM 0xFB #define VKEY_NONAME 0xFC #define VKEY_PA1 0xFD #define VKEY_OEM_CLEAR 0xFE /* * Friendly names for common keys (US) */ #define VKEY_SEMICOLON VKEY_OEM_1 #define VKEY_SLASH VKEY_OEM_2 #define VKEY_GRAVE_ACCENT VKEY_OEM_3 #define VKEY_RIGHT_BRACKET VKEY_OEM_4 #define VKEY_BACKSLASH VKEY_OEM_5 #define VKEY_LEFT_BRACKET VKEY_OEM_6 #define VKEY_APOSTROPHE VKEY_OEM_7 #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSEVENTRECEIVER.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Event Model Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSEVENTRECEIVER #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSEVENTRECEIVER namespace vl { namespace presentation { namespace controls { namespace tree { class INodeProvider; } } } } namespace vl { namespace presentation { using namespace reflection; namespace compositions { class GuiGraphicsComposition; /*********************************************************************** Event ***********************************************************************/ class IGuiGraphicsEventHandler : public virtual IDescriptable, public Description<IGuiGraphicsEventHandler> { public: class Container { public: Ptr<IGuiGraphicsEventHandler> handler; }; virtual bool IsAttached() = 0; }; template<typename T> class GuiGraphicsEvent : public Object, public Description<GuiGraphicsEvent<T>> { public: typedef void(RawFunctionType)(GuiGraphicsComposition*, T&); typedef Func<RawFunctionType> 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<FunctionHandler> handler; Ptr<HandlerNode> next; }; GuiGraphicsComposition* sender; Ptr<HandlerNode> handlers; bool Attach(Ptr<FunctionHandler> handler) { Ptr<HandlerNode>* 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<typename TClass, typename TMethod> Ptr<IGuiGraphicsEventHandler> AttachMethod(TClass* receiver, TMethod TClass::* method) { auto handler=MakePtr<FunctionHandler>(FunctionType(receiver, method)); Attach(handler); return handler; } Ptr<IGuiGraphicsEventHandler> AttachFunction(RawFunctionType* function) { auto handler = MakePtr<FunctionHandler>(FunctionType(function)); Attach(handler); return handler; } Ptr<IGuiGraphicsEventHandler> AttachFunction(const FunctionType& function) { auto handler = MakePtr<FunctionHandler>(function); Attach(handler); return handler; } template<typename TLambda> Ptr<IGuiGraphicsEventHandler> AttachLambda(const TLambda& lambda) { auto handler = MakePtr<FunctionHandler>(FunctionType(lambda)); Attach(handler); return handler; } bool Detach(Ptr<IGuiGraphicsEventHandler> handler) { auto typedHandler = handler.Cast<FunctionHandler>(); 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 ***********************************************************************/ /// <summary>Notify event arguments.</summary> struct GuiEventArgs : public Object, public AggregatableDescription<GuiEventArgs> { /// <summary>The event raiser composition.</summary> GuiGraphicsComposition* compositionSource; /// <summary>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.</summary> GuiGraphicsComposition* eventSource; /// <summary>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.</summary> bool handled; /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to null.</summary> GuiEventArgs() :compositionSource(0) ,eventSource(0) ,handled(false) { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiEventArgs(GuiGraphicsComposition* composition) :compositionSource(composition) ,eventSource(composition) ,handled(false) { } ~GuiEventArgs() { FinalizeAggregation(); } }; /// <summary>Request event arguments.</summary> struct GuiRequestEventArgs : public GuiEventArgs, public Description<GuiRequestEventArgs> { /// <summary>Set this field to false in event handlers will stop the corresponding action.</summary> bool cancel; /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to null.</summary> GuiRequestEventArgs() :cancel(false) { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiRequestEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,cancel(false) { } }; /// <summary>Keyboard event arguments.</summary> struct GuiKeyEventArgs : public GuiEventArgs, public NativeWindowKeyInfo, public Description<GuiKeyEventArgs> { /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to null.</summary> GuiKeyEventArgs() { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiKeyEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; /// <summary>Char input event arguments.</summary> struct GuiCharEventArgs : public GuiEventArgs, public NativeWindowCharInfo, public Description<GuiCharEventArgs> { /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to null.</summary> GuiCharEventArgs() { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiCharEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; /// <summary>Mouse event arguments.</summary> struct GuiMouseEventArgs : public GuiEventArgs, public NativeWindowMouseInfo, public Description<GuiMouseEventArgs> { /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to null.</summary> GuiMouseEventArgs() { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiMouseEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) { } }; typedef GuiGraphicsEvent<GuiEventArgs> GuiNotifyEvent; typedef GuiGraphicsEvent<GuiRequestEventArgs> GuiRequestEvent; typedef GuiGraphicsEvent<GuiKeyEventArgs> GuiKeyEvent; typedef GuiGraphicsEvent<GuiCharEventArgs> GuiCharEvent; typedef GuiGraphicsEvent<GuiMouseEventArgs> GuiMouseEvent; /*********************************************************************** Predefined Item Events ***********************************************************************/ /// <summary>Item event arguments.</summary> struct GuiItemEventArgs : public GuiEventArgs, public Description<GuiItemEventArgs> { /// <summary>Item index.</summary> vint itemIndex; GuiItemEventArgs() :itemIndex(-1) { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiItemEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,itemIndex(-1) { } }; /// <summary>Item mouse event arguments.</summary> struct GuiItemMouseEventArgs : public GuiMouseEventArgs, public Description<GuiItemMouseEventArgs> { /// <summary>Item index.</summary> vint itemIndex; GuiItemMouseEventArgs() :itemIndex(-1) { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiItemMouseEventArgs(GuiGraphicsComposition* composition) :GuiMouseEventArgs(composition) ,itemIndex(-1) { } }; typedef GuiGraphicsEvent<GuiItemEventArgs> GuiItemNotifyEvent; typedef GuiGraphicsEvent<GuiItemMouseEventArgs> GuiItemMouseEvent; /*********************************************************************** Predefined Node Events ***********************************************************************/ /// <summary>Node event arguments.</summary> struct GuiNodeEventArgs : public GuiEventArgs, public Description<GuiNodeEventArgs> { /// <summary>Tree node.</summary> controls::tree::INodeProvider* node; GuiNodeEventArgs() :node(0) { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiNodeEventArgs(GuiGraphicsComposition* composition) :GuiEventArgs(composition) ,node(0) { } }; /// <summary>Node mouse event arguments.</summary> struct GuiNodeMouseEventArgs : public GuiMouseEventArgs, public Description<GuiNodeMouseEventArgs> { /// <summary>Tree node.</summary> controls::tree::INodeProvider* node; GuiNodeMouseEventArgs() :node(0) { } /// <summary>Create an event arguments with <see cref="compositionSource"/> and <see cref="eventSource"/> set to a specified value.</summary> /// <param name="composition">The speciied value to set <see cref="compositionSource"/> and <see cref="eventSource"/>.</param> GuiNodeMouseEventArgs(GuiGraphicsComposition* composition) :GuiMouseEventArgs(composition) ,node(0) { } }; typedef GuiGraphicsEvent<GuiNodeEventArgs> GuiNodeNotifyEvent; typedef GuiGraphicsEvent<GuiNodeMouseEventArgs> GuiNodeMouseEvent; /*********************************************************************** Event Receiver ***********************************************************************/ /// <summary> /// Contains all available user input events for a <see cref="GuiGraphicsComposition"/>. 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 <see cref="GuiEventArgs"/>) for the event will store the original event raiser composition. /// </summary> class GuiGraphicsEventReceiver : public Object { protected: GuiGraphicsComposition* sender; public: GuiGraphicsEventReceiver(GuiGraphicsComposition* _sender); ~GuiGraphicsEventReceiver(); GuiGraphicsComposition* GetAssociatedComposition(); /// <summary>Left mouse button down event.</summary> GuiMouseEvent leftButtonDown; /// <summary>Left mouse button up event.</summary> GuiMouseEvent leftButtonUp; /// <summary>Left mouse button double click event.</summary> GuiMouseEvent leftButtonDoubleClick; /// <summary>Middle mouse button down event.</summary> GuiMouseEvent middleButtonDown; /// <summary>Middle mouse button up event.</summary> GuiMouseEvent middleButtonUp; /// <summary>Middle mouse button double click event.</summary> GuiMouseEvent middleButtonDoubleClick; /// <summary>Right mouse button down event.</summary> GuiMouseEvent rightButtonDown; /// <summary>Right mouse button up event.</summary> GuiMouseEvent rightButtonUp; /// <summary>Right mouse button double click event.</summary> GuiMouseEvent rightButtonDoubleClick; /// <summary>Horizontal wheel scrolling event.</summary> GuiMouseEvent horizontalWheel; /// <summary>Vertical wheel scrolling event.</summary> GuiMouseEvent verticalWheel; /// <summary>Mouse move event.</summary> GuiMouseEvent mouseMove; /// <summary>Mouse enter event.</summary> GuiNotifyEvent mouseEnter; /// <summary>Mouse leave event.</summary> GuiNotifyEvent mouseLeave; /// <summary>Preview key event.</summary> GuiKeyEvent previewKey; /// <summary>Key down event.</summary> GuiKeyEvent keyDown; /// <summary>Key up event.</summary> GuiKeyEvent keyUp; /// <summary>System key down event.</summary> GuiKeyEvent systemKeyDown; /// <summary>System key up event.</summary> GuiKeyEvent systemKeyUp; /// <summary>Preview char input event.</summary> GuiCharEvent previewCharInput; /// <summary>Char input event.</summary> GuiCharEvent charInput; /// <summary>Got focus event.</summary> GuiNotifyEvent gotFocus; /// <summary>Lost focus event.</summary> GuiNotifyEvent lostFocus; /// <summary>Caret notify event. This event is raised when a caret graph need to change the visibility state.</summary> GuiNotifyEvent caretNotify; /// <summary>Clipboard notify event. This event is raised when the content in the system clipboard is changed.</summary> GuiNotifyEvent clipboardNotify; /// <summary>Render target changed event. This event is raised when the render target of this composition is changed.</summary> GuiNotifyEvent renderTargetChanged; }; } } /*********************************************************************** Workflow to C++ Codegen Helpers ***********************************************************************/ namespace __vwsn { template<typename T> struct EventHelper<presentation::compositions::GuiGraphicsEvent<T>> { using Event = presentation::compositions::GuiGraphicsEvent<T>; using Sender = presentation::compositions::GuiGraphicsComposition; using IGuiGraphicsEventHandler = presentation::compositions::IGuiGraphicsEventHandler; using Handler = Func<void(Sender*, T*)>; class EventHandlerImpl : public Object, public reflection::description::IEventHandler { public: Ptr<IGuiGraphicsEventHandler> handler; EventHandlerImpl(Ptr<IGuiGraphicsEventHandler> _handler) :handler(_handler) { } bool IsAttached()override { return handler->IsAttached(); } }; static Ptr<reflection::description::IEventHandler> Attach(Event& e, Handler handler) { return MakePtr<EventHandlerImpl>(e.AttachLambda([=](Sender* sender, T& args) { handler(sender, &args); })); } static bool Detach(Event& e, Ptr<reflection::description::IEventHandler> handler) { auto impl = handler.Cast<EventHandlerImpl>(); if (!impl) return false; return e.Detach(impl->handler); } static auto Invoke(Event& e) { return [&](Sender* sender, T* args) { e.ExecuteWithNewSender(*args, sender); }; } }; } } #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 ***********************************************************************/ /// <summary> /// This is a class for managing grpahics element factories and graphics renderer factories /// </summary> class GuiGraphicsResourceManager : public Object { typedef collections::Dictionary<WString, Ptr<IGuiGraphicsElementFactory>> elementFactoryMap; typedef collections::Dictionary<WString, Ptr<IGuiGraphicsRendererFactory>> rendererFactoryMap; protected: elementFactoryMap elementFactories; rendererFactoryMap rendererFactories; public: /// <summary> /// Create a graphics resource manager without any predefined factories /// </summary> GuiGraphicsResourceManager(); ~GuiGraphicsResourceManager(); /// <summary> /// Register a <see cref="IGuiGraphicsElementFactory"></see> using the element type from <see cref="IGuiGraphicsElementFactory::GetElementTypeName"></see>. /// </summary> /// <param name="factory">The instance of the graphics element factory to register.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool RegisterElementFactory(IGuiGraphicsElementFactory* factory); /// <summary> /// Register a <see cref="IGuiGraphicsRendererFactory"></see> and bind it to a registered <see cref="IGuiGraphicsElementFactory"></see>. /// </summary> /// <param name="elementTypeName">The element type to represent a graphics element factory.</param> /// <param name="factory">The instance of the graphics renderer factory to register.</param> /// <returns>Returns true if this operation succeeded.</returns> virtual bool RegisterRendererFactory(const WString& elementTypeName, IGuiGraphicsRendererFactory* factory); /// <summary> /// Get the instance of a registered <see cref="IGuiGraphicsElementFactory"></see> that is binded to a specified element type. /// </summary> /// <returns>Returns the element factory.</returns> /// <param name="elementTypeName">The element type to get a corresponding graphics element factory.</param> virtual IGuiGraphicsElementFactory* GetElementFactory(const WString& elementTypeName); /// <summary> /// Get the instance of a registered <see cref="IGuiGraphicsRendererFactory"></see> that is binded to a specified element type. /// </summary> /// <returns>Returns the renderer factory.</returns> /// <param name="elementTypeName">The element type to get a corresponding graphics renderer factory.</param> virtual IGuiGraphicsRendererFactory* GetRendererFactory(const WString& elementTypeName); /// <summary> /// Get the instance of a <see cref="IGuiGraphicsRenderTarget"></see> that is binded to an <see cref="INativeWindow"></see>. /// </summary> /// <param name="window">The specified window.</param> /// <returns>Returns the render target.</returns> virtual IGuiGraphicsRenderTarget* GetRenderTarget(INativeWindow* window)=0; /// <summary> /// Recreate the render target for the specified window. /// </summary> /// <param name="window">The specified window.</param> virtual void RecreateRenderTarget(INativeWindow* window) = 0; /// <summary> /// Resize the render target to fit the current window size. /// </summary> /// <param name="window">The specified window.</param> virtual void ResizeRenderTarget(INativeWindow* window) = 0; /// <summary> /// Get the renderer awared rich text document layout engine provider object. /// </summary> /// <returns>Returns the layout provider.</returns> virtual IGuiGraphicsLayoutProvider* GetLayoutProvider()=0; }; /// <summary> /// Get the current <see cref="GuiGraphicsResourceManager"></see>. /// </summary> /// <returns>Returns the current resource manager.</returns> extern GuiGraphicsResourceManager* GetGuiGraphicsResourceManager(); /// <summary> /// Set the current <see cref="GuiGraphicsResourceManager"></see>. /// </summary> /// <param name="resourceManager">The resource manager to set.</param> extern void SetGuiGraphicsResourceManager(GuiGraphicsResourceManager* resourceManager); /// <summary> /// Helper function to register a <see cref="IGuiGraphicsElementFactory"></see> with a <see cref="IGuiGraphicsRendererFactory"></see> and bind them together. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="elementFactory">The element factory to register.</param> /// <param name="rendererFactory">The renderer factory to register.</param> extern bool RegisterFactories(IGuiGraphicsElementFactory* elementFactory, IGuiGraphicsRendererFactory* rendererFactory); /*********************************************************************** Helpers ***********************************************************************/ template<typename TElement> class GuiElementBase : public Object, public IGuiGraphicsElement, public Description<TElement> { public: class Factory : public Object, public IGuiGraphicsElementFactory { public: WString GetElementTypeName() { return TElement::GetElementTypeName(); } IGuiGraphicsElement* Create() { auto element = new TElement; element->factory = this; IGuiGraphicsRendererFactory* rendererFactory = GetGuiGraphicsResourceManager()->GetRendererFactory(GetElementTypeName()); if (rendererFactory) { element->renderer = rendererFactory->Create(); element->renderer->Initialize(element); } return element; } }; protected: IGuiGraphicsElementFactory* factory = nullptr; Ptr<IGuiGraphicsRenderer> 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 factory = GetGuiGraphicsResourceManager()->GetElementFactory(TElement::GetElementTypeName()); CHECK_ERROR(factory != nullptr, L"This element is not supported by the selected renderer."); return dynamic_cast<TElement*>(factory->Create()); } ~GuiElementBase() { if (renderer) { renderer->Finalize(); } } IGuiGraphicsElementFactory* GetFactory()override { return factory; } IGuiGraphicsRenderer* GetRenderer()override { return renderer.Obj(); } compositions::GuiGraphicsComposition* GetOwnerComposition()override { return ownerComposition; } }; #define DEFINE_GUI_GRAPHICS_ELEMENT(TELEMENT, ELEMENT_TYPE_NAME)\ friend class GuiElementBase<TELEMENT>;\ public:\ static WString GetElementTypeName()\ {\ return ELEMENT_TYPE_NAME;\ }\ #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()\ {\ RegisterFactories(new TELEMENT::Factory, new TRENDERER::Factory);\ }\ IGuiGraphicsRendererFactory* GetFactory()override\ {\ return factory;\ }\ void Initialize(IGuiGraphicsElement* _element)override\ {\ element=dynamic_cast<TELEMENT*>(_element);\ InitializeInternal();\ }\ void Finalize()override\ {\ FinalizeInternal();\ }\ void SetRenderTarget(IGuiGraphicsRenderTarget* _renderTarget)override\ {\ TTARGET* oldRenderTarget=renderTarget;\ renderTarget=dynamic_cast<TTARGET*>(_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<TKEY, Package> aliveResources;\ List<DeadPackage> 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;i<deadResources.Count();i++)\ {\ if(deadResources[i].key==key)\ {\ DeadPackage deadPackage=deadResources[i];\ deadResources.RemoveAt(i);\ resource=deadPackage.value;\ break;\ }\ }\ if(!resource)\ {\ resource=CreateInternal(key);\ }\ Package package;\ package.resource=resource;\ package.counter=1;\ aliveResources.Add(key, package);\ return package.resource;\ }\ void Destroy(const TKEY& key)\ {\ vint index=aliveResources.Keys().IndexOf(key);\ if(index!=-1)\ {\ Package package=aliveResources.Values().Get(index);\ package.counter--;\ if(package.counter==0)\ {\ aliveResources.Remove(key);\ if(deadResources.Count()==DeadPackageMax)\ {\ deadResources.RemoveAt(DeadPackageMax-1);\ }\ DeadPackage deadPackage;\ deadPackage.key=key;\ deadPackage.value=package.resource;\ deadResources.Insert(0, deadPackage);\ }\ else\ {\ aliveResources.Set(key, package);\ }\ }\ } } } } #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 { using namespace reflection; class GuiResourceItem; class GuiResourceFolder; class GuiResource; /*********************************************************************** Helper Functions ***********************************************************************/ /// <summary>Get the folder path from a file path. The result folder path is ended with a separator.</summary> /// <returns>The folder path.</returns> /// <param name="filePath">The file path.</param> extern WString GetFolderPath(const WString& filePath); /// <summary>Get the file name from a file path.</summary> /// <returns>The file name.</returns> /// <param name="filePath">The file path.</param> extern WString GetFileName(const WString& filePath); /// <summary>Load a text file.</summary> /// <returns>Returns true if the operation succeeded.</returns> /// <param name="filePath">The text file path.</param> /// <param name="text">The text file content, if succeeded.</param> extern bool LoadTextFile(const WString& filePath, WString& text); /// <summary>Test is a text a resource url and extract the protocol and the path.</summary> /// <returns>Returns true if the text is a resource url.</returns> /// <param name="text">The text.</param> /// <param name="protocol">The extracted protocol.</param> /// <param name="path">The extracted path.</param> extern bool IsResourceUrl(const WString& text, WString& protocol, WString& path); extern void HexToBinary(stream::IStream& stream, const WString& hexText); extern WString BinaryToHex(stream::IStream& stream); /*********************************************************************** 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: static vint Compare(GlobalStringKey a, GlobalStringKey b){ return a.key - b.key; } bool operator==(GlobalStringKey g)const{ return key == g.key; } bool operator!=(GlobalStringKey g)const{ return key != g.key; } bool operator<(GlobalStringKey g)const{ return key < g.key; } bool operator<=(GlobalStringKey g)const{ return key <= g.key; } bool operator>(GlobalStringKey g)const{ return key > g.key; } bool operator>=(GlobalStringKey g)const{ return key >= g.key; } static GlobalStringKey Get(const WString& string); vint ToKey()const; WString ToString()const; }; /*********************************************************************** Resource Image ***********************************************************************/ /// <summary> /// Represnets an image to display. /// </summary> class GuiImageData : public Object, public Description<GuiImageData> { protected: Ptr<INativeImage> image; vint frameIndex; public: /// <summary>Create an empty image data.</summary> GuiImageData(); /// <summary>Create an image data with a specified image and a frame index.</summary> /// <param name="_image">The specified image.</param> /// <param name="_frameIndex">The specified frame index.</param> GuiImageData(Ptr<INativeImage> _image, vint _frameIndex); ~GuiImageData(); /// <summary>Get the specified image.</summary> /// <returns>The specified image.</returns> Ptr<INativeImage> GetImage(); /// <summary>Get the specified frame index.</summary> /// <returns>The specified frame index.</returns> vint GetFrameIndex(); }; /*********************************************************************** Resource String ***********************************************************************/ /// <summary>Represents a text resource.</summary> class GuiTextData : public Object, public Description<GuiTextData> { protected: WString text; public: /// <summary>Create an empty text data.</summary> GuiTextData(); /// <summary>Create a text data with a specified text.</summary> /// <param name="_text">The specified text.</param> GuiTextData(const WString& _text); /// <summary>Get the specified text.</summary> /// <returns>The specified text.</returns> WString GetText(); }; /*********************************************************************** Resource Structure ***********************************************************************/ /// <summary>Resource node base.</summary> class GuiResourceNodeBase : public Object, public Description<GuiResourceNodeBase> { friend class GuiResourceFolder; protected: GuiResourceFolder* parent; WString name; WString fileContentPath; WString fileAbsolutePath; public: GuiResourceNodeBase(); ~GuiResourceNodeBase(); /// <summary>Get the containing folder. Returns null means that this is the root resource node.</summary> /// <returns>The containing folder.</returns> GuiResourceFolder* GetParent(); /// <summary>Get the name of this resource node.</summary> /// <returns>The name of this resource node .</returns> const WString& GetName(); /// <summary>Get the resource path of this resource node</summary> /// <returns>The resource path of this resource node .</returns> WString GetResourcePath(); /// <summary>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.</summary> /// <returns>The file content path of this resource node .</returns> const WString& GetFileContentPath(); /// <summary>Get the absolute file content path of this resource node. This path points to an existing file containing the content.</summary> /// <returns>The file absolute path of this resource node .</returns> const WString& GetFileAbsolutePath(); /// <summary>Set the file content path of this resource node.</summary> /// <param name="content">The file content path of this resource node .</param> /// <param name="absolute">The file absolute path of this resource node .</param> 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<GuiResourceNodeBase> 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 = parsing::ParsingTextPos::UnknownValue; vint column = parsing::ParsingTextPos::UnknownValue; GuiResourceTextPos() = default; GuiResourceTextPos(GuiResourceLocation location, parsing::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<GuiResourceError>; 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<Ptr<parsing::ParsingError>>& parsingErrors); static void Transform(GuiResourceLocation _location, GuiResourceError::List& errors, collections::List<Ptr<parsing::ParsingError>>& parsingErrors, parsing::ParsingTextPos offset); static void Transform(GuiResourceLocation _location, GuiResourceError::List& errors, collections::List<Ptr<parsing::ParsingError>>& parsingErrors, GuiResourceTextPos offset); static void SortAndLog(List& errors, collections::List<WString>& output, const WString& workingDirectory = WString::Empty); }; class DocumentModel; class GuiResourcePathResolver; struct GuiResourcePrecompileContext; struct GuiResourceInitializeContext; class IGuiResourcePrecompileCallback; /// <summary>Resource item.</summary> class GuiResourceItem : public GuiResourceNodeBase, public Description<GuiResourceItem> { friend class GuiResourceFolder; protected: Ptr<DescriptableObject> content; WString typeName; public: /// <summary>Create a resource item.</summary> GuiResourceItem(); ~GuiResourceItem(); /// <summary>Get the type of this resource item.</summary> /// <returns>The type name.</returns> const WString& GetTypeName(); /// <summary>Get the contained object for this resource item.</summary> /// <returns>The contained object.</returns> Ptr<DescriptableObject> GetContent(); /// <summary>Set the containd object for this resource item.</summary> /// <param name="_typeName">The type name of this contained object.</param> /// <param name="value">The contained object.</param> void SetContent(const WString& _typeName, Ptr<DescriptableObject> value); /// <summary>Get the contained object as an image.</summary> /// <returns>The contained object.</returns> Ptr<GuiImageData> AsImage(); /// <summary>Get the contained object as an xml.</summary> /// <returns>The contained object.</returns> Ptr<parsing::xml::XmlDocument> AsXml(); /// <summary>Get the contained object as a string.</summary> /// <returns>The contained object.</returns> Ptr<GuiTextData> AsString(); /// <summary>Get the contained object as a document model.</summary> /// <returns>The contained object.</returns> Ptr<DocumentModel> AsDocument(); }; /// <summary>Resource folder. A resource folder contains many sub folders and sub items.</summary> class GuiResourceFolder : public GuiResourceNodeBase, public Description<GuiResourceFolder> { protected: typedef collections::Dictionary<WString, Ptr<GuiResourceItem>> ItemMap; typedef collections::Dictionary<WString, Ptr<GuiResourceFolder>> FolderMap; typedef collections::List<Ptr<GuiResourceItem>> ItemList; typedef collections::List<Ptr<GuiResourceFolder>> FolderList; struct DelayLoading { WString type; WString workingDirectory; Ptr<GuiResourceItem> preloadResource; }; typedef collections::List<DelayLoading> DelayLoadingList; WString importUri; ItemMap items; FolderMap folders; void LoadResourceFolderFromXml(DelayLoadingList& delayLoadings, const WString& containingFolder, Ptr<parsing::xml::XmlElement> folderXml, GuiResourceError::List& errors); void SaveResourceFolderToXml(Ptr<parsing::xml::XmlElement> xmlParent); void CollectTypeNames(collections::List<WString>& typeNames); void LoadResourceFolderFromBinary(DelayLoadingList& delayLoadings, stream::internal::ContextFreeReader& reader, collections::List<WString>& typeNames, GuiResourceError::List& errors); void SaveResourceFolderToBinary(stream::internal::ContextFreeWriter& writer, collections::List<WString>& typeNames); void PrecompileResourceFolder(GuiResourcePrecompileContext& context, IGuiResourcePrecompileCallback* callback, GuiResourceError::List& errors); void InitializeResourceFolder(GuiResourceInitializeContext& context); void ImportFromUri(const WString& uri, GuiResourceTextPos position, GuiResourceError::List& errors); public: /// <summary>Create a resource folder.</summary> GuiResourceFolder(); ~GuiResourceFolder(); ///<summary>Get the import uri for this folder.</summary> ///<returns>The import uri for this folder. Returns an empty string for non-import folders</returns> const WString& GetImportUri(); ///<summary>Set the import uri for this folder.</summary> ///<param name="uri">The import uri for this folder. Set an empty string for non-import folders</param> void SetImportUri(const WString& uri); /// <summary>Get all sub items.</summary> /// <returns>All sub items.</returns> const ItemList& GetItems(); /// <summary>Get the item of a specified name.</summary> /// <returns>The item of a specified name.</returns> /// <param name="name">The specified name.</param> Ptr<GuiResourceItem> GetItem(const WString& name); /// <summary>Add a resource item.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="name">The name of this resource item.</param> /// <param name="item">The resource item.</param> bool AddItem(const WString& name, Ptr<GuiResourceItem> item); /// <summary>Remove a resource item of a specified name.</summary> /// <returns>Returns the removed resource item if this operation succeeded.</returns> /// <param name="name">The name of this resource item.</param> Ptr<GuiResourceItem> RemoveItem(const WString& name); /// <summary>Remove all resource item.</summary> void ClearItems(); /// <summary>Get all sub folders.</summary> /// <returns>All sub folders.</returns> const FolderList& GetFolders(); /// <summary>Get the folder of a specified name.</summary> /// <returns>The folder of a specified name.</returns> /// <param name="name">The specified name.</param> Ptr<GuiResourceFolder> GetFolder(const WString& name); /// <summary>Add a resource folder.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="name">The name of this resource folder.</param> /// <param name="folder">The resource folder.</param> bool AddFolder(const WString& name, Ptr<GuiResourceFolder> folder); /// <summary>Remove a resource folder of a specified name.</summary> /// <returns>Returns the removed resource folder if this operation succeeded.</returns> /// <param name="name">The name of this resource folder.</param> Ptr<GuiResourceFolder> RemoveFolder(const WString& name); /// <summary>Remove all resource folders.</summary> void ClearFolders(); /// <summary>Get a contained resource object using a path like "Packages\Application\Name".</summary> /// <returns>The containd resource object.</returns> /// <param name="path">The path.</param> Ptr<DescriptableObject> GetValueByPath(const WString& path); /// <summary>Get a resource folder using a path like "Packages\Application\Name\".</summary> /// <returns>The resource folder.</returns> /// <param name="path">The path.</param> Ptr<GuiResourceFolder> GetFolderByPath(const WString& path); /// <summary>Create a contained resource object using a path like "Packages\Application\Name".</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="path">The path.</param> /// <param name="typeName">The type name of this contained object.</param> /// <param name="value">The contained object.</param> bool CreateValueByPath(const WString& path, const WString& typeName, Ptr<DescriptableObject> value); }; /*********************************************************************** Resource ***********************************************************************/ enum class GuiResourceUsage { DataOnly, InstanceClass, }; /// <summary>Resource metadata.</summary> class GuiResourceMetadata : public Object { public: WString name; WString version; collections::List<WString> dependencies; void LoadFromXml(Ptr<parsing::xml::XmlDocument> xml, GuiResourceLocation location, GuiResourceError::List& errors); Ptr<parsing::xml::XmlDocument> SaveToXml(); }; /// <summary>Resource. A resource is a root resource folder that does not have a name.</summary> class GuiResource : public GuiResourceFolder, public Description<GuiResource> { protected: WString workingDirectory; Ptr<GuiResourceMetadata> metadata; static void ProcessDelayLoading(Ptr<GuiResource> resource, DelayLoadingList& delayLoadings, GuiResourceError::List& errors); public: static const wchar_t* CurrentVersionString; /// <summary>Create a resource.</summary> GuiResource(); ~GuiResource(); /// <summary>Get the metadata of the resource.</summary> /// <returns>The metadata.</returns> Ptr<GuiResourceMetadata> GetMetadata(); /// <summary>Get the directory where the resource is load.</summary> /// <returns>The directory.</returns> WString GetWorkingDirectory(); /// <summary>Load a resource from an xml file. If the xml file refers other files, they will be loaded as well.</summary> /// <returns>The loaded resource.</returns> /// <param name="xml">The xml document.</param> /// <param name="filePath">The file path of the resource.</param> /// <param name="workingDirectory">The working directory for loading external resources.</param> /// <param name="errors">All collected errors during loading a resource.</param> static Ptr<GuiResource> LoadFromXml(Ptr<parsing::xml::XmlDocument> xml, const WString& filePath, const WString& workingDirectory, GuiResourceError::List& errors); /// <summary>Load a resource from an xml file. If the xml file refers other files, they will be loaded as well.</summary> /// <returns>The loaded resource.</returns> /// <param name="filePath">The file path of the xml file.</param> /// <param name="errors">All collected errors during loading a resource.</param> static Ptr<GuiResource> LoadFromXml(const WString& filePath, GuiResourceError::List& errors); /// <summary>Save the resource to xml.</summary> /// <returns>The xml.</returns> Ptr<parsing::xml::XmlDocument> SaveToXml(); /// <summary>Load a precompiled resource from a stream.</summary> /// <returns>The loaded resource.</returns> /// <param name="stream">The stream.</param> /// <param name="errors">All collected errors during loading a resource.</param> static Ptr<GuiResource> LoadPrecompiledBinary(stream::IStream& stream, GuiResourceError::List& errors); /// <summary>Load a precompiled resource from a stream. This function will hit an assert if there are errors.</summary> /// <returns>The loaded resource.</returns> /// <param name="stream">The stream.</param> static Ptr<GuiResource> LoadPrecompiledBinary(stream::IStream& stream); /// <summary>Save the precompiled resource to a stream.</summary> /// <param name="stream">The stream.</param> void SavePrecompiledBinary(stream::IStream& stream); /// <summary>Precompile this resource to improve performance.</summary> /// <returns>The resource folder contains all precompiled result. The folder will be added to the resource if there is no error.</returns> /// <param name="callback">A callback to receive progress.</param> /// <param name="errors">All collected errors during precompiling a resource.</param> Ptr<GuiResourceFolder> Precompile(IGuiResourcePrecompileCallback* callback, GuiResourceError::List& errors); /// <summary>Initialize a precompiled resource.</summary> /// <param name="usage">In which role an application is initializing this resource.</param> void Initialize(GuiResourceUsage usage); /// <summary>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.</summary> /// <returns>The containd resource object.</returns> /// <param name="path">The path.</param> Ptr<DocumentModel> GetDocumentByPath(const WString& path); /// <summary>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.</summary> /// <returns>The containd resource object.</returns> /// <param name="path">The path.</param> Ptr<GuiImageData> GetImageByPath(const WString& path); /// <summary>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.</summary> /// <returns>The containd resource object.</returns> /// <param name="path">The path.</param> Ptr<parsing::xml::XmlDocument> GetXmlByPath(const WString& path); /// <summary>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.</summary> /// <returns>The containd resource object.</returns> /// <param name="path">The path.</param> WString GetStringByPath(const WString& path); }; /*********************************************************************** Resource Path Resolver ***********************************************************************/ /// <summary>Represents a symbol resolver for loading a resource of a certain protocol.</summary> class IGuiResourcePathResolver : public IDescriptable, public Description<IGuiResourcePathResolver> { public: /// <summary>Load a resource when the descriptor is something like a protocol-prefixed uri.</summary> /// <returns>The loaded resource. Returns null if failed to load.</returns> /// <param name="path">The path.</param> virtual Ptr<DescriptableObject> ResolveResource(const WString& path)=0; }; /// <summary>Represents an <see cref="IGuiResourcePathResolver"/> factory.</summary> class IGuiResourcePathResolverFactory : public IDescriptable, public Description<IGuiResourcePathResolverFactory> { public: /// <summary>Get the protocol for this resolver.</summary> /// <returns>The protocol.</returns> virtual WString GetProtocol()=0; /// <summary>Create an <see cref="IGuiResourcePathResolver"/> object.</summary> /// <returns>The created resolver.</returns> /// <param name="resource">The resource context.</param> /// <param name="workingDirectory">The working directory context.</param> virtual Ptr<IGuiResourcePathResolver> CreateResolver(Ptr<GuiResource> resource, const WString& workingDirectory)=0; }; /// <summary>Represents a symbol resolver for loading a resource.</summary> class GuiResourcePathResolver : public Object, public Description<GuiResourcePathResolver> { typedef collections::Dictionary<WString, Ptr<IGuiResourcePathResolver>> ResolverMap; protected: ResolverMap resolvers; Ptr<GuiResource> resource; WString workingDirectory; public: /// <summary>Create a resolver.</summary> /// <param name="_resource">The resource context.</param> /// <param name="_workingDirectory">The working directory context.</param> GuiResourcePathResolver(Ptr<GuiResource> _resource, const WString& _workingDirectory); ~GuiResourcePathResolver(); /// <summary>Load a resource when the descriptor is something like a protocol-prefixed uri.</summary> /// <returns>The loaded resource. Returns null if failed to load.</returns> /// <param name="protocol">The protocol.</param> /// <param name="path">The path.</param> Ptr<DescriptableObject> 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; /// <summary>Represents a symbol type for loading a resource.</summary> class IGuiResourceTypeResolver : public virtual IDescriptable, public Description<IGuiResourceTypeResolver> { public: /// <summary>Get the type of the resource that load by this resolver.</summary> /// <returns>The type.</returns> virtual WString GetType() = 0; /// <summary>Test is this resource able to serialize in an XML resource or not.</summary> /// <returns>Returns true if this resource is able to serialize in an XML resource.</returns> virtual bool XmlSerializable() = 0; /// <summary>Test is this resource able to serialize in a precompiled binary resource or not.</summary> /// <returns>Returns true if this resource is able to serialize in a precompiled binary resource.</returns> virtual bool StreamSerializable() = 0; /// <summary>Get the precompiler for the type resolver.</summary> /// <returns>Returns null if the type resolve does not support precompiling.</returns> virtual IGuiResourceTypeResolver_Precompile* Precompile(){ return 0; } /// <summary>Get the initializer for the type resolver.</summary> /// <returns>Returns null if the type resolve does not support initializing.</returns> virtual IGuiResourceTypeResolver_Initialize* Initialize(){ return 0; } /// <summary>Get the object for convert the resource between xml and object.</summary> /// <returns>Returns null if the type resolver does not have this ability.</returns> virtual IGuiResourceTypeResolver_DirectLoadXml* DirectLoadXml(){ return 0; } /// <summary>Get the object for convert the resource between stream and object.</summary> /// <returns>Returns null if the type resolver does not have this ability.</returns> virtual IGuiResourceTypeResolver_DirectLoadStream* DirectLoadStream(){ return 0; } /// <summary>Get the object for convert the resource between the preload type and the current type.</summary> /// <returns>Returns null if the type resolver does not have this ability.</returns> virtual IGuiResourceTypeResolver_IndirectLoad* IndirectLoad(){ return 0; } }; /// <summary>Provide a context for resource precompiling</summary> struct GuiResourcePrecompileContext { typedef collections::Dictionary<Ptr<DescriptableObject>, Ptr<DescriptableObject>> PropertyMap; /// <summary>Progress callback.</summary> workflow::IWfCompilerCallback* compilerCallback = nullptr; /// <summary>The folder to contain compiled objects.</summary> Ptr<GuiResourceFolder> targetFolder; /// <summary>The root resource object.</summary> GuiResource* rootResource = nullptr; /// <summary>Indicate the pass index of this precompiling pass.</summary> vint passIndex = -1; /// <summary>The path resolver. This is only for delay load resource.</summary> Ptr<GuiResourcePathResolver> resolver; /// <summary>Additional properties for resource item contents</summary> PropertyMap additionalProperties; }; /// <summary> /// 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 /// </summary> class IGuiResourceTypeResolver_Precompile : public virtual IDescriptable, public Description<IGuiResourceTypeResolver_Precompile> { 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, }; /// <summary>Get the maximum pass index that the precompiler needs.</summary> /// <returns>Returns the maximum pass index. The precompiler doesn't not need to response to every pass.</returns> virtual vint GetMaxPassIndex() = 0; /// <summary>Get how this resolver supports precompiling.</summary> /// <param name="passIndex">The pass index.</param> /// <returns>Returns how this resolver supports precompiling.</returns> virtual PassSupport GetPassSupport(vint passIndex) = 0; /// <summary>Precompile the resource item.</summary> /// <param name="resource">The resource to precompile.</param> /// <param name="context">The context for precompiling.</param> /// <param name="errors">All collected errors during loading a resource.</param> virtual void PerResourcePrecompile(Ptr<GuiResourceItem> resource, GuiResourcePrecompileContext& context, GuiResourceError::List& errors) = 0; /// <summary>Precompile for a pass.</summary> /// <param name="context">The context for precompiling.</param> /// <param name="errors">All collected errors during loading a resource.</param> virtual void PerPassPrecompile(GuiResourcePrecompileContext& context, GuiResourceError::List& errors) = 0; }; class IGuiResourcePrecompileCallback : public virtual IDescriptable, public Description<IGuiResourcePrecompileCallback> { public: virtual workflow::IWfCompilerCallback* GetCompilerCallback() = 0; virtual void OnPerPass(vint passIndex) = 0; virtual void OnPerResource(vint passIndex, Ptr<GuiResourceItem> resource) = 0; }; /// <summary>Provide a context for resource initializing</summary> struct GuiResourceInitializeContext : GuiResourcePrecompileContext { GuiResourceUsage usage; }; /// <summary> /// 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) /// </summary> class IGuiResourceTypeResolver_Initialize : public virtual IDescriptable, public Description<IGuiResourceTypeResolver_Initialize> { public: /// <summary>Get the maximum pass index that the initializer needs.</summary> /// <returns>Returns the maximum pass index. The initializer doesn't not need to response to every pass.</returns> virtual vint GetMaxPassIndex() = 0; /// <summary>Initialize the resource item.</summary> /// <param name="resource">The resource to initializer.</param> /// <param name="context">The context for initializing.</param> virtual void Initialize(Ptr<GuiResourceItem> resource, GuiResourceInitializeContext& context) = 0; }; /// <summary>Represents a symbol type for loading a resource without a preload type.</summary> class IGuiResourceTypeResolver_DirectLoadXml : public virtual IDescriptable, public Description<IGuiResourceTypeResolver_DirectLoadXml> { public: /// <summary>Serialize a resource to an xml element. This function is called if this type resolver does not have a preload type.</summary> /// <returns>The serialized xml element.</returns> /// <param name="resource">The resource item containing the resource.</param> /// <param name="content">The object to serialize.</param> virtual Ptr<parsing::xml::XmlElement> Serialize(Ptr<GuiResourceItem> resource, Ptr<DescriptableObject> content) = 0; /// <summary>Load a resource for a type inside an xml element.</summary> /// <returns>The resource.</returns> /// <param name="resource">The resource item containing the resource.</param> /// <param name="element">The xml element.</param> /// <param name="errors">All collected errors during loading a resource.</param> virtual Ptr<DescriptableObject> ResolveResource(Ptr<GuiResourceItem> resource, Ptr<parsing::xml::XmlElement> element, GuiResourceError::List& errors) = 0; /// <summary>Load a resource for a type from a file.</summary> /// <returns>The resource.</returns> /// <param name="resource">The resource item containing the resource.</param> /// <param name="path">The file path.</param> /// <param name="errors">All collected errors during loading a resource.</param> virtual Ptr<DescriptableObject> ResolveResource(Ptr<GuiResourceItem> resource, const WString& path, GuiResourceError::List& errors) = 0; }; /// <summary>Represents a symbol type for loading a resource without a preload type.</summary> class IGuiResourceTypeResolver_DirectLoadStream : public virtual IDescriptable, public Description<IGuiResourceTypeResolver_DirectLoadStream> { public: /// <summary>Serialize a precompiled resource to a stream.</summary> /// <param name="resource">The resource item containing the resource.</param> /// <param name="content">The content to serialize.</param> /// <param name="stream">The stream.</param> virtual void SerializePrecompiled(Ptr<GuiResourceItem> resource, Ptr<DescriptableObject> content, stream::IStream& stream) = 0; /// <summary>Load a precompiled resource from a stream.</summary> /// <returns>The resource.</returns> /// <param name="resource">The resource item containing the resource.</param> /// <param name="stream">The stream.</param> /// <param name="errors">All collected errors during loading a resource.</param> virtual Ptr<DescriptableObject> ResolveResourcePrecompiled(Ptr<GuiResourceItem> resource, stream::IStream& stream, GuiResourceError::List& errors) = 0; }; /// <summary>Represents a symbol type for loading a resource with a preload type.</summary> class IGuiResourceTypeResolver_IndirectLoad : public virtual IDescriptable, public Description<IGuiResourceTypeResolver_IndirectLoad> { public: /// <summary>Get the preload type to load the resource before loading itself.</summary> /// <returns>The preload type. Returns an empty string to indicate that there is no preload type for this resolver.</returns> virtual WString GetPreloadType() = 0; /// <summary>Get the delay load feature for this resolver.</summary> /// <returns>Returns true if this type need to delay load.</returns> virtual bool IsDelayLoad() = 0; /// <summary>Serialize a resource to a resource in preload type.</summary> /// <returns>The serialized resource.</returns> /// <param name="resource">The resource item containing the resource.</param> /// <param name="content">The object to serialize.</param> virtual Ptr<DescriptableObject> Serialize(Ptr<GuiResourceItem> resource, Ptr<DescriptableObject> content) = 0; /// <summary>Load a resource for a type from a resource loaded by the preload type resolver.</summary> /// <returns>The resource.</returns> /// <param name="resource">The resource item containing the resource.</param> /// <param name="resolver">The path resolver. This is only for delay load resource.</param> /// <param name="errors">All collected errors during loading a resource.</param> virtual Ptr<DescriptableObject> ResolveResource(Ptr<GuiResourceItem> resource, Ptr<GuiResourcePathResolver> resolver, GuiResourceError::List& errors) = 0; }; /*********************************************************************** Resource Resolver Manager ***********************************************************************/ /// <summary>A resource resolver manager.</summary> class IGuiResourceResolverManager : public IDescriptable, public Description<IGuiResourceResolverManager> { public: /// <summary>Get the <see cref="IGuiResourcePathResolverFactory"/> for a protocol.</summary> /// <returns>The factory.</returns> /// <param name="protocol">The protocol.</param> virtual IGuiResourcePathResolverFactory* GetPathResolverFactory(const WString& protocol) = 0; /// <summary>Set the <see cref="IGuiResourcePathResolverFactory"/> for a protocol.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="factory">The factory.</param> virtual bool SetPathResolverFactory(Ptr<IGuiResourcePathResolverFactory> factory) = 0; /// <summary>Get the <see cref="IGuiResourceTypeResolver"/> for a resource type.</summary> /// <returns>The resolver.</returns> /// <param name="type">The resource type.</param> virtual IGuiResourceTypeResolver* GetTypeResolver(const WString& type) = 0; /// <summary>Set the <see cref="IGuiResourceTypeResolver"/> for a resource type.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="resolver">The resolver.</param> virtual bool SetTypeResolver(Ptr<IGuiResourceTypeResolver> resolver) = 0; /// <summary>Get the maximum precompiling pass index.</summary> /// <returns>The maximum precompiling pass index.</returns> virtual vint GetMaxPrecompilePassIndex() = 0; /// <summary>Get the maximum initializing pass index.</summary> /// <returns>The maximum initializing pass index.</returns> virtual vint GetMaxInitializePassIndex() = 0; /// <summary>Get names of all per resource resolvers for a pass.</summary> /// <param name="passIndex">The pass index.</param> /// <param name="names">Names of resolvers</param> virtual void GetPerResourceResolverNames(vint passIndex, collections::List<WString>& names) = 0; /// <summary>Get names of all per pass resolvers for a pass.</summary> /// <param name="passIndex">The pass index.</param> /// <param name="names">Names of resolvers</param> virtual void GetPerPassResolverNames(vint passIndex, collections::List<WString>& names) = 0; }; extern IGuiResourceResolverManager* GetResourceResolverManager(); extern void DecompressStream(const char** buffer, bool compress, vint rows, vint block, vint remain, stream::IStream& outputStream); } } #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 { using namespace reflection; 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; } }; /// <summary>Represents a text style.</summary> class DocumentStyleProperties : public Object, public Description<DocumentStyleProperties> { public: /// <summary>Font face.</summary> Nullable<WString> face; /// <summary>Font size.</summary> Nullable<DocumentFontSize> size; /// <summary>Font color.</summary> Nullable<Color> color; /// <summary>Font color.</summary> Nullable<Color> backgroundColor; /// <summary>Bold.</summary> Nullable<bool> bold; /// <summary>Italic.</summary> Nullable<bool> italic; /// <summary>Underline.</summary> Nullable<bool> underline; /// <summary>Strikeline.</summary> Nullable<bool> strikeline; /// <summary>Antialias.</summary> Nullable<bool> antialias; /// <summary>Vertical antialias.</summary> Nullable<bool> verticalAntialias; }; /*********************************************************************** Rich Content Document (run) ***********************************************************************/ /// <summary>Pepresents a logical run of a rich content document.</summary> class DocumentRun : public Object, public Description<DocumentRun> { public: /// <summary>A visitor interface for <see cref="DocumentRun"/>.</summary> class IVisitor : public Interface { public: /// <summary>Visit operation for <see cref="DocumentTextRun"/>.</summary> /// <param name="run">The run object.</param> virtual void Visit(DocumentTextRun* run)=0; /// <summary>Visit operation for <see cref="DocumentStylePropertiesRun"/>.</summary> /// <param name="run">The run object.</param> virtual void Visit(DocumentStylePropertiesRun* run)=0; /// <summary>Visit operation for <see cref="DocumentStyleApplicationRun"/>.</summary> /// <param name="run">The run object.</param> virtual void Visit(DocumentStyleApplicationRun* run)=0; /// <summary>Visit operation for <see cref="DocumentHyperlinkRun"/>.</summary> /// <param name="run">The run object.</param> virtual void Visit(DocumentHyperlinkRun* run)=0; /// <summary>Visit operation for <see cref="DocumentImageRun"/>.</summary> /// <param name="run">The run object.</param> virtual void Visit(DocumentImageRun* run)=0; /// <summary>Visit operation for <see cref="DocumentEmbeddedObjectRun"/>.</summary> /// <param name="run">The run object.</param> virtual void Visit(DocumentEmbeddedObjectRun* run)=0; /// <summary>Visit operation for <see cref="DocumentParagraphRun"/>.</summary> /// <param name="run">The run object.</param> virtual void Visit(DocumentParagraphRun* run)=0; }; DocumentRun(){} /// <summary>Accept a <see cref="IVisitor"/> and trigger the selected visit operation.</summary> /// <param name="visitor">The visitor.</param> virtual void Accept(IVisitor* visitor)=0; }; /// <summary>Pepresents a container run.</summary> class DocumentContainerRun : public DocumentRun, public Description<DocumentContainerRun> { typedef collections::List<Ptr<DocumentRun>> RunList; public: /// <summary>Sub runs.</summary> RunList runs; }; /// <summary>Pepresents a content run.</summary> class DocumentContentRun : public DocumentRun, public Description<DocumentContentRun> { public: /// <summary>Get representation text.</summary> /// <returns>The representation text.</returns> virtual WString GetRepresentationText()=0; }; //------------------------------------------------------------------------- /// <summary>Pepresents a text run.</summary> class DocumentTextRun : public DocumentContentRun, public Description<DocumentTextRun> { public: /// <summary>Run text.</summary> WString text; DocumentTextRun(){} WString GetRepresentationText()override{return text;} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// <summary>Pepresents a inline object run.</summary> class DocumentInlineObjectRun : public DocumentContentRun, public Description<DocumentInlineObjectRun> { public: /// <summary>Size of the inline object.</summary> Size size; /// <summary>Baseline of the inline object.</summary> vint baseline; DocumentInlineObjectRun():baseline(-1){} }; /// <summary>Pepresents a image run.</summary> class DocumentImageRun : public DocumentInlineObjectRun, public Description<DocumentImageRun> { public: static const wchar_t* RepresentationText; /// <summary>The image.</summary> Ptr<INativeImage> image; /// <summary>The frame index.</summary> vint frameIndex; /// <summary>The image source string.</summary> WString source; DocumentImageRun():frameIndex(0){} WString GetRepresentationText()override{return RepresentationText;} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// <summary>Pepresents an embedded object run.</summary> class DocumentEmbeddedObjectRun : public DocumentInlineObjectRun, public Description<DocumentImageRun> { public: static const wchar_t* RepresentationText; /// <summary>The object name.</summary> WString name; WString GetRepresentationText()override{return RepresentationText;} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; //------------------------------------------------------------------------- /// <summary>Pepresents a style properties run.</summary> class DocumentStylePropertiesRun : public DocumentContainerRun, public Description<DocumentStylePropertiesRun> { public: /// <summary>Style properties.</summary> Ptr<DocumentStyleProperties> style; DocumentStylePropertiesRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// <summary>Pepresents a style application run.</summary> class DocumentStyleApplicationRun : public DocumentContainerRun, public Description<DocumentStyleApplicationRun> { public: /// <summary>Style name.</summary> WString styleName; DocumentStyleApplicationRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// <summary>Pepresents a hyperlink text run.</summary> class DocumentHyperlinkRun : public DocumentStyleApplicationRun, public Description<DocumentHyperlinkRun> { public: class Package : public Object, public Description<Package> { public: collections::List<Ptr<DocumentHyperlinkRun>> hyperlinks; vint row = -1; vint start = -1; vint end = -1; }; /// <summary>Style name for normal state.</summary> WString normalStyleName; /// <summary>Style name for active state.</summary> WString activeStyleName; /// <summary>The reference of the hyperlink.</summary> WString reference; DocumentHyperlinkRun(){} void Accept(IVisitor* visitor)override{visitor->Visit(this);} }; /// <summary>Pepresents a paragraph run.</summary> class DocumentParagraphRun : public DocumentContainerRun, public Description<DocumentParagraphRun> { public: /// <summary>Paragraph alignment.</summary> Nullable<Alignment> 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) ***********************************************************************/ /// <summary>Represents a text style.</summary> class DocumentStyle : public Object, public Description<DocumentStyle> { public: /// <summary>Parent style name, could be #Default, #Context, #NormalLink, #ActiveLink or style name of others</summary> WString parentStyleName; /// <summary>Properties of this style.</summary> Ptr<DocumentStyleProperties> styles; /// <summary>Resolved properties of this style using parent styles.</summary> Ptr<DocumentStyleProperties> resolvedStyles; }; /// <summary>Represents a rich content document model.</summary> class DocumentModel : public Object, public Description<DocumentModel> { 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: /// <summary>Represents a resolved style.</summary> struct ResolvedStyle { /// <summary>The style of the text.</summary> FontProperties style; /// <summary>The color of the text.</summary> Color color; /// <summary>The background color of the text.</summary> 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<DocumentRun*, RunRange> RunRangeMap; private: typedef collections::List<Ptr<DocumentParagraphRun>> ParagraphList; typedef collections::Dictionary<WString, Ptr<DocumentStyle>> StyleMap; public: /// <summary>All paragraphs.</summary> ParagraphList paragraphs; /// <summary>All available styles. These will not be persistant.</summary> StyleMap styles; DocumentModel(); static void MergeStyle(Ptr<DocumentStyleProperties> style, Ptr<DocumentStyleProperties> parent); void MergeBaselineStyle(Ptr<DocumentStyleProperties> style, const WString& styleName); void MergeBaselineStyle(Ptr<DocumentModel> baselineDocument, const WString& styleName); void MergeBaselineStyles(Ptr<DocumentModel> baselineDocument); void MergeDefaultFont(const FontProperties& defaultFont); ResolvedStyle GetStyle(Ptr<DocumentStyleProperties> 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<DocumentModel> CopyDocument(TextPos begin, TextPos end, bool deepCopy); Ptr<DocumentModel> CopyDocument(); bool CutParagraph(TextPos position); bool CutEditRange(TextPos begin, TextPos end); bool EditContainer(TextPos begin, TextPos end, const Func<void(DocumentParagraphRun*, RunRangeMap&, vint, vint)>& editor); vint EditRun(TextPos begin, TextPos end, Ptr<DocumentModel> replaceToModel, bool copy); vint EditRunNoCopy(TextPos begin, TextPos end, const collections::Array<Ptr<DocumentParagraphRun>>& runs); vint EditText(TextPos begin, TextPos end, bool frontSide, const collections::Array<WString>& text); bool EditStyle(TextPos begin, TextPos end, Ptr<DocumentStyleProperties> style); Ptr<DocumentImageRun> EditImage(TextPos begin, TextPos end, Ptr<GuiImageData> 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<DocumentHyperlinkRun::Package> 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<DocumentStyleProperties> SummarizeStyle(TextPos begin, TextPos end); Nullable<WString> SummarizeStyleName(TextPos begin, TextPos end); Nullable<Alignment> SummarizeParagraphAlignment(TextPos begin, TextPos end); /// <summary>Load a document model from an xml.</summary> /// <returns>The loaded document model.</returns> /// <param name="resource">The resource item containing the resource.</param> /// <param name="xml">The xml document.</param> /// <param name="resolver">A document resolver to resolve symbols in non-embedded objects like image.</param> /// <param name="errors">All collected errors during loading a resource.</param> static Ptr<DocumentModel> LoadFromXml(Ptr<GuiResourceItem> resource, Ptr<parsing::xml::XmlDocument> xml, Ptr<GuiResourcePathResolver> resolver, GuiResourceError::List& errors); /// <summary>Save a document model to an xml.</summary> /// <returns>The saved xml document.</returns> Ptr<parsing::xml::XmlDocument> 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 ***********************************************************************/ /// <summary> /// Defines a shape for some <see cref="IGuiGraphicsElement"></see>. /// </summary> enum class ElementShapeType { /// <summary>Rectangle shape.</summary> Rectangle, /// <summary>Ellipse shape.</summary> Ellipse, /// <summary>Round rectangle shape.</summary> RoundRect, }; /// <summary> /// Defines a shape for some <see cref="IGuiGraphicsElement"></see>. /// </summary> 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); } }; /// <summary> /// Defines a border element with a thickness of one pixel. /// </summary> class GuiSolidBorderElement : public GuiElementBase<GuiSolidBorderElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiSolidBorderElement, L"SolidBorder") protected: Color color; ElementShape shape; GuiSolidBorderElement(); public: /// <summary> /// Get the border color. /// </summary> /// <returns>The border color.</returns> Color GetColor(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new border color.</param> void SetColor(Color value); /// <summary> /// Get the shape. /// </summary> /// <returns>The shape.</returns> ElementShape GetShape(); /// <summary> /// Set the shape. /// </summary> /// <param name="value">The new shape.</param> void SetShape(ElementShape value); }; /// <summary> /// Defines a 3D-like rectangle element with a thickness of two pixels. /// </summary> class Gui3DBorderElement : public GuiElementBase<Gui3DBorderElement> { DEFINE_GUI_GRAPHICS_ELEMENT(Gui3DBorderElement, L"3DBorder") protected: Color color1; Color color2; Gui3DBorderElement(); public: /// <summary> /// Get the left-top color. /// </summary> /// <returns>The left-top color.</returns> Color GetColor1(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new left-top color.</param> void SetColor1(Color value); /// <summary> /// Get the right-bottom color. /// </summary> /// <returns>The right-bottom color.</returns> Color GetColor2(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new right-bottom color.</param> void SetColor2(Color value); /// <summary> /// Set colors of the element. /// </summary> /// <param name="value1">The new left-top color.</param> /// <param name="value2">The new right bottom color.</param> void SetColors(Color value1, Color value2); }; /// <summary> /// Defines a 3D-like splitter element with a thickness of two pixels. /// </summary> class Gui3DSplitterElement : public GuiElementBase<Gui3DSplitterElement> { DEFINE_GUI_GRAPHICS_ELEMENT(Gui3DSplitterElement, L"3DSplitter") public: /// <summary> /// Defines a direction of the <see cref="Gui3DSplitterElement"></see>. /// </summary> enum Direction { /// <summary>Horizontal direction.</summary> Horizontal, /// <summary>Vertical direction.</summary> Vertical, }; protected: Color color1; Color color2; Direction direction; Gui3DSplitterElement(); public: /// <summary> /// Get the left-top color. /// </summary> /// <returns>The left-top color.</returns> Color GetColor1(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new left-top color.</param> void SetColor1(Color value); /// <summary> /// Get the right-bottom color. /// </summary> /// <returns>The right-bottom color.</returns> Color GetColor2(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new right-bottom color.</param> void SetColor2(Color value); /// <summary> /// Set colors of the element. /// </summary> /// <param name="value1">The new left-top color.</param> /// <param name="value2">The new right bottom color.</param> void SetColors(Color value1, Color value2); /// <summary> /// Get the direction. /// </summary> /// <returns>The direction.</returns> Direction GetDirection(); /// <summary> /// Set the direction. /// </summary> /// <param name="value">The new direction.</param> void SetDirection(Direction value); }; /// <summary> /// Defines a color-filled element without border. /// </summary> class GuiSolidBackgroundElement : public GuiElementBase<GuiSolidBackgroundElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiSolidBackgroundElement, L"SolidBackground") protected: Color color; ElementShape shape; GuiSolidBackgroundElement(); public: /// <summary> /// Get the border color. /// </summary> /// <returns>The border color.</returns> Color GetColor(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new border color.</param> void SetColor(Color value); /// <summary> /// Get the shape. /// </summary> /// <returns>The shape.</returns> ElementShape GetShape(); /// <summary> /// Set the shape. /// </summary> /// <param name="value">The new shape.</param> void SetShape(ElementShape value); }; /// <summary> /// Defines a color-filled gradient element without border. /// </summary> class GuiGradientBackgroundElement : public GuiElementBase<GuiGradientBackgroundElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiGradientBackgroundElement, L"GradientBackground") public: /// <summary> /// Defines a direction of the <see cref="GuiGradientBackgroundElement"></see>. /// </summary> enum Direction { /// <summary>Horizontal direction.</summary> Horizontal, /// <summary>vertical direction.</summary> Vertical, /// <summary>Slash direction.</summary> Slash, /// <summary>Back slash direction.</summary> Backslash, }; protected: Color color1; Color color2; Direction direction; ElementShape shape; GuiGradientBackgroundElement(); public: /// <summary> /// Get the left-top color. /// </summary> /// <returns>The left-top color.</returns> Color GetColor1(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new left-top color.</param> void SetColor1(Color value); /// <summary> /// Get the right bottom color. /// </summary> /// <returns>The right-bottom color.</returns> Color GetColor2(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new right-bottom color.</param> void SetColor2(Color value); /// <summary> /// Set colors of the element. /// </summary> /// <param name="value1">The new left-top color.</param> /// <param name="value2">The new right bottom color.</param> void SetColors(Color value1, Color value2); /// <summary> /// Get the direction. /// </summary> /// <returns>The direction.</returns> Direction GetDirection(); /// <summary> /// Set the direction. /// </summary> /// <param name="value">The new direction.</param> void SetDirection(Direction value); /// <summary> /// Get the shape. /// </summary> /// <returns>The shape.</returns> ElementShape GetShape(); /// <summary> /// Set the shape. /// </summary> /// <param name="value">The new shape.</param> void SetShape(ElementShape value); }; /// <summary> /// Defines a gradient border for shadow. /// </summary> class GuiInnerShadowElement : public GuiElementBase<GuiInnerShadowElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiInnerShadowElement, L"InnerShadow") protected: Color color; vint thickness = 0; GuiInnerShadowElement(); public: /// <summary> /// Get the shadow color. /// </summary> /// <returns>The shadow color.</returns> Color GetColor(); /// <summary> /// Set the shadow color. /// </summary> /// <param name="value">The new shadow color.</param> void SetColor(Color value); /// <summary> /// Get the thickness. /// </summary> /// <returns>The thickness.</returns> vint GetThickness(); /// <summary> /// Set the thickness. /// </summary> /// <param name="value">The new thickness.</param> void SetThickness(vint value); }; /// <summary> /// Defines an element of a plain text. /// </summary> class GuiSolidLabelElement : public GuiElementBase<GuiSolidLabelElement> { 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: /// <summary> /// Get the text color. /// </summary> /// <returns>The text color.</returns> Color GetColor(); /// <summary> /// Set the text color. /// </summary> /// <param name="value">The new text color.</param> void SetColor(Color value); /// <summary> /// Get the text font. /// </summary> /// <returns>The text font.</returns> const FontProperties& GetFont(); /// <summary> /// Set the text font. /// </summary> /// <param name="value">The new text font.</param> void SetFont(const FontProperties& value); /// <summary> /// Get the text. /// </summary> /// <returns>The text.</returns> const WString& GetText(); /// <summary> /// Set the text. /// </summary> /// <param name="value">The new text.</param> void SetText(const WString& value); /// <summary> /// Get the horizontal alignment of the text. /// </summary> /// <returns>The horizontal alignment of the text.</returns> Alignment GetHorizontalAlignment(); /// <summary> /// Get the vertical alignment of the text. /// </summary> /// <returns>The vertical alignment of the text.</returns> Alignment GetVerticalAlignment(); /// <summary> /// Set the horizontal alignment of the text. /// </summary> /// <param name="value">The new horizontal alignment of the text.</param> void SetHorizontalAlignment(Alignment value); /// <summary> /// Set the vertical alignment of the text. /// </summary> /// <param name="value">The vertical alignment of the text.</param> void SetVerticalAlignment(Alignment value); /// <summary> /// Set alignments in both directions of the text. /// </summary> /// <param name="horizontal">The new horizontal alignment of the text.</param> /// <param name="vertical">The vertical alignment of the text.</param> void SetAlignments(Alignment horizontal, Alignment vertical); /// <summary> /// Get if line auto-wrapping is enabled for this text. /// </summary> /// <returns>Return true if line auto-wrapping is enabled for this text.</returns> bool GetWrapLine(); /// <summary> /// Set if line auto-wrapping is enabled for this text. /// </summary> /// <param name="value">True if line auto-wrapping is enabled for this text.</param> void SetWrapLine(bool value); /// <summary> /// Get if ellipse is enabled for this text. Ellipse will appear when the text is clipped. /// </summary> /// <returns>Return true if ellipse is enabled for this text.</returns> bool GetEllipse(); /// <summary> /// Set if ellipse is enabled for this text. Ellipse will appear when the text is clipped. /// </summary> /// <param name="value">True if ellipse is enabled for this text.</param> void SetEllipse(bool value); /// <summary> /// Get if multiple lines is enabled for this text. /// </summary> /// <returns>Return true if multiple lines is enabled for this text.</returns> bool GetMultiline(); /// <summary> /// Set if multiple lines is enabled for this text. /// </summary> /// <param name="value">True if multiple lines is enabled for this text.</param> void SetMultiline(bool value); /// <summary> /// Get if the element calculates the min height when wrap line is enabled. /// </summary> /// <returns>Return true if the element calculates the min height when wrap line is enabled.</returns> bool GetWrapLineHeightCalculation(); /// <summary> /// Set if the element calculates the min height when wrap line is enabled. /// </summary> /// <param name="value">True if the element calculates the min height when wrap line is enabled.</param> void SetWrapLineHeightCalculation(bool value); }; /// <summary> /// Defines an element containing an image. /// </summary> class GuiImageFrameElement : public GuiElementBase<GuiImageFrameElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiImageFrameElement, L"ImageFrame"); protected: Ptr<INativeImage> image; vint frameIndex; Alignment hAlignment; Alignment vAlignment; bool stretch; bool enabled; GuiImageFrameElement(); public: /// <summary> /// Get the containing image. /// </summary> /// <returns>The contining picture.</returns> Ptr<INativeImage> GetImage(); /// <summary> /// Get the index of the frame in the containing image. /// </summary> /// <returns>The index of the frame in the containing image</returns> vint GetFrameIndex(); /// <summary> /// Set the containing image. /// </summary> /// <param name="value">The new containing image.</param> void SetImage(Ptr<INativeImage> value); /// <summary> /// Set the frame index. /// </summary> /// <param name="value">The new frameIndex.</param> void SetFrameIndex(vint value); /// <summary> /// Set the containing image and the frame index. /// </summary> /// <param name="_image">The new containing image.</param> /// <param name="_frameIndex">The new frameIndex.</param> void SetImage(Ptr<INativeImage> _image, vint _frameIndex); /// <summary> /// Get the horizontal alignment of the image. /// </summary> /// <returns>The horizontal alignment of the image.</returns> Alignment GetHorizontalAlignment(); /// <summary> /// Get the vertical alignment of the image. /// </summary> /// <returns>The vertical alignment of the image.</returns> Alignment GetVerticalAlignment(); /// <summary> /// Set the horizontal alignment of the text. /// </summary> /// <param name="value">The new horizontal alignment of the text.</param> void SetHorizontalAlignment(Alignment value); /// <summary> /// Set the vertical alignment of the text. /// </summary> /// <param name="value">The vertical alignment of the text.</param> void SetVerticalAlignment(Alignment value); /// <summary> /// Set alignments in both directions of the image. /// </summary> /// <param name="horizontal">The new horizontal alignment of the image.</param> /// <param name="vertical">The vertical alignment of the image.</param> void SetAlignments(Alignment horizontal, Alignment vertical); /// <summary> /// Get if stretching is enabled for this image. /// </summary> /// <returns>Return true if stretching is enabled for this image.</returns> bool GetStretch(); /// <summary> /// Set if stretching is enabled for this image. /// </summary> /// <param name="value">True if stretching is enabled for this image.</param> void SetStretch(bool value); /// <summary> /// Get if the image is rendered as enabled. /// </summary> /// <returns>Return true if the image is rendered as enabled.</returns> bool GetEnabled(); /// <summary> /// Set if the image is rendered as enabled. /// </summary> /// <param name="value">True if the image is rendered as enabled.</param> void SetEnabled(bool value); }; /// <summary> /// Defines a polygon element with a thickness of one pixel. /// </summary> class GuiPolygonElement : public GuiElementBase<GuiPolygonElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiPolygonElement, L"Polygon"); typedef collections::Array<Point> PointArray; protected: Size size; PointArray points; Color borderColor; Color backgroundColor; GuiPolygonElement(); public: /// <summary> /// Get a suggested size. The polygon element will be layouted to the center of the required bounds using this size. /// </summary> /// <returns>The suggested size.</returns> Size GetSize(); /// <summary> /// Set a suggested size. The polygon element will be layouted to the center of the required bounds using this size. /// </summary> /// <param name="value">The new size.</param> void SetSize(Size value); /// <summary> /// Get a point of the polygon element using an index. /// </summary> /// <param name="index">The index to access a point.</param> /// <returns>The point of the polygon element associated with the index.</returns> const Point& GetPoint(vint index); /// <summary> /// Get the number of points /// </summary> /// <returns>The number of points.</returns> vint GetPointCount(); /// <summary> /// Set all points to the polygon element. /// </summary> /// <param name="p">A pointer to a buffer that stores all points.</param> /// <param name="count">The number of points.</param> void SetPoints(const Point* p, vint count); /// <summary> /// Get all points. /// </summary> /// <returns>All points</returns> const PointArray& GetPointsArray(); /// <summary> /// Set all points. /// </summary> /// <param name="value">All points</param> void SetPointsArray(const PointArray& value); /// <summary> /// Get the border color. /// </summary> /// <returns>The border color.</returns> Color GetBorderColor(); /// <summary> /// Set the border color. /// </summary> /// <param name="value">The new border color.</param> void SetBorderColor(Color value); /// <summary> /// Get the background color. /// </summary> /// <returns>The background color.</returns> Color GetBackgroundColor(); /// <summary> /// Set the background color. /// </summary> /// <param name="value">The new background color.</param> 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) ***********************************************************************/ /// <summary>Defines a rich text document element for rendering complex styled document.</summary> class GuiDocumentElement : public GuiElementBase<GuiDocumentElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiDocumentElement, L"RichDocument"); public: /// <summary>Callback interface for this element.</summary> class ICallback : public virtual IDescriptable, public Description<ICallback> { public: /// <summary>Called when the rendering is started.</summary> virtual void OnStartRender() = 0; /// <summary>Called when the rendering is finished.</summary> virtual void OnFinishRender() = 0; /// <summary>Called when an embedded object is being rendered.</summary> /// <returns>Returns the new size of the rendered embedded object.</returns> /// <param name="name">The name of the embedded object</param> /// <param name="location">The location of the embedded object, relative to the left-top corner of this element.</param> 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<vint, Ptr<EmbeddedObject>> IdEmbeddedObjectMap; typedef collections::Dictionary<WString, vint> NameIdMap; typedef collections::List<vint> FreeIdList; struct ParagraphCache { WString fullText; Ptr<IGuiGraphicsParagraph> graphicsParagraph; IdEmbeddedObjectMap embeddedObjects; vint selectionBegin; vint selectionEnd; ParagraphCache() :selectionBegin(-1) ,selectionEnd(-1) { } }; typedef collections::Array<Ptr<ParagraphCache>> ParagraphCacheArray; typedef collections::Array<vint> 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<ParagraphCache> 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<DocumentHyperlinkRun::Package> 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<DocumentModel> document; ICallback* callback = nullptr; TextPos caretBegin; TextPos caretEnd; bool caretVisible; bool caretFrontSide; Color caretColor; void UpdateCaret(); GuiDocumentElement(); public: /// <summary>Get the callback.</summary> /// <returns>The callback.</returns> ICallback* GetCallback(); /// <summary>Set the callback.</summary> /// <param name="value">The callback.</param> void SetCallback(ICallback* value); /// <summary>Get the document.</summary> /// <returns>The document.</returns> Ptr<DocumentModel> GetDocument(); /// <summary>Set the document. When a document is set to this element, modifying the document without invoking <see cref="NotifyParagraphUpdated"/> will lead to undefined behavior.</summary> /// <param name="value">The document.</param> void SetDocument(Ptr<DocumentModel> value); /// <summary> /// Get the begin position of the selection area. /// </summary> /// <returns>The begin position of the selection area.</returns> TextPos GetCaretBegin(); /// <summary> /// Get the end position of the selection area. /// </summary> /// <returns>The end position of the selection area.</returns> TextPos GetCaretEnd(); /// <summary> /// Get the prefer side for the caret. /// </summary> /// <returns>Returns true if the caret is rendered for the front side.</returns> bool IsCaretEndPreferFrontSide(); /// <summary> /// Set the end position of the selection area. /// </summary> /// <param name="begin">The begin position of the selection area.</param> /// <param name="end">The end position of the selection area.</param> /// <param name="frontSide">Set to true to show the caret for the character before it. This argument is ignored if begin and end are the same.</param> void SetCaret(TextPos begin, TextPos end, bool frontSide); /// <summary> /// Get the caret visibility. /// </summary> /// <returns>Returns true if the caret will be rendered.</returns> bool GetCaretVisible(); /// <summary> /// Set the caret visibility. /// </summary> /// <param name="value">True if the caret will be rendered.</param> void SetCaretVisible(bool value); /// <summary> /// Get the color of the caret. /// </summary> /// <returns>The color of the caret.</returns> Color GetCaretColor(); /// <summary> /// Set the color of the caret. /// </summary> /// <param name="value">The color of the caret.</param> void SetCaretColor(Color value); /// <summary>Calculate a caret using a specified comparing caret and a relative position.</summary> /// <returns>The calculated caret.</returns> /// <param name="comparingCaret">The comparing caret.</param> /// <param name="position">The relative position.</param> /// <param name="preferFrontSide">Specify the side for the comparingCaret. Retrive the suggested side for the new caret. If the return caret equals compareCaret, this output is ignored.</param> TextPos CalculateCaret(TextPos comparingCaret, IGuiGraphicsParagraph::CaretRelativePosition position, bool& preferFrontSide); /// <summary>Calculate a caret using a specified point.</summary> /// <returns>The calculated caret.</returns> /// <param name="point">The specified point.</param> TextPos CalculateCaretFromPoint(Point point); /// <summary>Get the bounds of a caret.</summary> /// <returns>The bounds.</returns> /// <param name="caret">The caret.</param> /// <param name="frontSide">Set to true to get the bounds for the character before it.</param> Rect GetCaretBounds(TextPos caret, bool frontSide); /// <summary>Notify that some paragraphs are updated.</summary> /// <param name="index">The start paragraph index.</param> /// <param name="oldCount">The number of paragraphs to be updated.</param> /// <param name="newCount">The number of updated paragraphs.</param> /// <param name="updatedText">Set to true to notify that the text is updated.</param> void NotifyParagraphUpdated(vint index, vint oldCount, vint newCount, bool updatedText); /// <summary>Edit run in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="model">The new run.</param> /// <param name="copy">Set to true to copy the model before editing. Otherwise, objects inside the model will be used directly</param> void EditRun(TextPos begin, TextPos end, Ptr<DocumentModel> model, bool copy); /// <summary>Edit text in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="frontSide">Set to true to use the text style in front of the specified range.</param> /// <param name="text">The new text.</param> void EditText(TextPos begin, TextPos end, bool frontSide, const collections::Array<WString>& text); /// <summary>Edit style in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="style">The new style.</param> void EditStyle(TextPos begin, TextPos end, Ptr<DocumentStyleProperties> style); /// <summary>Edit image in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="image">The new image.</param> void EditImage(TextPos begin, TextPos end, Ptr<GuiImageData> image); /// <summary>Set hyperlink in a specified range.</summary> /// <param name="paragraphIndex">The index of the paragraph to edit.</param> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="reference">The reference of the hyperlink.</param> /// <param name="normalStyleName">The normal style name of the hyperlink.</param> /// <param name="activeStyleName">The active style name of the hyperlink.</param> void EditHyperlink(vint paragraphIndex, vint begin, vint end, const WString& reference, const WString& normalStyleName=DocumentModel::NormalLinkStyleName, const WString& activeStyleName=DocumentModel::ActiveLinkStyleName); /// <summary>Remove hyperlink in a specified range.</summary> /// <param name="paragraphIndex">The index of the paragraph to edit.</param> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> void RemoveHyperlink(vint paragraphIndex, vint begin, vint end); /// <summary>Edit style name in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="styleName">The new style name.</param> void EditStyleName(TextPos begin, TextPos end, const WString& styleName); /// <summary>Remove style name in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> void RemoveStyleName(TextPos begin, TextPos end); /// <summary>Rename a style.</summary> /// <param name="oldStyleName">The name of the style.</param> /// <param name="newStyleName">The new name.</param> void RenameStyle(const WString& oldStyleName, const WString& newStyleName); /// <summary>Clear all styles in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> void ClearStyle(TextPos begin, TextPos end); /// <summary>Summarize the text style in a specified range.</summary> /// <returns>The text style summary.</returns> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> Ptr<DocumentStyleProperties> SummarizeStyle(TextPos begin, TextPos end); /// <summary>Summarize the style name in a specified range.</summary> /// <returns>The style name summary.</returns> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> Nullable<WString> SummarizeStyleName(TextPos begin, TextPos end); /// <summary>Set the alignment of paragraphs in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="alignments">The alignment for each paragraph.</param> void SetParagraphAlignment(TextPos begin, TextPos end, const collections::Array<Nullable<Alignment>>& alignments); /// <summary>Summarize the text alignment in a specified range.</summary> /// <returns>The text alignment summary.</returns> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> Nullable<Alignment> SummarizeParagraphAlignment(TextPos begin, TextPos end); /// <summary>Get hyperlink from point.</summary> /// <returns>Corressponding hyperlink id. Returns -1 indicates that the point is not in a hyperlink.</returns> /// <param name="point">The point to get the hyperlink id.</param> Ptr<DocumentHyperlinkRun::Package> 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 { /// <summary> /// Represents the extra information of a character to display. /// </summary> struct CharAtt { /// <summary> /// The distance from the head of the line to the right side of this character in pixel. /// </summary> vuint32_t rightOffset; /// <summary> /// 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. /// </summary> vuint32_t colorIndex; }; /// <summary> /// Represents a line of characters. /// </summary> struct TextLine { static const vint BlockSize=32; static const vint MaxWidth=0xFFFF; /// <summary> /// A character buffer starts from the first character of this line. /// </summary> wchar_t* text; /// <summary> /// A extra information buffer starts from the first character of this line. /// </summary> CharAtt* att; /// <summary> /// The number of available <see cref="CharAtt::rightOffset"/> in the buffer. /// </summary> vint availableOffsetCount; /// <summary> /// The number of elements in the allocated buffer memory. /// </summary> vint bufferLength; /// <summary> /// The number of available characters in the buffer. /// </summary> vint dataLength; /// <summary> /// 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. /// </summary> vint lexerFinalState; /// <summary> /// 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. /// </summary> 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;} /// <summary> /// Initialize the <see cref="TextLine"/> instance to be an empty line. /// </summary> void Initialize(); /// <summary> /// Release all resources used in this line. /// </summary> void Finalize(); /// <summary> /// Test is the line initialized. /// </summary> /// <returns>Returns true if the line is initialized.</returns> bool IsReady(); /// <summary> /// Modify the characters in the line by replacing characters. /// </summary> /// <returns>Returns true if the modification succeeded.</returns> /// <param name="start">The position of the first character to be replaced.</param> /// <param name="count">The number of characters to be replaced.</param> /// <param name="input">The buffer to the characters to write into this line.</param> /// <param name="inputCount">The numbers of the characters to write into this line.</param> bool Modify(vint start, vint count, const wchar_t* input, vint inputCount); /// <summary> /// 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. /// </summary> /// <returns>The new text line.</returns> /// <param name="index">.</param> TextLine Split(vint index); /// <summary> /// Append a text line after the this text line, and finalize the input text line. /// </summary> /// <param name="line">The text line that contains all characters and color indices to append and be finalized.</param> void AppendAndFinalize(TextLine& line); }; #if defined VCZH_MSVC /// <summary>Test if a wchar_t is the first character of a surrogate pair.</summary> /// <param name="c">The character to test.</param> /// <returns>Returns true if it is the first character of a surrogate pair.</returns> inline bool UTF16SPFirst(wchar_t c) { return 0xD800 <= c && c < 0xDC00; } /// <summary>Test if a wchar_t is the second character of a surrogate pair.</summary> /// <param name="c">The character to test.</param> /// <returns>Returns true if it is the second character of a surrogate pair.</returns> inline bool UTF16SPSecond(wchar_t c) { return 0xDC00 <= c && c < 0xDFFF; } #endif /// <summary> /// 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. /// </summary> 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 } }; /// <summary> /// An abstract class for character size measuring in differect rendering technology. /// </summary> class CharMeasurer : public virtual IDescriptable { protected: IGuiGraphicsRenderTarget* oldRenderTarget = nullptr; vint rowHeight; vint widths[65536]; /// <summary> /// Measure the width of a character. /// </summary> /// <returns>The width in pixel.</returns> /// <param name="codePoint">The unicode code point to measure.</param> /// <param name="renderTarget">The render target which the character is going to be rendered. This is a pure virtual member function to be overrided.</param> virtual vint MeasureWidthInternal(UnicodeCodePoint codePoint, IGuiGraphicsRenderTarget* renderTarget)=0; /// <summary> /// Measure the height of a character. /// </summary> /// <returns>The height in pixel.</returns> /// <param name="renderTarget">The render target which the character is going to be rendered.</param> virtual vint GetRowHeightInternal(IGuiGraphicsRenderTarget* renderTarget)=0; public: /// <summary> /// Initialize a character measurer. /// </summary> /// <param name="_rowHeight">The default character height in pixel before the character measurer is binded to a render target.</param> CharMeasurer(vint _rowHeight); ~CharMeasurer(); /// <summary> /// Bind a render target to this character measurer. /// </summary> /// <param name="value">The render target to bind.</param> void SetRenderTarget(IGuiGraphicsRenderTarget* value); /// <summary> /// Measure the width of a character using the binded render target. /// </summary> /// <returns>The width of a character, in pixel.</returns> /// <param name="codePoint">The unicode code point to measure.</param> vint MeasureWidth(UnicodeCodePoint codePoint); /// <summary> /// Measure the height of a character. /// </summary> /// <returns>The height of a character, in pixel.</returns> vint GetRowHeight(); }; /// <summary> /// A class to maintain multiple lines of text buffer. /// </summary> class TextLines : public Object, public Description<TextLines> { typedef collections::List<TextLine> TextLineList; protected: GuiColorizedTextElement* ownerElement; TextLineList lines; CharMeasurer* charMeasurer; IGuiGraphicsRenderTarget* renderTarget; vint tabWidth; vint tabSpaceCount; wchar_t passwordChar; public: TextLines(GuiColorizedTextElement* _ownerElement); ~TextLines(); /// <summary> /// Returns the number of text lines. /// </summary> /// <returns>The number of text lines.</returns> vint GetCount(); /// <summary> /// Returns the text line of a specified row number. /// </summary> /// <returns>The related text line object.</returns> /// <param name="row">The specified row number.</param> TextLine& GetLine(vint row); /// <summary> /// Returns the binded <see cref="CharMeasurer"/>. /// </summary> /// <returns>The binded <see cref="CharMeasurer"/>.</returns> CharMeasurer* GetCharMeasurer(); /// <summary> /// Binded a <see cref="CharMeasurer"/>. /// </summary> /// <param name="value">The <see cref="CharMeasurer"/> to bind.</param> void SetCharMeasurer(CharMeasurer* value); /// <summary> /// Returns the binded <see cref="IGuiGraphicsRenderTarget"/>. /// </summary> /// <returns>The binded <see cref="IGuiGraphicsRenderTarget"/>.</returns> IGuiGraphicsRenderTarget* GetRenderTarget(); /// <summary> /// Binded a <see cref="IGuiGraphicsRenderTarget"/>. /// </summary> /// <param name="value">The <see cref="IGuiGraphicsRenderTarget"/> to bind.</param> void SetRenderTarget(IGuiGraphicsRenderTarget* value); /// <summary> /// Returns a string from a specified range of the text lines. /// </summary> /// <returns>The string.</returns> /// <param name="start">The start position.</param> /// <param name="end">The end position.</param> WString GetText(TextPos start, TextPos end); /// <summary> /// Returns the whole string in the text lines. /// </summary> /// <returns>The string.</returns> WString GetText(); /// <summary> /// Set the string to the text lines. This operation will modified every <see cref="TextLine"/> objects. /// </summary> /// <param name="value">The string to set into the text lines.</param> void SetText(const WString& value); /// <summary> /// Remove text lines in a specified range. /// </summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="start">The first row number.</param> /// <param name="count">The number of text lines to be removed.</param> bool RemoveLines(vint start, vint count); /// <summary> /// Test is a text position available in the text lines. /// </summary> /// <returns>Returns true if this position is available.</returns> /// <param name="pos">The text position to test.</param> bool IsAvailable(TextPos pos); /// <summary> /// Normalize a text position to be available. /// </summary> /// <returns>The normalized text position.</returns> /// <param name="pos">The text position to normalize.</param> TextPos Normalize(TextPos pos); /// <summary> /// Modify some text lines by replacing characters. /// </summary> /// <returns>The new end position.</returns> /// <param name="start">The start position of the range of characters to be replaced.</param> /// <param name="end">The end position of the range of characters to be replaced.</param> /// <param name="inputs">The buffer to the string buffers to replace into the text lines.</param> /// <param name="inputCounts">The numbers of characters for each string buffer.</param> /// <param name="rows">The number of string buffers.</param> TextPos Modify(TextPos start, TextPos end, const wchar_t** inputs, vint* inputCounts, vint rows); /// <summary> /// Modify some text lines by replacing characters. /// </summary> /// <returns>The new end position.</returns> /// <param name="start">The start position of the range of characters to be replaced.</param> /// <param name="end">The end position of the range of characters to be replaced.</param> /// <param name="input">The buffer to the string to replace into the text lines.</param> /// <param name="inputCount">The number of characters to replace into the text lines.</param> TextPos Modify(TextPos start, TextPos end, const wchar_t* input, vint inputCount); /// <summary> /// Modify some text lines by replacing characters. /// </summary> /// <returns>The new end position.</returns> /// <param name="start">The start position of the range of characters to be replaced.</param> /// <param name="end">The end position of the range of characters to be replaced.</param> /// <param name="input">The string to replace into the text lines.</param> TextPos Modify(TextPos start, TextPos end, const wchar_t* input); /// <summary> /// Modify some text lines by replacing characters. /// </summary> /// <returns>The new end position.</returns> /// <param name="start">The start position of the range of characters to be replaced.</param> /// <param name="end">The end position of the range of characters to be replaced.</param> /// <param name="input">The string to replace into the text lines.</param> TextPos Modify(TextPos start, TextPos end, const WString& input); /// <summary> /// Remove every text lines. /// </summary> void Clear(); /// <summary> /// Clear all cached <see cref="CharAtt::rightOffset"/>. /// </summary> void ClearMeasurement(); /// <summary> /// Returns the number of spaces to replace a tab character for rendering. /// </summary> /// <returns>The number of spaces to replace a tab character for rendering.</returns> vint GetTabSpaceCount(); /// <summary> /// Set the number of spaces to replace a tab character for rendering. /// </summary> /// <param name="value">The number of spaces to replace a tab character for rendering.</param> void SetTabSpaceCount(vint value); /// <summary> /// Measure all characters in a specified row. /// </summary> /// <param name="row">The specified row number.</param> void MeasureRow(vint row); /// <summary> /// Returns the width of a specified row. /// </summary> /// <returns>The width of a specified row, in pixel.</returns> /// <param name="row">The specified row number.</param> vint GetRowWidth(vint row); /// <summary> /// Returns the height of a row. /// </summary> /// <returns>The height of a row, in pixel.</returns> vint GetRowHeight(); /// <summary> /// Returns the total width of the text lines. /// </summary> /// <returns>The width of the text lines, in pixel.</returns> vint GetMaxWidth(); /// <summary> /// Returns the total height of the text lines. /// </summary> /// <returns>The height of the text lines, in pixel.</returns> vint GetMaxHeight(); /// <summary> /// Get the text position near to specified point. /// </summary> /// <returns>The text position.</returns> /// <param name="point">The specified point, in pixel.</param> TextPos GetTextPosFromPoint(Point point); /// <summary> /// Get the point of a specified text position. /// </summary> /// <returns>The point, in pixel. Returns (-1, -1) if the text position is not available.</returns> /// <param name="pos">The specified text position.</param> Point GetPointFromTextPos(TextPos pos); /// <summary> /// Get the bounds of a specified text position. /// </summary> /// <returns>The bounds, in pixel. Returns (-1, -1, -1, -1) if the text position is not available.</returns> /// <param name="pos">The specified text position.</param> Rect GetRectFromTextPos(TextPos pos); /// <summary> /// Get the password mode displaying character. /// </summary> /// <returns>The password mode displaying character. Returns L'\0' means the password mode is not activated.</returns> wchar_t GetPasswordChar(); /// <summary> /// Set the password mode displaying character. /// </summary> /// <param name="value">The password mode displaying character. Set to L'\0' to deactivate the password mode.</param> void SetPasswordChar(wchar_t value); }; /// <summary> /// Represents colors of a character. /// </summary> struct ColorItem { /// <summary> /// Text color. /// </summary> Color text; /// <summary> /// Background color. /// </summary> Color background; bool operator==(const ColorItem& value)const { return text == value.text && background == value.background; } bool operator!=(const ColorItem& value)const { return !(*this == value); } }; /// <summary> /// 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. /// </summary> struct ColorEntry { /// <summary> /// Colors in normal state. /// </summary> ColorItem normal; /// <summary> /// Colors in focused and selected state. /// </summary> ColorItem selectedFocused; /// <summary> /// Colors in not focused and selected state. /// </summary> ColorItem selectedUnfocused; bool operator==(const ColorEntry& value)const {return normal == value.normal && selectedFocused == value.selectedFocused && selectedUnfocused == value.selectedUnfocused;} bool operator!=(const ColorEntry& value)const {return !(*this == value);} }; } /*********************************************************************** Colorized Plain Text (element) ***********************************************************************/ /// <summary> /// Defines a text element with separate color configuration for each character. /// </summary> class GuiColorizedTextElement : public GuiElementBase<GuiColorizedTextElement> { DEFINE_GUI_GRAPHICS_ELEMENT(GuiColorizedTextElement, L"ColorizedText"); friend class text::TextLines; typedef collections::Array<text::ColorEntry> ColorArray; public: /// <summary> /// An callback interface. Member functions will be called when colors or fonts of a <see cref="GuiColorizedTextElement"/> changed. /// </summary> class ICallback : public virtual IDescriptable, public Description<ICallback> { public: /// <summary> /// Called when the color table of a <see cref="GuiColorizedTextElement"/> changed. /// </summary> virtual void ColorChanged()=0; /// <summary> /// Called when the font configuration of a <see cref="GuiColorizedTextElement"/> changed. /// </summary> 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: /// <summary> /// Get the internal <see cref="text::TextLines"/> object that stores all characters and colors. /// </summary> /// <returns>The internal <see cref="text::TextLines"/> object.</returns> text::TextLines& GetLines(); /// <summary> /// Get the binded callback object. /// </summary> /// <returns>The binded callback object.</returns> ICallback* GetCallback(); /// <summary> /// Bind a callback object. /// </summary> /// <param name="value">The callback object to bind.</param> void SetCallback(ICallback* value); /// <summary> /// Get the binded color table. Use <see cref="text::CharAtt::colorIndex"/> to use colors in this color table. /// </summary> /// <returns>The binded color table.</returns> const ColorArray& GetColors(); /// <summary> /// Bind a color table. Use <see cref="text::CharAtt::colorIndex"/> to use colors in this color table. <see cref="ICallback::ColorChanged"/> will be called. /// </summary> /// <param name="value">The color table to bind.</param> void SetColors(const ColorArray& value); /// <summary> /// Reset color of all characters /// </summary> /// <param name="index">Color index of all characters.</param> void ResetTextColorIndex(vint index); /// <summary> /// Get the font configuration for all characters. /// </summary> /// <returns>The font configuration.</returns> const FontProperties& GetFont(); /// <summary> /// Set the font configuration for all characters. <see cref="ICallback::FontChanged"/> will be called. /// </summary> /// <param name="value">The font configuration.</param> void SetFont(const FontProperties& value); /// <summary> /// Get the password mode displaying character. /// </summary> /// <returns>The password mode displaying character. Returns L'\0' means the password mode is not activated.</returns> wchar_t GetPasswordChar(); /// <summary> /// Set the password mode displaying character. /// </summary> /// <param name="value">The password mode displaying character. Set to L'\0' to deactivate the password mode.</param> void SetPasswordChar(wchar_t value); /// <summary> /// Get the left-top position of the visible bounds of characters. /// </summary> /// <returns>The left-top position of the visible bounds of characters.</returns> Point GetViewPosition(); /// <summary> /// Set the left-top position of the visible bounds of characters. /// </summary> /// <param name="value">The left-top position of the visible bounds of characters.</param> void SetViewPosition(Point value); /// <summary> /// Get the enabling state. /// </summary> /// <returns>Returns true if the element will be rendered as an enabled element.</returns> bool GetVisuallyEnabled(); /// <summary> /// Set the enabling state. /// </summary> /// <param name="value">True if the element will be rendered as an enabled element.</param> void SetVisuallyEnabled(bool value); /// <summary> /// Get the focused state. /// </summary> /// <returns>Returns true if the element will be rendered as a focused element.</returns> bool GetFocused(); /// <summary> /// Set the focused state. /// </summary> /// <param name="value">True if the element will be rendered as a focused element.</param> void SetFocused(bool value); /// <summary> /// Get the begin position of the selection area. /// </summary> /// <returns>The begin position of the selection area.</returns> TextPos GetCaretBegin(); /// <summary> /// Set the begin position of the selection area. /// </summary> /// <param name="value">The begin position of the selection area.</param> void SetCaretBegin(TextPos value); /// <summary> /// Get the end position of the selection area. /// </summary> /// <returns>The end position of the selection area.</returns> TextPos GetCaretEnd(); /// <summary> /// Set the end position of the selection area. /// </summary> /// <param name="value">The end position of the selection area.</param> void SetCaretEnd(TextPos value); /// <summary> /// Get the caret visibility. /// </summary> /// <returns>Returns true if the caret will be rendered.</returns> bool GetCaretVisible(); /// <summary> /// Set the caret visibility. /// </summary> /// <param name="value">True if the caret will be rendered.</param> void SetCaretVisible(bool value); /// <summary> /// Get the color of the caret. /// </summary> /// <returns>The color of the caret.</returns> Color GetCaretColor(); /// <summary> /// Set the color of the caret. /// </summary> /// <param name="value">The color of the caret.</param> void SetCaretColor(Color value); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSCOMPOSITIONBASE.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSCOMPOSITIONBASE #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSCOMPOSITIONBASE namespace vl { namespace presentation { namespace controls { class GuiControl; class GuiControlHost; } namespace compositions { class GuiGraphicsHost; /*********************************************************************** Basic Construction ***********************************************************************/ /// <summary> /// Represents a composition for <see cref="elements::IGuiGraphicsElement"/>. 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. /// </summary> class GuiGraphicsComposition : public Object, public Description<GuiGraphicsComposition> { typedef collections::List<GuiGraphicsComposition*> CompositionList; friend class controls::GuiControl; friend class GuiGraphicsHost; friend void InvokeOnCompositionStateChanged(compositions::GuiGraphicsComposition* composition); public: /// <summary> /// Minimum size limitation. /// </summary> enum MinSizeLimitation { /// <summary>No limitation for the minimum size.</summary> NoLimit, /// <summary>Minimum size of this composition is the minimum size of the contained graphics element.</summary> LimitToElement, /// <summary>Minimum size of this composition is combiniation of sub compositions and the minimum size of the contained graphics element.</summary> LimitToElementAndChildren, }; protected: struct GraphicsHostRecord { GuiGraphicsHost* host = nullptr; elements::IGuiGraphicsRenderTarget* renderTarget = nullptr; INativeWindow* nativeWindow = nullptr; }; protected: CompositionList children; GuiGraphicsComposition* parent = nullptr; Ptr<elements::IGuiGraphicsElement> ownedElement; bool visible = true; bool transparentToMouse = false; MinSizeLimitation minSizeLimitation = MinSizeLimitation::NoLimit; Ptr<compositions::GuiGraphicsEventReceiver> 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(); /// <summary>Get the parent composition.</summary> /// <returns>The parent composition.</returns> GuiGraphicsComposition* GetParent(); /// <summary>Get all child compositions ordered by z-order from low to high.</summary> /// <returns>Child compositions.</returns> const CompositionList& Children(); /// <summary>Add a composition as a child.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="child">The child composition to add.</param> bool AddChild(GuiGraphicsComposition* child); /// <summary>Add a composition as a child with a specified z-order.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="index">The z-order. 0 means the lowest position.</param> /// <param name="child">The child composition to add.</param> bool InsertChild(vint index, GuiGraphicsComposition* child); /// <summary>Remove a child composition.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="child">The child composition to remove.</param> bool RemoveChild(GuiGraphicsComposition* child); /// <summary>Move a child composition to a new z-order.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="child">The child composition to move.</param> /// <param name="newIndex">The new z-order. 0 means the lowest position.</param> bool MoveChild(GuiGraphicsComposition* child, vint newIndex); /// <summary>Get the contained graphics element.</summary> /// <returns>The contained graphics element.</returns> Ptr<elements::IGuiGraphicsElement> GetOwnedElement(); /// <summary>Set the contained graphics element.</summary> /// <param name="element">The new graphics element to set.</param> void SetOwnedElement(Ptr<elements::IGuiGraphicsElement> element); /// <summary>Get the visibility of the composition.</summary> /// <returns>Returns true if the composition is visible.</returns> bool GetVisible(); /// <summary>Set the visibility of the composition.</summary> /// <param name="value">Set to true to make the composition visible.</param> void SetVisible(bool value); /// <summary>Get the minimum size limitation of the composition.</summary> /// <returns>The minimum size limitation of the composition.</returns> MinSizeLimitation GetMinSizeLimitation(); /// <summary>Set the minimum size limitation of the composition.</summary> /// <param name="value">The minimum size limitation of the composition.</param> void SetMinSizeLimitation(MinSizeLimitation value); /// <summary>Get the binded render target.</summary> /// <returns>The binded render target.</returns> elements::IGuiGraphicsRenderTarget* GetRenderTarget(); /// <summary>Render the composition using an offset.</summary> /// <param name="offset">The offset.</param> void Render(Size offset); /// <summary>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).</summary> /// <returns>The event receiver.</returns> compositions::GuiGraphicsEventReceiver* GetEventReceiver(); /// <summary>Test if any event receiver has already been requested.</summary> /// <returns>Returns true if any event receiver has already been requested.</returns> bool HasEventReceiver(); /// <summary>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.</summary> /// <returns>The deepest composition that under a specified location.</returns> /// <param name="location">The specified location.</param> /// <param name="forMouseEvent">Find a composition for mouse event, it will ignore all compositions that are transparent to mouse events.</param> GuiGraphicsComposition* FindComposition(Point location, bool forMouseEvent); /// <summary>Get is this composition transparent to mouse events.</summary> /// <returns>Returns true if this composition is transparent to mouse events, which means it just passes all mouse events to the composition under it.</returns> bool GetTransparentToMouse(); /// <summary>Set is the composition transparent to mouse events.</summary> /// <param name="value">Set to true to make this composition transparent to mouse events.</param> void SetTransparentToMouse(bool value); /// <summary>Get the bounds in the top composition space.</summary> /// <returns>The bounds in the top composition space.</returns> Rect GetGlobalBounds(); /// <summary>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.</summary> /// <returns>The associated control.</returns> controls::GuiControl* GetAssociatedControl(); /// <summary>Get the associated graphics host. A graphics host is associated to a composition only when the composition becomes the bounds of the graphics host.</summary> /// <returns>The associated graphics host.</returns> GuiGraphicsHost* GetAssociatedHost(); /// <summary>Get the associated cursor.</summary> /// <returns>The associated cursor.</returns> INativeCursor* GetAssociatedCursor(); /// <summary>Set the associated cursor.</summary> /// <param name="cursor">The associated cursor.</param> void SetAssociatedCursor(INativeCursor* cursor); /// <summary>Get the associated hit test result.</summary> /// <returns>The associated hit test result.</returns> INativeWindowListener::HitTestResult GetAssociatedHitTestResult(); /// <summary>Set the associated hit test result.</summary> /// <param name="value">The associated hit test result.</param> void SetAssociatedHitTestResult(INativeWindowListener::HitTestResult value); /// <summary>Get the related control. A related control is the deepest control that contains this composition.</summary> /// <returns>The related control.</returns> controls::GuiControl* GetRelatedControl(); /// <summary>Get the related graphics host. A related graphics host is the graphics host that contains this composition.</summary> /// <returns>The related graphics host.</returns> GuiGraphicsHost* GetRelatedGraphicsHost(); /// <summary>Get the related control host. A related control host is the control host that contains this composition.</summary> /// <returns>The related control host.</returns> controls::GuiControlHost* GetRelatedControlHost(); /// <summary>Get the related cursor. A related cursor is from the deepest composition that contains this composition and associated with a cursor.</summary> /// <returns>The related cursor.</returns> INativeCursor* GetRelatedCursor(); /// <summary>Get the margin.</summary> /// <returns>The margin.</returns> virtual Margin GetMargin(); /// <summary>Set the margin.</summary> /// <param name="value">The margin.</param> virtual void SetMargin(Margin value); /// <summary>Get the internal margin.</summary> /// <returns>The internal margin.</returns> virtual Margin GetInternalMargin(); /// <summary>Set the internal margin.</summary> /// <param name="value">The internal margin.</param> virtual void SetInternalMargin(Margin value); /// <summary>Get the preferred minimum size.</summary> /// <returns>The preferred minimum size.</returns> virtual Size GetPreferredMinSize(); /// <summary>Set the preferred minimum size.</summary> /// <param name="value">The preferred minimum size.</param> virtual void SetPreferredMinSize(Size value); /// <summary>Get the client area.</summary> /// <returns>The client area.</returns> virtual Rect GetClientArea(); /// <summary>Force to calculate layout and size immediately</summary> virtual void ForceCalculateSizeImmediately(); /// <summary>Test is the size calculation affected by the parent.</summary> /// <returns>Returns true if the size calculation is affected by the parent.</returns> virtual bool IsSizeAffectParent()=0; /// <summary>Get the preferred minimum client size.</summary> /// <returns>The preferred minimum client size.</returns> virtual Size GetMinPreferredClientSize()=0; /// <summary>Get the preferred bounds.</summary> /// <returns>The preferred bounds.</returns> virtual Rect GetPreferredBounds()=0; /// <summary>Get the bounds.</summary> /// <returns>The bounds.</returns> virtual Rect GetBounds()=0; }; /// <summary> /// A general implementation for <see cref="GuiGraphicsComposition"/>. /// </summary> class GuiGraphicsSite : public GuiGraphicsComposition, public Description<GuiGraphicsSite> { protected: Rect previousBounds; /// <summary>Calculate the final bounds from an expected bounds.</summary> /// <returns>The final bounds according to some configuration like margin, minimum size, etc..</returns> /// <param name="expectedBounds">The expected bounds.</param> virtual Rect GetBoundsInternal(Rect expectedBounds); void UpdatePreviousBounds(Rect bounds); public: GuiGraphicsSite(); ~GuiGraphicsSite(); /// <summary>Event that will be raised when the final bounds is changed.</summary> compositions::GuiNotifyEvent BoundsChanged; bool IsSizeAffectParent()override; Size GetMinPreferredClientSize()override; Rect GetPreferredBounds()override; }; /*********************************************************************** Helper Functions ***********************************************************************/ /// <summary>Call [M:vl.presentation.controls.GuiInstanceRootObject.FinalizeInstance] in all child root objects.</summary> /// <param name="value">The container control to notify.</param> extern void NotifyFinalizeInstance(controls::GuiControl* value); /// <summary>Call [M:vl.presentation.controls.GuiInstanceRootObject.FinalizeInstance] in all child root objects.</summary> /// <param name="value">The container composition to notify.</param> extern void NotifyFinalizeInstance(GuiGraphicsComposition* value); /// <summary>Safely remove and delete a control.</summary> /// <param name="value">The control to delete.</param> extern void SafeDeleteControl(controls::GuiControl* value); /// <summary>Safely remove and delete a composition. If some sub compositions are controls, those controls will be deleted too.</summary> /// <param name="value">The composition to delete.</param> extern void SafeDeleteComposition(GuiGraphicsComposition* value); } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSBASICCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSBASICCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSBASICCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Basic Compositions ***********************************************************************/ /// <summary> /// Represents a composition for the client area in an <see cref="INativeWindow"/>. /// </summary> class GuiWindowComposition : public GuiGraphicsSite, public Description<GuiWindowComposition> { public: GuiWindowComposition(); ~GuiWindowComposition(); Rect GetBounds()override; void SetMargin(Margin value)override; }; /// <summary> /// Represents a composition that is free to change the expected bounds. /// </summary> class GuiBoundsComposition : public GuiGraphicsSite, public Description<GuiBoundsComposition> { protected: bool sizeAffectParent = true; Rect compositionBounds; Margin alignmentToParent{ -1,-1,-1,-1 }; public: GuiBoundsComposition(); ~GuiBoundsComposition(); /// <summary>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.</summary> /// <returns>Returns true if it is awared.</returns> bool GetSizeAffectParent(); /// <summary>Set if the parent composition's size calculation is aware of the configuration of this composition.</summary> /// <param name="value">Set to true to be awared.</param> void SetSizeAffectParent(bool value); bool IsSizeAffectParent()override; Rect GetPreferredBounds()override; Rect GetBounds()override; /// <summary>Set the expected bounds.</summary> /// <param name="value">The expected bounds.</param> void SetBounds(Rect value); /// <summary>Get the alignment to its parent. -1 in each alignment component means that the corressponding side is not aligned to its parent.</summary> /// <returns>The alignment to its parent.</returns> Margin GetAlignmentToParent(); /// <summary>Set the alignment to its parent. -1 in each alignment component means that the corressponding side is not aligned to its parent.</summary> /// <param name="value">The alignment to its parent.</param> void SetAlignmentToParent(Margin value); /// <summary>Test is the composition aligned to its parent.</summary> /// <returns>Returns true if the composition is aligned to its parent.</returns> bool IsAlignedToParent(); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSRESPONSIVECOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSRESPONSIVECOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSRESPONSIVECOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** GuiResponsiveCompositionBase ***********************************************************************/ enum class ResponsiveDirection { Horizontal = 1, Vertical = 2, Both = 3, }; /// <summary>Base class for responsive layout compositions.</summary> class GuiResponsiveCompositionBase abstract : public GuiBoundsComposition, public Description<GuiResponsiveCompositionBase> { 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(); /// <summary>LevelCount changed event.</summary> GuiNotifyEvent LevelCountChanged; /// <summary>CurrentLevel chagned event.</summary> GuiNotifyEvent CurrentLevelChanged; /// <summary>Get the level count. A level count represents how many views this composition carries.</summary> /// <returns>The level count.</returns> virtual vint GetLevelCount() = 0; /// <summary>Get the current level. Zero is the view with the smallest size.</summary> /// <returns>The current level.</returns> virtual vint GetCurrentLevel() = 0; /// <summary>Switch to a smaller view.</summary> /// <returns>Returns true if this operation succeeded.</returns> virtual bool LevelDown() = 0; /// <summary>Switch to a larger view.</summary> /// <returns>Returns true if this operation succeeded.</returns> virtual bool LevelUp() = 0; /// <summary>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 .</summary> /// <returns>All supported directions.</returns> ResponsiveDirection GetDirection(); /// <summary>Set all supported directions.</summary> /// <param name="value">All supported directions.</param> void SetDirection(ResponsiveDirection value); }; /*********************************************************************** GuiResponsiveViewComposition ***********************************************************************/ class GuiResponsiveViewComposition; class GuiResponsiveSharedComposition; class GuiResponsiveSharedCollection : public collections::ObservableListBase<controls::GuiControl*> { 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<GuiResponsiveCompositionBase*> { 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(); }; /// <summary>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]</summary> class GuiResponsiveSharedComposition : public GuiBoundsComposition, public Description<GuiResponsiveSharedComposition> { protected: GuiResponsiveViewComposition* view = nullptr; controls::GuiControl* shared = nullptr; void SetSharedControl(); void OnParentLineChanged()override; public: GuiResponsiveSharedComposition(); ~GuiResponsiveSharedComposition(); /// <summary>Get the selected shared control.</summary> /// <returns>The selected shared control.</returns> controls::GuiControl* GetShared(); /// <summary>Set the selected shared control, which should be stored in [M:vl.presentation.compositions.GuiResponsiveViewComposition.GetSharedControls].</summary> /// <param name="value">The selected shared control.</param> void SetShared(controls::GuiControl* value); }; /// <summary>A responsive layout composition defined by views of different sizes.</summary> class GuiResponsiveViewComposition : public GuiResponsiveCompositionBase, public Description<GuiResponsiveViewComposition> { friend class GuiResponsiveSharedCollection; friend class GuiResponsiveViewCollection; friend class GuiResponsiveSharedComposition; using ControlSet = collections::SortedList<controls::GuiControl*>; 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(); /// <summary>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.</summary> GuiItemNotifyEvent BeforeSwitchingView; vint GetLevelCount()override; vint GetCurrentLevel()override; bool LevelDown()override; bool LevelUp()override; /// <summary>Get the current displaying view.</summary> /// <returns>The current displaying view.</returns> GuiResponsiveCompositionBase* GetCurrentView(); /// <summary>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.</summary> /// <returns>All shared controls.</returns> collections::ObservableListBase<controls::GuiControl*>& GetSharedControls(); /// <summary>Get all individual views to switch.</summary> /// <returns>All individual views to switch.</returns> collections::ObservableListBase<GuiResponsiveCompositionBase*>& GetViews(); }; /*********************************************************************** Others ***********************************************************************/ /// <summary>A responsive layout composition which stop parent responsive composition to search its children.</summary> class GuiResponsiveFixedComposition : public GuiResponsiveCompositionBase, public Description<GuiResponsiveFixedComposition> { protected: void OnResponsiveChildLevelUpdated()override; public: GuiResponsiveFixedComposition(); ~GuiResponsiveFixedComposition(); vint GetLevelCount()override; vint GetCurrentLevel()override; bool LevelDown()override; bool LevelUp()override; }; /// <summary>A responsive layout composition which change its size by changing children's views one by one in one direction.</summary> class GuiResponsiveStackComposition : public GuiResponsiveCompositionBase, public Description<GuiResponsiveStackComposition> { using ResponsiveChildList = collections::List<GuiResponsiveCompositionBase*>; 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; }; /// <summary>A responsive layout composition which change its size by changing children's views at the same time.</summary> class GuiResponsiveGroupComposition : public GuiResponsiveCompositionBase, public Description<GuiResponsiveGroupComposition> { using ResponsiveChildList = collections::List<GuiResponsiveCompositionBase*>; 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 ***********************************************************************/ /// <summary>A composition which will automatically tell its target responsive composition to switch between views according to its size.</summary> class GuiResponsiveContainerComposition : public GuiBoundsComposition, public Description<GuiResponsiveContainerComposition> { protected: GuiResponsiveCompositionBase* responsiveTarget = nullptr; Size upperLevelSize; void AdjustLevel(); void OnBoundsChanged(GuiGraphicsComposition* sender, GuiEventArgs& arguments); public: GuiResponsiveContainerComposition(); ~GuiResponsiveContainerComposition(); /// <summary>Get the responsive composition to control.</summary> /// <returns>The responsive composition to control.</returns> GuiResponsiveCompositionBase* GetResponsiveTarget(); /// <summary>Get the responsive composition to control.</summary> /// <param name="value">The responsive composition to control.</param> void SetResponsiveTarget(GuiResponsiveCompositionBase* value); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSSPECIALIZEDCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSSPECIALIZEDCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSSPECIALIZEDCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Specialized Compositions ***********************************************************************/ /// <summary> /// Represents a composition that is aligned to one border of the parent composition. /// </summary> class GuiSideAlignedComposition : public GuiGraphicsSite, public Description<GuiSideAlignedComposition> { public: /// <summary>The border to align.</summary> enum Direction { /// <summary>The left border.</summary> Left, /// <summary>The top border.</summary> Top, /// <summary>The right border.</summary> Right, /// <summary>The bottom border.</summary> Bottom, }; protected: Direction direction; vint maxLength; double maxRatio; public: GuiSideAlignedComposition(); ~GuiSideAlignedComposition(); /// <summary>Get the border to align.</summary> /// <returns>The border to align.</returns> Direction GetDirection(); /// <summary>Set the border to align.</summary> /// <param name="value">The border to align.</param> void SetDirection(Direction value); /// <summary>Get the maximum length of this composition.</summary> /// <returns>The maximum length of this composition.</returns> vint GetMaxLength(); /// <summary>Set the maximum length of this composition.</summary> /// <param name="value">The maximum length of this composition.</param> void SetMaxLength(vint value); /// <summary>Get the maximum ratio to limit the size according to the size of the parent.</summary> /// <returns>The maximum ratio to limit the size according to the size of the parent.</returns> double GetMaxRatio(); /// <summary>Set the maximum ratio to limit the size according to the size of the parent.</summary> /// <param name="value">The maximum ratio to limit the size according to the size of the parent.</param> void SetMaxRatio(double value); bool IsSizeAffectParent()override; Rect GetBounds()override; }; /// <summary> /// Represents a composition that its location and size are decided by the client area of the parent composition by setting ratios. /// </summary> class GuiPartialViewComposition : public GuiGraphicsSite, public Description<GuiPartialViewComposition> { protected: double wRatio; double wPageSize; double hRatio; double hPageSize; public: GuiPartialViewComposition(); ~GuiPartialViewComposition(); /// <summary>Get the width ratio to decided the horizontal location. Value in [0, 1-pageSize].</summary> /// <returns>The width ratio to decided the horizontal location.</returns> double GetWidthRatio(); /// <summary>Get the page size to decide the horizontal size. Value in [0, 1].</summary> /// <returns>The page size to decide the horizontal size.</returns> double GetWidthPageSize(); /// <summary>Get the height ratio to decided the vertical location. Value in [0, 1-pageSize].</summary> /// <returns>The height ratio to decided the vertical location.</returns> double GetHeightRatio(); /// <summary>Get the page size to decide the vertical size. Value in [0, 1].</summary> /// <returns>The page size to decide the vertical size.</returns> double GetHeightPageSize(); /// <summary>Set the width ratio to decided the horizontal location. Value in [0, 1-pageSize].</summary> /// <param name="value">The width ratio to decided the horizontal location.</param> void SetWidthRatio(double value); /// <summary>Set the page size to decide the horizontal size. Value in [0, 1].</summary> /// <param name="value">The page size to decide the horizontal size.</param> void SetWidthPageSize(double value); /// <summary>Set the height ratio to decided the vertical location. Value in [0, 1-pageSize].</summary> /// <param name="value">The height ratio to decided the vertical location.</param> void SetHeightRatio(double value); /// <summary>Set the page size to decide the vertical size. Value in [0, 1].</summary> /// <param name="value">The page size to decide the vertical size.</param> 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_ELEMENTS_GUIGRAPHICSSTACKCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSSTACKCOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Stack Compositions ***********************************************************************/ class GuiStackComposition; class GuiStackItemComposition; /// <summary> /// Represents a stack composition. /// </summary> class GuiStackComposition : public GuiBoundsComposition, public Description<GuiStackComposition> { friend class GuiStackItemComposition; typedef collections::List<GuiStackItemComposition*> ItemCompositionList; public: /// <summary>Stack item layout direction.</summary> enum Direction { /// <summary>Stack items is layouted from left to right.</summary> Horizontal, /// <summary>Stack items is layouted from top to bottom.</summary> Vertical, /// <summary>Stack items is layouted from right to left.</summary> ReversedHorizontal, /// <summary>Stack items is layouted from bottom to top.</summary> ReversedVertical, }; protected: Direction direction = Horizontal; ItemCompositionList stackItems; GuiStackItemComposition* ensuringVisibleStackItem = nullptr; vint padding = 0; vint adjustment = 0; Margin extraMargin; collections::Array<Rect> 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(); /// <summary>Get all stack items inside the stack composition.</summary> /// <returns>All stack items inside the stack composition.</returns> const ItemCompositionList& GetStackItems(); /// <summary>Insert a stack item at a specified position.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="index">The position.</param> /// <param name="item">The statck item to insert.</param> bool InsertStackItem(vint index, GuiStackItemComposition* item); /// <summary>Get the stack item layout direction.</summary> /// <returns>The stack item layout direction.</returns> Direction GetDirection(); /// <summary>Set the stack item layout direction.</summary> /// <param name="value">The stack item layout direction.</param> void SetDirection(Direction value); /// <summary>Get the stack item padding.</summary> /// <returns>The stack item padding.</returns> vint GetPadding(); /// <summary>Set the stack item padding.</summary> /// <param name="value">The stack item padding.</param> void SetPadding(vint value); void ForceCalculateSizeImmediately()override; Size GetMinPreferredClientSize()override; Rect GetBounds()override; /// <summary>Get the extra margin inside the stack composition.</summary> /// <returns>The extra margin inside the stack composition.</returns> Margin GetExtraMargin(); /// <summary>Set the extra margin inside the stack composition.</summary> /// <param name="value">The extra margin inside the stack composition.</param> void SetExtraMargin(Margin value); /// <summary>Test is any stack item clipped in the stack direction.</summary> /// <returns>Returns true if any stack item is clipped.</returns> bool IsStackItemClipped(); /// <summary>Make an item visible as complete as possible.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="index">The index of the item.</param> bool EnsureVisible(vint index); }; /// <summary> /// Represents a stack item composition of a <see cref="GuiStackComposition"/>. /// </summary> class GuiStackItemComposition : public GuiGraphicsSite, public Description<GuiStackItemComposition> { 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; /// <summary>Set the expected bounds of a stack item. In most of the cases only the size of the bounds is used.</summary> /// <param name="value">The expected bounds of a stack item.</param> void SetBounds(Rect value); /// <summary>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.</summary> /// <returns>The extra margin for this stack item.</returns> Margin GetExtraMargin(); /// <summary>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.</summary> /// <param name="value">The extra margin for this stack item.</param> void SetExtraMargin(Margin value); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSTABLECOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSTABLECOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSTABLECOMPOSITION namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Table Compositions ***********************************************************************/ class GuiTableComposition; class GuiCellComposition; class GuiTableSplitterCompositionBase; class GuiRowSplitterComposition; class GuiColumnSplitterComposition; /// <summary> /// Represnets a sizing configuration for a row or a column. /// </summary> struct GuiCellOption { /// <summary>Sizing algorithm</summary> enum ComposeType { /// <summary>Set the size to an absolute value.</summary> Absolute, /// <summary>Set the size to a percentage number of the whole table.</summary> Percentage, /// <summary>Set the size to the minimum size of the cell element.</summary> MinSize, }; /// <summary>Sizing algorithm</summary> ComposeType composeType; /// <summary>The absolute size when <see cref="GuiCellOption::composeType"/> is <see cref="ComposeType"/>::Absolute.</summary> vint absolute; /// <summary>The percentage number when <see cref="GuiCellOption::composeType"/> is <see cref="ComposeType"/>::Percentage.</summary> double percentage; GuiCellOption() :composeType(Absolute) ,absolute(20) ,percentage(0) { } bool operator==(const GuiCellOption& value){return false;} bool operator!=(const GuiCellOption& value){return true;} /// <summary>Creates an absolute sizing option</summary> /// <returns>The created option.</returns> /// <param name="value">The absolute size.</param> static GuiCellOption AbsoluteOption(vint value) { GuiCellOption option; option.composeType=Absolute; option.absolute=value; return option; } /// <summary>Creates an percantage sizing option</summary> /// <returns>The created option.</returns> /// <param name="value">The percentage number.</param> static GuiCellOption PercentageOption(double value) { GuiCellOption option; option.composeType=Percentage; option.percentage=value; return option; } /// <summary>Creates an minimum sizing option</summary> /// <returns>The created option.</returns> static GuiCellOption MinSizeOption() { GuiCellOption option; option.composeType=MinSize; return option; } }; /// <summary> /// Represents a table composition. /// </summary> class GuiTableComposition : public GuiBoundsComposition, public Description<GuiTableComposition> { 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<GuiCellOption> rowOptions; collections::Array<GuiCellOption> columnOptions; collections::Array<GuiCellComposition*> cellCompositions; collections::Array<Rect> cellBounds; collections::Array<vint> rowOffsets; collections::Array<vint> columnOffsets; collections::Array<vint> rowSizes; collections::Array<vint> 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<vint>& dimSizes, vint& dimSize, vint& dimSizeWithPercentage, collections::Array<GuiCellOption>& 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<vint>& dimSizes, vint dimSize, vint maxDimSize, collections::Array<GuiCellOption>& dimOptions ); vint UpdateCellBoundsOffsets( collections::Array<vint>& offsets, collections::Array<vint>& sizes, vint max ); void OnRenderContextChanged()override; public: GuiTableComposition(); ~GuiTableComposition(); /// <summary>Event that will be raised with row numbers, column numbers or options are changed.</summary> compositions::GuiNotifyEvent ConfigChanged; /// <summary>Get the number of rows.</summary> /// <returns>The number of rows.</returns> vint GetRows(); /// <summary>Get the number of columns.</summary> /// <returns>The number of columns.</returns> vint GetColumns(); /// <summary>Change the number of rows and columns.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="_rows">The number of rows.</param> /// <param name="_columns">The number of columns.</param> bool SetRowsAndColumns(vint _rows, vint _columns); /// <summary>Get the cell composition that covers the specified cell location.</summary> /// <returns>The cell composition that covers the specified cell location.</returns> /// <param name="_row">The number of rows.</param> /// <param name="_column">The number of columns.</param> GuiCellComposition* GetSitedCell(vint _row, vint _column); /// <summary>Get the sizing option of the specified row.</summary> /// <returns>The sizing option of the specified row.</returns> /// <param name="_row">The specified row number.</param> GuiCellOption GetRowOption(vint _row); /// <summary>Set the sizing option of the specified row.</summary> /// <param name="_row">The specified row number.</param> /// <param name="option">The sizing option of the specified row.</param> void SetRowOption(vint _row, GuiCellOption option); /// <summary>Get the sizing option of the specified column.</summary> /// <returns>The sizing option of the specified column.</returns> /// <param name="_column">The specified column number.</param> GuiCellOption GetColumnOption(vint _column); /// <summary>Set the sizing option of the specified column.</summary> /// <param name="_column">The specified column number.</param> /// <param name="option">The sizing option of the specified column.</param> void SetColumnOption(vint _column, GuiCellOption option); /// <summary>Get the cell padding. A cell padding is the distance between a table client area and a cell, or between two cells.</summary> /// <returns>The cell padding.</returns> vint GetCellPadding(); /// <summary>Set the cell padding. A cell padding is the distance between a table client area and a cell, or between two cells.</summary> /// <param name="value">The cell padding.</param> void SetCellPadding(vint value); /// <summary>Get the border visibility.</summary> /// <returns>Returns true means the border thickness equals to the cell padding, otherwise zero.</returns> bool GetBorderVisible(); /// <summary>Set the border visibility.</summary> /// <param name="value">Set to true to let the border thickness equal to the cell padding, otherwise zero.</param> void SetBorderVisible(bool value); /// <summary>Get the cell area in the space of the table's parent composition's client area.</summary> /// <returns>The cell area.</returns> Rect GetCellArea(); /// <summary>Update the sizing of the table and cells after all rows' and columns' sizing options are prepared.</summary> void UpdateCellBounds(); void ForceCalculateSizeImmediately()override; Size GetMinPreferredClientSize()override; Rect GetBounds()override; }; /// <summary> /// Represents a cell composition of a <see cref="GuiTableComposition"/>. /// </summary> class GuiCellComposition : public GuiGraphicsSite, public Description<GuiCellComposition> { 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(); /// <summary>Get the owner table composition.</summary> /// <returns>The owner table composition.</returns> GuiTableComposition* GetTableParent(); /// <summary>Get the row number for this cell composition.</summary> /// <returns>The row number for this cell composition.</returns> vint GetRow(); /// <summary>Get the total numbers of acrossed rows for this cell composition.</summary> /// <returns>The total numbers of acrossed rows for this cell composition.</returns> vint GetRowSpan(); /// <summary>Get the column number for this cell composition.</summary> /// <returns>The column number for this cell composition.</returns> vint GetColumn(); /// <summary>Get the total numbers of acrossed columns for this cell composition.</summary> /// <returns>The total numbers of acrossed columns for this cell composition.</returns> vint GetColumnSpan(); /// <summary>Set the position for this cell composition in the table.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="_row">The row number for this cell composition.</param> /// <param name="_column">The column number for this cell composition.</param> /// <param name="_rowSpan">The total numbers of acrossed rows for this cell composition.</param> /// <param name="_columnSpan">The total numbers of acrossed columns for this cell composition.</param> bool SetSite(vint _row, vint _column, vint _rowSpan, vint _columnSpan); Rect GetBounds()override; }; class GuiTableSplitterCompositionBase : public GuiGraphicsSite, public Description<GuiTableSplitterCompositionBase> { 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<vint>& 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<vint>& cellOffsets, vint Rect::* dimU1, vint Rect::* dimU2, vint Rect::* dimV1, vint Rect::* dimV2 ); public: GuiTableSplitterCompositionBase(); ~GuiTableSplitterCompositionBase(); /// <summary>Get the owner table composition.</summary> /// <returns>The owner table composition.</returns> GuiTableComposition* GetTableParent(); }; /// <summary> /// Represents a row splitter composition of a <see cref="GuiTableComposition"/>. /// </summary> class GuiRowSplitterComposition : public GuiTableSplitterCompositionBase, public Description<GuiRowSplitterComposition> { protected: vint rowsToTheTop; void OnMouseMove(GuiGraphicsComposition* sender, GuiMouseEventArgs& arguments); public: GuiRowSplitterComposition(); ~GuiRowSplitterComposition(); /// <summary>Get the number of rows that above the splitter.</summary> /// <returns>The number of rows that above the splitter.</returns> vint GetRowsToTheTop(); /// <summary>Set the number of rows that above the splitter.</summary> /// <param name="value">The number of rows that above the splitter</param> void SetRowsToTheTop(vint value); Rect GetBounds()override; }; /// <summary> /// Represents a column splitter composition of a <see cref="GuiTableComposition"/>. /// </summary> class GuiColumnSplitterComposition : public GuiTableSplitterCompositionBase, public Description<GuiColumnSplitterComposition> { protected: vint columnsToTheLeft; void OnMouseMove(GuiGraphicsComposition* sender, GuiMouseEventArgs& arguments); public: GuiColumnSplitterComposition(); ~GuiColumnSplitterComposition(); /// <summary>Get the number of columns that before the splitter.</summary> /// <returns>The number of columns that before the splitter.</returns> vint GetColumnsToTheLeft(); /// <summary>Set the number of columns that before the splitter.</summary> /// <param name="value">The number of columns that before the splitter</param> void SetColumnsToTheLeft(vint value); Rect GetBounds()override; }; } } } #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<DocumentModel> model); extern Ptr<DocumentModel> LoadDocumentFromClipboardStream(stream::IStream& stream); extern void SaveDocumentToClipboardStream(Ptr<DocumentModel> model, stream::IStream& stream); extern void SaveDocumentToRtf(Ptr<DocumentModel> model, AString& rtf); extern void SaveDocumentToRtfStream(Ptr<DocumentModel> model, stream::IStream& stream); extern void SaveDocumentToHtmlUtf8(Ptr<DocumentModel> model, AString& header, AString& content, AString& footer); extern void SaveDocumentToHtmlClipboardStream(Ptr<DocumentModel> model, stream::IStream& stream); } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSAXIS.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSAXIS #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSAXIS namespace vl { namespace presentation { namespace compositions { /*********************************************************************** Axis Interface ***********************************************************************/ /// <summary>Represents the four directions that is accessable by keyboard.</summary> enum class KeyDirection { /// <summary>The up direction.</summary> Up, /// <summary>The down direction.</summary> Down, /// <summary>The left direction.</summary> Left, /// <summary>The right direction.</summary> Right, /// <summary>The home direction.</summary> Home, /// <summary>The end direction.</summary> End, /// <summary>The page up direction.</summary> PageUp, /// <summary>The page down direction.</summary> PageDown, /// <summary>The page left direction.</summary> PageLeft, /// <summary>The page right direction.</summary> PageRight, }; /// <summary>Item coordinate transformer for a <see cref="GuiListControl"/>. 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.</summary> class IGuiAxis : public virtual IDescriptable, public Description<IGuiAxis> { public: /// <summary>Translate real size to virtual size.</summary> /// <returns>The virtual size.</returns> /// <param name="size">The real size.</param> virtual Size RealSizeToVirtualSize(Size size)=0; /// <summary>Translate virtual size to real size.</summary> /// <returns>The real size.</returns> /// <param name="size">The virtual size.</param> virtual Size VirtualSizeToRealSize(Size size)=0; /// <summary>Translate real point to virtual point.</summary> /// <returns>The virtual point.</returns> /// <param name="realFullSize">The real full size.</param> /// <param name="point">The real point.</param> virtual Point RealPointToVirtualPoint(Size realFullSize, Point point)=0; /// <summary>Translate virtual point to real point.</summary> /// <returns>The real point.</returns> /// <param name="realFullSize">The real full size.</param> /// <param name="point">The virtual point.</param> virtual Point VirtualPointToRealPoint(Size realFullSize, Point point)=0; /// <summary>Translate real bounds to virtual bounds.</summary> /// <returns>The virtual bounds.</returns> /// <param name="realFullSize">The real full size.</param> /// <param name="rect">The real bounds.</param> virtual Rect RealRectToVirtualRect(Size realFullSize, Rect rect)=0; /// <summary>Translate virtual bounds to real bounds.</summary> /// <returns>The real bounds.</returns> /// <param name="realFullSize">The real full size.</param> /// <param name="rect">The virtual bounds.</param> virtual Rect VirtualRectToRealRect(Size realFullSize, Rect rect)=0; /// <summary>Translate real margin to margin size.</summary> /// <returns>The virtual margin.</returns> /// <param name="margin">The real margin.</param> virtual Margin RealMarginToVirtualMargin(Margin margin)=0; /// <summary>Translate virtual margin to margin size.</summary> /// <returns>The real margin.</returns> /// <param name="margin">The virtual margin.</param> virtual Margin VirtualMarginToRealMargin(Margin margin)=0; /// <summary>Translate real key direction to virtual key direction.</summary> /// <returns>The virtual key direction.</returns> /// <param name="key">The real key direction.</param> virtual KeyDirection RealKeyDirectionToVirtualKeyDirection(KeyDirection key)=0; }; /*********************************************************************** Axis Implementation ***********************************************************************/ /// <summary>Default item coordinate transformer. This transformer doesn't transform any coordinate.</summary> class GuiDefaultAxis : public Object, virtual public IGuiAxis, public Description<GuiDefaultAxis> { public: /// <summary>Create the transformer.</summary> 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; }; /// <summary>Axis aligned item coordinate transformer. This transformer transforms coordinates by changing the axis direction.</summary> class GuiAxis : public Object, virtual public IGuiAxis, public Description<GuiAxis> { protected: AxisDirection axisDirection; public: /// <summary>Create the transformer with a specified axis direction.</summary> /// <param name="_axisDirection">The specified axis direction.</param> GuiAxis(AxisDirection _axisDirection); ~GuiAxis(); /// <summary>Get the specified axis direction.</summary> /// <returns>The specified axis direction.</returns> 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 /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSFLOWCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSFLOWCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSFLOWCOMPOSITION namespace vl { namespace presentation { namespace compositions { class GuiFlowComposition; class GuiFlowItemComposition; /*********************************************************************** Flow Compositions ***********************************************************************/ /// <summary> /// Alignment for a row in a flow layout /// </summary> enum class FlowAlignment { /// <summary>Align to the left.</summary> Left, /// <summary>Align to the center.</summary> Center, /// <summary>Extend to the entire row.</summary> Extend, }; /// <summary> /// Represents a flow composition. /// </summary> class GuiFlowComposition : public GuiBoundsComposition, public Description<GuiFlowComposition> { friend class GuiFlowItemComposition; typedef collections::List<GuiFlowItemComposition*> ItemCompositionList; protected: Margin extraMargin; vint rowPadding = 0; vint columnPadding = 0; FlowAlignment alignment = FlowAlignment::Left; Ptr<IGuiAxis> axis; ItemCompositionList flowItems; collections::Array<Rect> 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(); /// <summary>Get all flow items inside the flow composition.</summary> /// <returns>All flow items inside the flow composition.</returns> const ItemCompositionList& GetFlowItems(); /// <summary>Insert a flow item at a specified position.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="index">The position.</param> /// <param name="item">The flow item to insert.</param> bool InsertFlowItem(vint index, GuiFlowItemComposition* item); /// <summary>Get the extra margin inside the flow composition.</summary> /// <returns>The extra margin inside the flow composition.</returns> Margin GetExtraMargin(); /// <summary>Set the extra margin inside the flow composition.</summary> /// <param name="value">The extra margin inside the flow composition.</param> void SetExtraMargin(Margin value); /// <summary>Get the distance between rows.</summary> /// <returns>The distance between rows.</returns> vint GetRowPadding(); /// <summary>Set the distance between rows.</summary> /// <param name="value">The distance between rows.</param> void SetRowPadding(vint value); /// <summary>Get the distance between columns.</summary> /// <returns>The distance between columns.</returns> vint GetColumnPadding(); /// <summary>Set the distance between columns.</summary> /// <param name="value">The distance between columns.</param> void SetColumnPadding(vint value); /// <summary>Get the axis of the layout.</summary> /// <returns>The axis.</returns> Ptr<IGuiAxis> GetAxis(); /// <summary>Set the axis of the layout.</summary> /// <param name="value">The axis.</param> void SetAxis(Ptr<IGuiAxis> value); /// <summary>Get the alignment for rows.</summary> /// <returns>The alignment.</returns> FlowAlignment GetAlignment(); /// <summary>Set the alignment for rows.</summary> /// <param name="value">The alignment.</param> void SetAlignment(FlowAlignment value); void ForceCalculateSizeImmediately()override; Size GetMinPreferredClientSize()override; Rect GetBounds()override; }; /// <summary> /// Represnets a base line configuration for a flow item. /// </summary> struct GuiFlowOption { /// <summary>Base line calculation algorithm</summary> enum BaselineType { /// <summary>By percentage of the height from the top.</summary> Percentage, /// <summary>By a distance from the top.</summary> FromTop, /// <summary>By a distance from the bottom.</summary> FromBottom, }; /// <summary>The base line calculation algorithm.</summary> BaselineType baseline = FromBottom; /// <summary>The percentage value.</summary> double percentage = 0.0; /// <summary>The distance value.</summary> vint distance = 0; }; /// <summary> /// Represents a flow item composition of a <see cref="GuiFlowComposition"/>. /// </summary> class GuiFlowItemComposition : public GuiGraphicsSite, public Description<GuiFlowItemComposition> { 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); /// <summary>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.</summary> /// <returns>The extra margin for this flow item.</returns> Margin GetExtraMargin(); /// <summary>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.</summary> /// <param name="value">The extra margin for this flow item.</param> void SetExtraMargin(Margin value); /// <summary>Get the base line option for this flow item.</summary> /// <returns>The base line option.</returns> GuiFlowOption GetFlowOption(); /// <summary>Set the base line option for this flow item.</summary> /// <param name="value">The base line option.</param> void SetFlowOption(GuiFlowOption value); }; } } } #endif /*********************************************************************** .\GRAPHICSCOMPOSITION\GUIGRAPHICSCOMPOSITION.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Composition System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSCOMPOSITION #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSCOMPOSITION namespace vl { namespace presentation { template<typename T> using ItemProperty = Func<T(const reflection::description::Value&)>; template<typename T> using WritableItemProperty = Func<T(const reflection::description::Value&, T, bool)>; template<typename T> using TemplateProperty = Func<T*(const reflection::description::Value&)>; namespace templates { class GuiTemplate; } namespace compositions { class GuiSharedSizeItemComposition; class GuiSharedSizeRootComposition; /// <summary>A shared size composition that shares the same size with all other <see cref="GuiSharedSizeItemComposition"/> that has a same group name.</summary> class GuiSharedSizeItemComposition : public GuiBoundsComposition, public Description<GuiSharedSizeItemComposition> { protected: GuiSharedSizeRootComposition* parentRoot = nullptr; WString group; bool sharedWidth = false; bool sharedHeight = false; void Update(); void OnParentLineChanged()override; public: GuiSharedSizeItemComposition(); ~GuiSharedSizeItemComposition(); /// <summary>Get the group name of this item.</summary> /// <returns>The group name.</returns> const WString& GetGroup(); /// <summary>Set the group name of this item.</summary> /// <param name="value">The group name.</param> void SetGroup(const WString& value); /// <summary>Test is the width of this item is shared.</summary> /// <returns>Returns true if the width of this item is shared.</returns> bool GetSharedWidth(); /// <summary>Enable or disable sharing the width of this item.</summary> /// <param name="value">Set to true to share the width of this item.</param> void SetSharedWidth(bool value); /// <summary>Test is the height of this item is shared.</summary> /// <returns>Returns true if the height of this item is shared.</returns> bool GetSharedHeight(); /// <summary>Enable or disable sharing the height of this item.</summary> /// <param name="value">Set to true to share the height of this item.</param> void SetSharedHeight(bool value); }; /// <summary>A root composition that takes care of all direct or indirect <see cref="GuiSharedSizeItemComposition"/> to enable size sharing.</summary> class GuiSharedSizeRootComposition :public GuiBoundsComposition, public Description<GuiSharedSizeRootComposition> { friend class GuiSharedSizeItemComposition; protected: collections::Dictionary<WString, vint> itemWidths; collections::Dictionary<WString, vint> itemHeights; collections::List<GuiSharedSizeItemComposition*> childItems; void AddSizeComponent(collections::Dictionary<WString, vint>& sizes, const WString& group, vint sizeComponent); void CollectSizes(collections::Dictionary<WString, vint>& widths, collections::Dictionary<WString, vint>& heights); void AlignSizes(collections::Dictionary<WString, vint>& widths, collections::Dictionary<WString, vint>& heights); public: GuiSharedSizeRootComposition(); ~GuiSharedSizeRootComposition(); void ForceCalculateSizeImmediately()override; Rect GetBounds()override; }; /// <summary>A base class for all bindable repeat compositions.</summary> class GuiRepeatCompositionBase : public Object, public Description<GuiRepeatCompositionBase> { using ItemStyleProperty = TemplateProperty<templates::GuiTemplate>; using IValueEnumerable = reflection::description::IValueEnumerable; using IValueList = reflection::description::IValueList; protected: ItemStyleProperty itemTemplate; Ptr<IValueList> itemSource; Ptr<EventHandler> 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(); /// <summary>An event called after a new item is inserted.</summary> GuiItemNotifyEvent ItemInserted; /// <summary>An event called before a new item is removed.</summary> GuiItemNotifyEvent ItemRemoved; /// <summary>Get the item style provider.</summary> /// <returns>The item style provider.</returns> ItemStyleProperty GetItemTemplate(); /// <summary>Set the item style provider</summary> /// <param name="value">The new item style provider</param> void SetItemTemplate(ItemStyleProperty value); /// <summary>Get the item source.</summary> /// <returns>The item source.</returns> Ptr<IValueEnumerable> GetItemSource(); /// <summary>Set the item source.</summary> /// <param name="value">The item source. Null is acceptable if you want to clear all data.</param> void SetItemSource(Ptr<IValueEnumerable> value); }; /// <summary>Bindable stack composition.</summary> class GuiRepeatStackComposition : public GuiStackComposition, public GuiRepeatCompositionBase, public Description<GuiRepeatStackComposition> { protected: vint GetRepeatCompositionCount()override; GuiGraphicsComposition* GetRepeatComposition(vint index)override; GuiGraphicsComposition* InsertRepeatComposition(vint index)override; GuiGraphicsComposition* RemoveRepeatComposition(vint index)override; public: }; /// <summary>Bindable flow composition.</summary> class GuiRepeatFlowComposition : public GuiFlowComposition, public GuiRepeatCompositionBase, public Description<GuiRepeatFlowComposition> { protected: vint GetRepeatCompositionCount()override; GuiGraphicsComposition* GetRepeatComposition(vint index)override; GuiGraphicsComposition* InsertRepeatComposition(vint index)override; GuiGraphicsComposition* RemoveRepeatComposition(vint index)override; public: }; } } } #endif /*********************************************************************** .\GRAPHICSELEMENT\GUIGRAPHICSHOST.H ***********************************************************************/ /*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Graphics Composition Host Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSHOST #define VCZH_PRESENTATION_ELEMENTS_GUIGRAPHICSHOST namespace vl { namespace presentation { namespace controls { class GuiWindow; } namespace compositions { /*********************************************************************** Animation ***********************************************************************/ /// <summary> /// Represents a timer callback object. /// </summary> class IGuiGraphicsTimerCallback : public virtual IDescriptable, public Description<IGuiGraphicsTimerCallback> { public: /// <summary>Called periodically.</summary> /// <returns>Returns false to indicate that this callback need to be removed.</returns> virtual bool Play() = 0; }; /// <summary> /// Timer callback manager. /// </summary> class GuiGraphicsTimerManager : public Object, public Description<GuiGraphicsTimerManager> { typedef collections::List<Ptr<IGuiGraphicsTimerCallback>> CallbackList; protected: CallbackList callbacks; public: GuiGraphicsTimerManager(); ~GuiGraphicsTimerManager(); /// <summary>Add a new callback.</summary> /// <param name="callback">The new callback to add.</param> void AddCallback(Ptr<IGuiGraphicsTimerCallback> callback); /// <summary>Called periodically.</summary> void Play(); }; /*********************************************************************** Shortcut Key Manager ***********************************************************************/ class IGuiShortcutKeyManager; /// <summary>Shortcut key item.</summary> class IGuiShortcutKeyItem : public virtual IDescriptable, public Description<IGuiShortcutKeyItem> { public: /// <summary>Shortcut key executed event.</summary> GuiNotifyEvent Executed; /// <summary>Get the associated <see cref="IGuiShortcutKeyManager"/> object.</summary> /// <returns>The associated shortcut key manager.</returns> virtual IGuiShortcutKeyManager* GetManager()=0; /// <summary>Get the name represents the shortcut key combination for this item.</summary> /// <returns>The name represents the shortcut key combination for this item.</returns> virtual WString GetName()=0; }; /// <summary>Shortcut key manager item.</summary> class IGuiShortcutKeyManager : public virtual IDescriptable, public Description<IGuiShortcutKeyManager> { public: /// <summary>Get the number of shortcut key items that already attached to the manager.</summary> /// <returns>T number of shortcut key items that already attached to the manager.</returns> virtual vint GetItemCount()=0; /// <summary>Get the <see cref="IGuiShortcutKeyItem"/> associated with the index.</summary> /// <returns>The shortcut key item.</returns> /// <param name="index">The index.</param> virtual IGuiShortcutKeyItem* GetItem(vint index)=0; /// <summary>Execute shortcut key items using a key event info.</summary> /// <returns>Returns true if at least one shortcut key item is executed.</returns> /// <param name="info">The key event info.</param> virtual bool Execute(const NativeWindowKeyInfo& info)=0; }; /*********************************************************************** Alt-Combined Shortcut Key Interfaces ***********************************************************************/ class IGuiAltActionHost; /// <summary>IGuiAltAction is the handler when an alt-combined shortcut key is activated.</summary> class IGuiAltAction : public virtual IDescriptable { public: /// <summary>The identifier for this service.</summary> 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; }; /// <summary>IGuiAltActionContainer enumerates multiple <see cref="IGuiAltAction"/>.</summary> class IGuiAltActionContainer : public virtual IDescriptable { public: /// <summary>The identifier for this service.</summary> static const wchar_t* const Identifier; virtual vint GetAltActionCount() = 0; virtual IGuiAltAction* GetAltAction(vint index) = 0; }; /// <summary>IGuiAltActionHost is an alt-combined shortcut key host. A host can also be entered or leaved, with multiple sub actions enabled or disabled.</summary> class IGuiAltActionHost : public virtual IDescriptable { public: /// <summary>The identifier for this service.</summary> static const wchar_t* const Identifier; static void CollectAltActionsFromControl(controls::GuiControl* control, collections::Group<WString, IGuiAltAction*>& actions); virtual GuiGraphicsComposition* GetAltComposition() = 0; virtual IGuiAltActionHost* GetPreviousAltHost() = 0; virtual void OnActivatedAltHost(IGuiAltActionHost* previousHost) = 0; virtual void OnDeactivatedAltHost() = 0; virtual void CollectAltActions(collections::Group<WString, IGuiAltAction*>& actions) = 0; }; /*********************************************************************** Host ***********************************************************************/ /// <summary> /// GuiGraphicsHost hosts an <see cref="GuiWindowComposition"/> in an <see cref="INativeWindow"/>. The composition will fill the whole window. /// </summary> class GuiGraphicsHost : public Object, private INativeWindowListener, private INativeControllerListener, public Description<GuiGraphicsHost> { typedef collections::List<GuiGraphicsComposition*> CompositionList; typedef collections::Dictionary<WString, IGuiAltAction*> AltActionMap; typedef collections::Dictionary<WString, controls::GuiControl*> AltControlMap; typedef GuiGraphicsComposition::GraphicsHostRecord HostRecord; public: static const vuint64_t CaretInterval = 500; protected: HostRecord hostRecord; bool supressPaint = false; bool needRender = true; IGuiShortcutKeyManager* shortcutKeyManager = nullptr; controls::GuiControlHost* controlHost = nullptr; GuiWindowComposition* windowComposition = nullptr; GuiGraphicsComposition* focusedComposition = nullptr; Size previousClientSize; Size minSize; Point caretPoint; vuint64_t lastCaretTime = 0; GuiGraphicsTimerManager timerManager; GuiGraphicsComposition* mouseCaptureComposition = nullptr; CompositionList mouseEnterCompositions; IGuiAltActionHost* currentAltHost = nullptr; AltActionMap currentActiveAltActions; AltControlMap currentActiveAltTitles; WString currentAltPrefix; vint supressAltKey = 0; void EnterAltHost(IGuiAltActionHost* host); void LeaveAltHost(); bool EnterAltKey(wchar_t key); void LeaveAltKey(); void CreateAltTitles(const collections::Group<WString, IGuiAltAction*>& actions); vint FilterTitles(); void ClearAltHost(); void CloseAltHost(); 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); private: INativeWindowListener::HitTestResult HitTest(Point location)override; void Moving(Rect& bounds, bool fixSizeOnly)override; void Moved()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(); /// <summary>Get the associated window.</summary> /// <returns>The associated window.</returns> INativeWindow* GetNativeWindow(); /// <summary>Associate a window. A <see cref="GuiWindowComposition"/> will fill and appear in the window.</summary> /// <param name="_nativeWindow">The window to associated.</param> void SetNativeWindow(INativeWindow* _nativeWindow); /// <summary>Get the main <see cref="GuiWindowComposition"/>. If a window is associated, everything that put into the main composition will be shown in the window.</summary> /// <returns>The main compositoin.</returns> GuiGraphicsComposition* GetMainComposition(); /// <summary>Render the main composition and all content to the associated window.</summary> /// <param name="forceUpdate">Set to true to force updating layout and then render.</param> void Render(bool forceUpdate); /// <summary>Request a rendering</summary> void RequestRender(); /// <summary>Get the <see cref="IGuiShortcutKeyManager"/> attached with this graphics host.</summary> /// <returns>The shortcut key manager.</returns> IGuiShortcutKeyManager* GetShortcutKeyManager(); /// <summary>Attach or detach the <see cref="IGuiShortcutKeyManager"/> associated with this graphics host. When this graphics host is disposing, the associated shortcut key manager will be deleted if exists.</summary> /// <param name="value">The shortcut key manager. Set to null to detach the previous shortcut key manager from this graphics host.</param> void SetShortcutKeyManager(IGuiShortcutKeyManager* value); /// <summary>Set the focus composition. A focused composition will receive keyboard messages.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="composition">The composition to set focus. This composition should be or in the main composition.</param> bool SetFocus(GuiGraphicsComposition* composition); /// <summary>Get the focus composition. A focused composition will receive keyboard messages.</summary> /// <returns>The focus composition.</returns> GuiGraphicsComposition* GetFocusedComposition(); /// <summary>Get the caret point. A caret point is the position to place the edit box of the activated input method editor.</summary> /// <returns>The caret point.</returns> Point GetCaretPoint(); /// <summary>Set the caret point. A caret point is the position to place the edit box of the activated input method editor.</summary> /// <param name="value">The caret point.</param> /// <param name="referenceComposition">The point space. If this argument is null, the "value" argument will use the point space of the client area in the main composition.</param> void SetCaretPoint(Point value, GuiGraphicsComposition* referenceComposition=0); /// <summary>Get the timer manager.</summary> /// <returns>The timer manager.</returns> GuiGraphicsTimerManager* GetTimerManager(); /// <summary>Notify that a composition is going to disconnect from this graphics host. Generally this happens when a composition's parent line changes.</summary> /// <param name="composition">The composition to disconnect</param> void DisconnectComposition(GuiGraphicsComposition* composition); }; /*********************************************************************** Shortcut Key Manager Helpers ***********************************************************************/ class GuiShortcutKeyManager; class GuiShortcutKeyItem : public Object, public IGuiShortcutKeyItem { protected: GuiShortcutKeyManager* shortcutKeyManager; bool ctrl; bool shift; bool alt; vint key; void AttachManager(GuiShortcutKeyManager* manager); void DetachManager(GuiShortcutKeyManager* manager); public: GuiShortcutKeyItem(GuiShortcutKeyManager* _shortcutKeyManager, bool _ctrl, bool _shift, bool _alt, vint _key); ~GuiShortcutKeyItem(); IGuiShortcutKeyManager* GetManager()override; WString GetName()override; bool CanActivate(const NativeWindowKeyInfo& info); bool CanActivate(bool _ctrl, bool _shift, bool _alt, vint _key); }; /// <summary>A default implementation for <see cref="IGuiShortcutKeyManager"/>.</summary> class GuiShortcutKeyManager : public Object, public IGuiShortcutKeyManager, public Description<GuiShortcutKeyManager> { typedef collections::List<Ptr<GuiShortcutKeyItem>> ShortcutKeyItemList; protected: ShortcutKeyItemList shortcutKeyItems; public: /// <summary>Create the shortcut key manager.</summary> GuiShortcutKeyManager(); ~GuiShortcutKeyManager(); vint GetItemCount()override; IGuiShortcutKeyItem* GetItem(vint index)override; bool Execute(const NativeWindowKeyInfo& info)override; /// <summary>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.</summary> /// <returns>The created shortcut key item.</returns> /// <param name="ctrl">Set to true if the CTRL key is required.</param> /// <param name="shift">Set to true if the SHIFT key is required.</param> /// <param name="alt">Set to true if the ALT key is required.</param> /// <param name="key">The non-control key.</param> IGuiShortcutKeyItem* CreateShortcut(bool ctrl, bool shift, bool alt, vint key); /// <summary>Destroy a shortcut key item using a key combination</summary> /// <returns>Returns true if the manager destroyed a existing shortcut key item.</returns> /// <param name="ctrl">Set to true if the CTRL key is required.</param> /// <param name="shift">Set to true if the SHIFT key is required.</param> /// <param name="alt">Set to true if the ALT key is required.</param> /// <param name="key">The non-control key.</param> bool DestroyShortcut(bool ctrl, bool shift, bool alt, vint key); /// <summary>Get a shortcut key item using a key combination. If the item for the key combination does not exist, this function returns null.</summary> /// <returns>The shortcut key item.</returns> /// <param name="ctrl">Set to true if the CTRL key is required.</param> /// <param name="shift">Set to true if the SHIFT key is required.</param> /// <param name="alt">Set to true if the ALT key is required.</param> /// <param name="key">The non-control key.</param> IGuiShortcutKeyItem* TryGetShortcut(bool ctrl, bool shift, bool alt, vint key); }; } } } #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; /// <summary>The visual state for button.</summary> enum class ButtonState { /// <summary>Normal state.</summary> Normal, /// <summary>Active state (when the cursor is hovering on a button).</summary> Active, /// <summary>Pressed state (when the buttin is being pressed).</summary> Pressed, }; /// <summary>Represents the sorting state of list view items related to this column.</summary> enum class ColumnSortingState { /// <summary>Not sorted.</summary> NotSorted, /// <summary>Ascending.</summary> Ascending, /// <summary>Descending.</summary> Descending, }; /// <summary>A command executor for the combo box to change the control state.</summary> class ITextBoxCommandExecutor : public virtual IDescriptable, public Description<ITextBoxCommandExecutor> { public: /// <summary>Override the text content in the control.</summary> /// <param name="value">The new text content.</param> virtual void UnsafeSetText(const WString& value) = 0; }; /// <summary>A command executor for the combo box to change the control state.</summary> class IComboBoxCommandExecutor : public virtual IDescriptable, public Description<IComboBoxCommandExecutor> { public: /// <summary>Notify that an item is selected, the combo box should close the popup and show the text of the selected item.</summary> virtual void SelectItem() = 0; }; /// <summary>A command executor for the style controller to change the control state.</summary> class IScrollCommandExecutor : public virtual IDescriptable, public Description<IScrollCommandExecutor> { public: /// <summary>Do small decrement.</summary> virtual void SmallDecrease() = 0; /// <summary>Do small increment.</summary> virtual void SmallIncrease() = 0; /// <summary>Do big decrement.</summary> virtual void BigDecrease() = 0; /// <summary>Do big increment.</summary> virtual void BigIncrease() = 0; /// <summary>Change to total size of the scroll.</summary> /// <param name="value">The total size.</param> virtual void SetTotalSize(vint value) = 0; /// <summary>Change to page size of the scroll.</summary> /// <param name="value">The page size.</param> virtual void SetPageSize(vint value) = 0; /// <summary>Change to position of the scroll.</summary> /// <param name="value">The position.</param> virtual void SetPosition(vint value) = 0; }; /// <summary>A command executor for the style controller to change the control state.</summary> class ITabCommandExecutor : public virtual IDescriptable, public Description<ITabCommandExecutor> { public: /// <summary>Select a tab page.</summary> /// <param name="index">The specified position for the tab page.</param> virtual void ShowTab(vint index) = 0; }; /// <summary>A command executor for the style controller to change the control state.</summary> class IDatePickerCommandExecutor : public virtual IDescriptable, public Description<IDatePickerCommandExecutor> { public: /// <summary>Called when the date has been changed.</summary> virtual void NotifyDateChanged() = 0; /// <summary>Called when navigated to a date.</summary> virtual void NotifyDateNavigated() = 0; /// <summary>Called when selected a date.</summary> virtual void NotifyDateSelected() = 0; }; /// <summary>A command executor for the style controller to change the control state.</summary> class IRibbonGroupCommandExecutor : public virtual IDescriptable, public Description<IRibbonGroupCommandExecutor> { public: /// <summary>Called when the expand button is clicked.</summary> virtual void NotifyExpandButtonClicked() = 0; }; /// <summary>A command executor for the style controller to change the control state.</summary> class IRibbonGalleryCommandExecutor : public virtual IDescriptable, public Description<IRibbonGalleryCommandExecutor> { public: /// <summary>Called when the scroll up button is clicked.</summary> virtual void NotifyScrollUp() = 0; /// <summary>Called when the scroll down button is clicked.</summary> virtual void NotifyScrollDown() = 0; /// <summary>Called when the dropdown button is clicked.</summary> virtual void NotifyDropdown() = 0; }; class GuiInstanceRootObject; /// <summary> /// Represnets a component. /// </summary> class GuiComponent : public Object, public Description<GuiComponent> { public: GuiComponent(); ~GuiComponent(); virtual void Attach(GuiInstanceRootObject* rootObject); virtual void Detach(GuiInstanceRootObject* rootObject); }; /*********************************************************************** Animation ***********************************************************************/ /// <summary>Animation.</summary> class IGuiAnimation abstract : public virtual IDescriptable, public Description<IGuiAnimation> { public: /// <summary>Called when the animation is about to play the first frame.</summary> virtual void Start() = 0; /// <summary>Called when the animation is about to pause.</summary> virtual void Pause() = 0; /// <summary>Called when the animation is about to resume.</summary> virtual void Resume() = 0; /// <summary>Play the animation. The animation should calculate the time itself to determine the content of the current state of animating objects.</summary> virtual void Run() = 0; /// <summary>Test if the animation has ended.</summary> /// <returns>Returns true if the animation has ended.</returns> virtual bool GetStopped() = 0; /// <summary>Create a finite animation.</summary> /// <returns>Returns the created animation.</returns> /// <param name="run">The animation callback for each frame.</param> /// <param name="milliseconds">The length of the animation.</param> static Ptr<IGuiAnimation> CreateAnimation(const Func<void(vuint64_t)>& run, vuint64_t milliseconds); /// <summary>Create an infinite animation.</summary> /// <returns>Returns the created animation.</returns> /// <param name="run">The animation callback for each frame.</param> static Ptr<IGuiAnimation> CreateAnimation(const Func<void(vuint64_t)>& run); }; /*********************************************************************** Root Object ***********************************************************************/ class RootObjectTimerCallback; /// <summary>Represnets a root GUI object.</summary> class GuiInstanceRootObject abstract : public Description<GuiInstanceRootObject> { friend class RootObjectTimerCallback; typedef collections::List<Ptr<description::IValueSubscription>> SubscriptionList; protected: Ptr<GuiResourcePathResolver> resourceResolver; SubscriptionList subscriptions; collections::SortedList<GuiComponent*> components; Ptr<RootObjectTimerCallback> timerCallback; collections::SortedList<Ptr<IGuiAnimation>> runningAnimations; collections::SortedList<Ptr<IGuiAnimation>> 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(); /// <summary>Clear all subscriptions and components.</summary> void FinalizeInstance(); /// <summary>Test has the object been finalized.</summary> /// <returns>Returns true if this object has been finalized.</returns> bool IsFinalized(); void FinalizeInstanceRecursively(templates::GuiTemplate* thisObject); void FinalizeInstanceRecursively(GuiCustomControl* thisObject); void FinalizeInstanceRecursively(GuiControlHost* thisObject); void FinalizeGeneralInstance(GuiInstanceRootObject* thisObject); /// <summary>Set the resource resolver to connect the current root object to the resource creating it.</summary> /// <param name="resolver">The resource resolver</param> void SetResourceResolver(Ptr<GuiResourcePathResolver> resolver); /// <summary>Resolve a resource using the current resource resolver.</summary> /// <returns>The loaded resource. Returns null if failed to load.</returns> /// <param name="protocol">The protocol.</param> /// <param name="path">The path.</param> /// <param name="ensureExist">Set to true and it will throw an exception if the resource doesn't exist.</param> Ptr<DescriptableObject> ResolveResource(const WString& protocol, const WString& path, bool ensureExist); /// <summary>Add a subscription. When this control host is disposing, all attached subscriptions will be deleted.</summary> /// <returns>Returns null if this operation failed.</returns> /// <param name="subscription">The subscription to test.</param> Ptr<description::IValueSubscription> AddSubscription(Ptr<description::IValueSubscription> subscription); /// <summary>Clear all subscriptions.</summary> void UpdateSubscriptions(); /// <summary>Add a component. When this control host is disposing, all attached components will be deleted.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="component">The component to add.</param> bool AddComponent(GuiComponent* component); /// <summary>Add a control host as a component. When this control host is disposing, all attached components will be deleted.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="controlHost">The controlHost to add.</param> bool AddControlHostComponent(GuiControlHost* controlHost); /// <summary>Add an animation. The animation will be paused if the root object is removed from a window.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="animation">The animation.</param> bool AddAnimation(Ptr<IGuiAnimation> animation); /// <summary>Kill an animation.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="animation">The animation.</param> bool KillAnimation(Ptr<IGuiAnimation> 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<IGuiAnimationCoroutine> { public: class IImpl : public virtual IGuiAnimation, public Description<IImpl> { public: virtual void OnPlayAndWait(Ptr<IGuiAnimation> animation) = 0; virtual void OnPlayInGroup(Ptr<IGuiAnimation> animation, vint groupId) = 0; virtual void OnWaitForGroup(vint groupId) = 0; }; typedef Func<Ptr<description::ICoroutine>(IImpl*)> Creator; static void WaitAndPause(IImpl* impl, vuint64_t milliseconds); static void PlayAndWaitAndPause(IImpl* impl, Ptr<IGuiAnimation> animation); static void PlayInGroupAndPause(IImpl* impl, Ptr<IGuiAnimation> animation, vint groupId); static void WaitForGroupAndPause(IImpl* impl, vint groupId); static void ReturnAndExit(IImpl* impl); static Ptr<IGuiAnimation> Create(const Creator& creator); }; } } } #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<CLASS>\ {\ 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 ***********************************************************************/ /// <summary>Represents a user customizable template.</summary> class GuiTemplate : public compositions::GuiBoundsComposition, public controls::GuiInstanceRootObject, public Description<GuiTemplate> { protected: controls::GuiControlHost* GetControlHostForInstance()override; void OnParentLineChanged()override; public: /// <summary>Create a template.</summary> 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<GuiListItemTemplate> { 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)\ #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<DocumentModel>, 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, CustomizedBorder, false)\ F(GuiWindowTemplate, bool, Maximized, false)\ F(GuiWindowTemplate, TemplateProperty<GuiWindowTemplate>, TooltipTemplate, {})\ F(GuiWindowTemplate, TemplateProperty<GuiLabelTemplate>, ShortcutKeyTemplate, {})\ F(GuiWindowTemplate, bool, CustomFrameEnabled, true)\ #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<GuiMenuTemplate>, SubMenuTemplate, {})\ F(GuiToolstripButtonTemplate, bool, SubMenuExisting, false)\ F(GuiToolstripButtonTemplate, bool, SubMenuOpening, false)\ F(GuiToolstripButtonTemplate, controls::GuiButton*, SubMenuHost, nullptr)\ F(GuiToolstripButtonTemplate, Ptr<GuiImageData>, LargeImage, {})\ F(GuiToolstripButtonTemplate, Ptr<GuiImageData>, Image, {})\ F(GuiToolstripButtonTemplate, WString, ShortcutText, {})\ #define GuiListViewColumnHeaderTemplate_PROPERTIES(F)\ F(GuiListViewColumnHeaderTemplate, controls::ColumnSortingState, SortingState, controls::ColumnSortingState::NotSorted)\ #define GuiComboBoxTemplate_PROPERTIES(F)\ F(GuiComboBoxTemplate, controls::IComboBoxCommandExecutor*, Commands, nullptr)\ 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<DocumentModel>, BaselineDocument, {})\ F(GuiDocumentViewerTemplate, Color, CaretColor, {})\ #define GuiListControlTemplate_PROPERTIES(F)\ F(GuiListControlTemplate, TemplateProperty<GuiSelectableButtonTemplate>, BackgroundTemplate, {})\ #define GuiTextListTemplate_PROPERTIES(F)\ F(GuiTextListTemplate, Color, TextColor, {})\ F(GuiTextListTemplate, TemplateProperty<GuiSelectableButtonTemplate>, CheckBulletTemplate, {})\ F(GuiTextListTemplate, TemplateProperty<GuiSelectableButtonTemplate>, RadioBulletTemplate, {})\ #define GuiListViewTemplate_PROPERTIES(F)\ F(GuiListViewTemplate, TemplateProperty<GuiListViewColumnHeaderTemplate>, ColumnHeaderTemplate, {})\ F(GuiListViewTemplate, Color, PrimaryTextColor, {})\ F(GuiListViewTemplate, Color, SecondaryTextColor, {})\ F(GuiListViewTemplate, Color, ItemSeparatorColor, {})\ #define GuiTreeViewTemplate_PROPERTIES(F)\ F(GuiTreeViewTemplate, TemplateProperty<GuiSelectableButtonTemplate>, ExpandingDecoratorTemplate, {})\ F(GuiTreeViewTemplate, Color, TextColor, {})\ #define GuiTabTemplate_PROPERTIES(F)\ F(GuiTabTemplate, controls::ITabCommandExecutor*, Commands, nullptr)\ F(GuiTabTemplate, Ptr<reflection::description::IValueObservableList>, TabPages, {})\ F(GuiTabTemplate, controls::GuiTabPage*, SelectedTabPage, nullptr)\ #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<GuiDatePickerTemplate>, 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<GuiToolstripButtonTemplate>, LargeDropdownButtonTemplate, {})\ F(GuiRibbonGroupTemplate, TemplateProperty<GuiMenuTemplate>, SubMenuTemplate, {})\ #define GuiRibbonIconLabelTemplate_PROPERTIES(F)\ F(GuiRibbonIconLabelTemplate, Ptr<GuiImageData>, Image, {})\ #define GuiRibbonButtonsTemplate_PROPERTIES(F)\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, LargeButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, LargeDropdownButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, LargeSplitButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, SmallButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, SmallDropdownButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, SmallSplitButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, SmallIconLabelTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, IconButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, IconDropdownButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, IconSplitButtonTemplate, {})\ F(GuiRibbonButtonsTemplate, TemplateProperty<GuiToolstripButtonTemplate>, IconLabelTemplate, {})\ #define GuiRibbonToolstripsTemplate_PROPERTIES(F)\ F(GuiRibbonToolstripsTemplate, TemplateProperty<GuiControlTemplate>, 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<GuiTextListTemplate>, ItemListTemplate, {})\ F(GuiRibbonGalleryListTemplate, TemplateProperty<GuiRibbonToolstripMenuTemplate>, MenuTemplate, {})\ F(GuiRibbonGalleryListTemplate, TemplateProperty<GuiControlTemplate>, HeaderTemplate, {})\ F(GuiRibbonGalleryListTemplate, TemplateProperty<GuiSelectableButtonTemplate>, BackgroundTemplate, {})\ F(GuiRibbonGalleryListTemplate, TemplateProperty<GuiScrollViewTemplate>, 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<GuiImageData>, Image, {})\ #define GuiGridCellTemplate_PROPERTIES(F)\ F(GuiGridCellTemplate, Color, PrimaryTextColor, {})\ F(GuiGridCellTemplate, Color, SecondaryTextColor, {})\ F(GuiGridCellTemplate, Color, ItemSeparatorColor, {})\ F(GuiGridCellTemplate, Ptr<GuiImageData>, LargeImage, {})\ F(GuiGridCellTemplate, Ptr<GuiImageData>, 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 { /*********************************************************************** Basic Construction ***********************************************************************/ /// <summary> /// 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. /// </summary> class GuiControl : public Object, protected compositions::IGuiAltAction, public Description<GuiControl> { friend class compositions::GuiGraphicsComposition; protected: using ControlList = collections::List<GuiControl*>; using ControlTemplatePropertyType = TemplateProperty<templates::GuiControlTemplate>; private: theme::ThemeName controlThemeName; ControlTemplatePropertyType controlTemplate; templates::GuiControlTemplate* controlTemplateObject = nullptr; protected: compositions::GuiBoundsComposition* boundsComposition = nullptr; compositions::GuiBoundsComposition* containerComposition = nullptr; compositions::GuiGraphicsComposition* focusableComposition = nullptr; compositions::GuiGraphicsEventReceiver* eventReceiver = nullptr; bool isEnabled = true; bool isVisuallyEnabled = true; bool isVisible = true; WString alt; WString text; FontProperties font; description::Value context; compositions::IGuiAltActionHost* activatingAltHost = nullptr; GuiControl* parent = nullptr; ControlList children; description::Value tag; GuiControl* tooltipControl = nullptr; vint tooltipWidth = 0; Ptr<bool> flagDisposed; 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 OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget); virtual void OnBeforeReleaseGraphicsHost(); virtual void UpdateVisuallyEnabled(); void SetFocusableComposition(compositions::GuiGraphicsComposition* value); bool IsAltEnabled()override; bool IsAltAvailable()override; compositions::GuiGraphicsComposition* GetAltComposition()override; compositions::IGuiAltActionHost* GetActivatingAltHost()override; void OnActiveAlt()override; static bool SharedPtrDestructorProc(DescriptableObject* obj, bool forceDisposing); public: using ControlTemplateType = templates::GuiControlTemplate; /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiControl(theme::ThemeName themeName); ~GuiControl(); /// <summary>Theme name changed event. This event will be raised when the theme name is changed.</summary> compositions::GuiNotifyEvent ControlThemeNameChanged; /// <summary>Control template changed event. This event will be raised when the control template is changed.</summary> compositions::GuiNotifyEvent ControlTemplateChanged; /// <summary>Render target changed event. This event will be raised when the render target of the control is changed.</summary> compositions::GuiNotifyEvent RenderTargetChanged; /// <summary>Visible event. This event will be raised when the visibility state of the control is changed.</summary> compositions::GuiNotifyEvent VisibleChanged; /// <summary>Enabled event. This event will be raised when the enabling state of the control is changed.</summary> compositions::GuiNotifyEvent EnabledChanged; /// <summary> /// Enabled event. This event will be raised 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. /// </summary> compositions::GuiNotifyEvent VisuallyEnabledChanged; /// <summary>Alt changed event. This event will be raised when the associated Alt-combined shortcut key of the control is changed.</summary> compositions::GuiNotifyEvent AltChanged; /// <summary>Text changed event. This event will be raised when the text of the control is changed.</summary> compositions::GuiNotifyEvent TextChanged; /// <summary>Font changed event. This event will be raised when the font of the control is changed.</summary> compositions::GuiNotifyEvent FontChanged; /// <summary>Context changed event. This event will be raised when the font of the control is changed.</summary> compositions::GuiNotifyEvent ContextChanged; void InvokeOrDelayIfRendering(Func<void()> proc); /// <summary>A function to create the argument for notify events that raised by itself.</summary> /// <returns>The created argument.</returns> compositions::GuiEventArgs GetNotifyEventArguments(); /// <summary>Get the associated theme name.</summary> /// <returns>The theme name.</returns> theme::ThemeName GetControlThemeName(); /// <summary>Set the associated control theme name.</summary> /// <param name="value">The theme name.</param> void SetControlThemeName(theme::ThemeName value); /// <summary>Get the associated control template.</summary> /// <returns>The control template.</returns> ControlTemplatePropertyType GetControlTemplate(); /// <summary>Set the associated control template.</summary> /// <param name="value">The control template.</param> void SetControlTemplate(const ControlTemplatePropertyType& value); /// <summary>Set the associated control theme name and template and the same time.</summary> /// <param name="themeNameValue">The theme name.</param> /// <param name="controlTemplateValue">The control template.</param> void SetControlThemeNameAndTemplate(theme::ThemeName themeNameValue, const ControlTemplatePropertyType& controlTemplateValue); /// <summary>Get the associated style controller.</summary> /// <returns>The associated style controller.</returns> templates::GuiControlTemplate* GetControlTemplateObject(); /// <summary>Get the bounds composition for the control.</summary> /// <returns>The bounds composition.</returns> compositions::GuiBoundsComposition* GetBoundsComposition(); /// <summary>Get the container composition for the control.</summary> /// <returns>The container composition.</returns> compositions::GuiGraphicsComposition* GetContainerComposition(); /// <summary>Get the focusable composition for the control. A focusable composition is the composition to be focused when the control is focused.</summary> /// <returns>The focusable composition.</returns> compositions::GuiGraphicsComposition* GetFocusableComposition(); /// <summary>Get the parent control.</summary> /// <returns>The parent control.</returns> GuiControl* GetParent(); /// <summary>Get the number of child controls.</summary> /// <returns>The number of child controls.</returns> vint GetChildrenCount(); /// <summary>Get the child control using a specified index.</summary> /// <returns>The child control.</returns> /// <param name="index">The specified index.</param> GuiControl* GetChild(vint index); /// <summary>Put another control in the container composition of this control.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="control">The control to put in this control.</param> bool AddChild(GuiControl* control); /// <summary>Test if a control owned by this control.</summary> /// <returns>Returns true if the control is owned by this control.</returns> /// <param name="control">The control to test.</param> bool HasChild(GuiControl* control); /// <summary>Get the <see cref="GuiControlHost"/> that contains this control.</summary> /// <returns>The <see cref="GuiControlHost"/> that contains this control.</returns> virtual GuiControlHost* GetRelatedControlHost(); /// <summary>Test if this control is rendered as enabled.</summary> /// <returns>Returns true if this control is rendered as enabled.</returns> virtual bool GetVisuallyEnabled(); /// <summary>Test if this control is enabled.</summary> /// <returns>Returns true if this control is enabled.</returns> virtual bool GetEnabled(); /// <summary>Make the control enabled or disabled.</summary> /// <param name="value">Set to true to make the control enabled.</param> virtual void SetEnabled(bool value); /// <summary>Test if this visible or invisible.</summary> /// <returns>Returns true if this control is visible.</returns> virtual bool GetVisible(); /// <summary>Make the control visible or invisible.</summary> /// <param name="value">Set to true to make the visible enabled.</param> virtual void SetVisible(bool value); /// <summary>Get the Alt-combined shortcut key associated with this control.</summary> /// <returns>The Alt-combined shortcut key associated with this control.</returns> virtual const WString& GetAlt()override; /// <summary>Associate a Alt-combined shortcut key with this control.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The Alt-combined shortcut key to associate. Only zero, sigle or multiple upper case letters are legal.</param> virtual bool SetAlt(const WString& value); /// <summary>Make the control as the parent of multiple Alt-combined shortcut key activatable controls.</summary> /// <param name="host">The alt action host object.</param> void SetActivatingAltHost(compositions::IGuiAltActionHost* host); /// <summary>Get the text to display on the control.</summary> /// <returns>The text to display on the control.</returns> virtual const WString& GetText(); /// <summary>Set the text to display on the control.</summary> /// <param name="value">The text to display on the control.</param> virtual void SetText(const WString& value); /// <summary>Get the font to render the text.</summary> /// <returns>The font to render the text.</returns> virtual const FontProperties& GetFont(); /// <summary>Set the font to render the text.</summary> /// <param name="value">The font to render the text.</param> virtual void SetFont(const FontProperties& value); /// <summary>Get the context of this control. The control template and all item templates (if it has) will see this context property.</summary> /// <returns>The context of this context.</returns> virtual description::Value GetContext(); /// <summary>Set the context of this control.</summary> /// <param name="value">The context of this control.</param> virtual void SetContext(const description::Value& value); /// <summary>Focus this control.</summary> virtual void SetFocus(); /// <summary>Get the tag object of the control.</summary> /// <returns>The tag object of the control.</returns> description::Value GetTag(); /// <summary>Set the tag object of the control.</summary> /// <param name="value">The tag object of the control.</param> void SetTag(const description::Value& value); /// <summary>Get the tooltip control of the control.</summary> /// <returns>The tooltip control of the control.</returns> GuiControl* GetTooltipControl(); /// <summary>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.</summary> /// <returns>The old tooltip control.</returns> /// <param name="value">The tooltip control of the control.</param> GuiControl* SetTooltipControl(GuiControl* value); /// <summary>Get the tooltip width of the control.</summary> /// <returns>The tooltip width of the control.</returns> vint GetTooltipWidth(); /// <summary>Set the tooltip width of the control.</summary> /// <param name="value">The tooltip width of the control.</param> void SetTooltipWidth(vint value); /// <summary>Display the tooltip.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="location">The relative location to specify the left-top position of the tooltip.</param> bool DisplayTooltip(Point location); /// <summary>Close the tooltip that owned by this control.</summary> void CloseTooltip(); /// <summary>Query a service using an identifier. If you want to get a service of type IXXX, use IXXX::Identifier as the identifier.</summary> /// <returns>The requested service. If the control doesn't support this service, it will be null.</returns> /// <param name="identifier">The identifier.</param> virtual IDescriptable* QueryService(const WString& identifier); template<typename T> T* QueryTypedService() { return dynamic_cast<T*>(QueryService(T::Identifier)); } }; /// <summary>Represnets a user customizable control.</summary> class GuiCustomControl : public GuiControl, public GuiInstanceRootObject, public AggregatableDescription<GuiCustomControl> { protected: controls::GuiControlHost* GetControlHostForInstance()override; void OnParentLineChanged()override; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiCustomControl(theme::ThemeName themeName); ~GuiCustomControl(); }; template<typename T> class GuiObjectComponent : public GuiComponent { public: Ptr<T> object; GuiObjectComponent() { } GuiObjectComponent(Ptr<T> _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<templates::Gui##TEMPLATE*>(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* GetControlTemplateObject(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 ***********************************************************************/ /// <summary>A control with 3 phases state transffering when mouse click happens.</summary> class GuiButton : public GuiControl, public Description<GuiButton> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ButtonTemplate, GuiControl) protected: bool clickOnMouseUp = true; bool mousePressing = false; bool mouseHoving = false; ButtonState controlState = ButtonState::Normal; void OnParentLineChanged()override; void OnActiveAlt()override; void UpdateControlState(); 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); public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiButton(theme::ThemeName themeName); ~GuiButton(); /// <summary>Mouse click event.</summary> compositions::GuiNotifyEvent Clicked; /// <summary>Test is the <see cref="Clicked"/> event raised when left mouse button up.</summary> /// <returns>Returns true if this event is raised when left mouse button up</returns> bool GetClickOnMouseUp(); /// <summary>Set is the <see cref="Clicked"/> event raised when left mouse button up or not.</summary> /// <param name="value">Set to true to make this event raised when left mouse button up</param> void SetClickOnMouseUp(bool value); }; /// <summary>A <see cref="GuiButton"/> with a selection state.</summary> class GuiSelectableButton : public GuiButton, public Description<GuiSelectableButton> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(SelectableButtonTemplate, GuiButton) public: /// <summary>Selection group controller. Control the selection state of all attached button.</summary> class GroupController : public GuiComponent, public Description<GroupController> { protected: collections::List<GuiSelectableButton*> buttons; public: GroupController(); ~GroupController(); /// <summary>Called when the group controller is attached to a <see cref="GuiSelectableButton"/>. use [M:vl.presentation.controls.GuiSelectableButton.SetGroupController] to attach or detach a group controller to or from a selectable button.</summary> /// <param name="button">The button to attach.</param> virtual void Attach(GuiSelectableButton* button); /// <summary>Called when the group controller is deteched to a <see cref="GuiSelectableButton"/>. use [M:vl.presentation.controls.GuiSelectableButton.SetGroupController] to attach or detach a group controller to or from a selectable button.</summary> /// <param name="button">The button to detach.</param> virtual void Detach(GuiSelectableButton* button); /// <summary>Called when the selection state of any <see cref="GuiSelectableButton"/> changed.</summary> /// <param name="button">The button that changed the selection state.</param> virtual void OnSelectedChanged(GuiSelectableButton* button) = 0; }; /// <summary>A mutex group controller, usually for radio buttons.</summary> class MutexGroupController : public GroupController, public Description<MutexGroupController> { 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: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiSelectableButton(theme::ThemeName themeName); ~GuiSelectableButton(); /// <summary>Group controller changed event.</summary> compositions::GuiNotifyEvent GroupControllerChanged; /// <summary>Auto selection changed event.</summary> compositions::GuiNotifyEvent AutoSelectionChanged; /// <summary>Selected changed event.</summary> compositions::GuiNotifyEvent SelectedChanged; /// <summary>Get the attached group controller.</summary> /// <returns>The attached group controller.</returns> virtual GroupController* GetGroupController(); /// <summary>Set the attached group controller.</summary> /// <param name="value">The attached group controller.</param> virtual void SetGroupController(GroupController* value); /// <summary>Get the auto selection state. True if the button is automatically selected or unselected when the button is clicked.</summary> /// <returns>The auto selection state.</returns> virtual bool GetAutoSelection(); /// <summary>Set the auto selection state. True if the button is automatically selected or unselected when the button is clicked.</summary> /// <param name="value">The auto selection state.</param> virtual void SetAutoSelection(bool value); /// <summary>Get the selected state.</summary> /// <returns>The selected state.</returns> virtual bool GetSelected(); /// <summary>Set the selected state.</summary> /// <param name="value">The selected state.</param> 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 { /*********************************************************************** Dialogs ***********************************************************************/ /// <summary>Base class for dialogs.</summary> class GuiDialogBase abstract : public GuiComponent, public Description<GuiDialogBase> { protected: GuiInstanceRootObject* rootObject = nullptr; GuiWindow* GetHostWindow(); public: GuiDialogBase(); ~GuiDialogBase(); void Attach(GuiInstanceRootObject* _rootObject); void Detach(GuiInstanceRootObject* _rootObject); }; /// <summary>Message dialog.</summary> class GuiMessageDialog : public GuiDialogBase, public Description<GuiMessageDialog> { 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: /// <summary>Create a message dialog.</summary> GuiMessageDialog(); ~GuiMessageDialog(); /// <summary>Get the button combination that appear on the dialog.</summary> /// <returns>The button combination.</returns> INativeDialogService::MessageBoxButtonsInput GetInput(); /// <summary>Set the button combination that appear on the dialog.</summary> /// <param name="value">The button combination.</param> void SetInput(INativeDialogService::MessageBoxButtonsInput value); /// <summary>Get the default button for the selected button combination.</summary> /// <returns>The default button.</returns> INativeDialogService::MessageBoxDefaultButton GetDefaultButton(); /// <summary>Set the default button for the selected button combination.</summary> /// <param name="value">The default button.</param> void SetDefaultButton(INativeDialogService::MessageBoxDefaultButton value); /// <summary>Get the icon that appears on the dialog.</summary> /// <returns>The icon.</returns> INativeDialogService::MessageBoxIcons GetIcon(); /// <summary>Set the icon that appears on the dialog.</summary> /// <param name="value">The icon.</param> void SetIcon(INativeDialogService::MessageBoxIcons value); /// <summary>Get the way that how this dialog disable windows of the current process.</summary> /// <returns>The way that how this dialog disable windows of the current process.</returns> INativeDialogService::MessageBoxModalOptions GetModalOption(); /// <summary>Set the way that how this dialog disable windows of the current process.</summary> /// <param name="value">The way that how this dialog disable windows of the current process.</param> void SetModalOption(INativeDialogService::MessageBoxModalOptions value); /// <summary>Get the text for the dialog.</summary> /// <returns>The text.</returns> const WString& GetText(); /// <summary>Set the text for the dialog.</summary> /// <param name="value">The text.</param> void SetText(const WString& value); /// <summary>Get the title for the dialog.</summary> /// <returns>The title.</returns> const WString& GetTitle(); /// <summary>Set the title for the dialog. If the title is empty, the dialog will use the title of the window that host this dialog.</summary> /// <param name="value">The title.</param> void SetTitle(const WString& value); /// <summary>Show the dialog.</summary> /// <returns>Returns the clicked button.</returns> INativeDialogService::MessageBoxButtonsOutput ShowDialog(); }; /// <summary>Color dialog.</summary> class GuiColorDialog : public GuiDialogBase, public Description<GuiColorDialog> { protected: bool enabledCustomColor = true; bool openedCustomColor = false; Color selectedColor; bool showSelection = true; collections::List<Color> customColors; public: /// <summary>Create a color dialog.</summary> GuiColorDialog(); ~GuiColorDialog(); /// <summary>Selected color changed event.</summary> compositions::GuiNotifyEvent SelectedColorChanged; /// <summary>Get if the custom color panel is enabled for the dialog.</summary> /// <returns>Returns true if the color panel is enabled for the dialog.</returns> bool GetEnabledCustomColor(); /// <summary>Set if custom color panel is enabled for the dialog.</summary> /// <param name="value">Set to true to enable the custom color panel for the dialog.</param> void SetEnabledCustomColor(bool value); /// <summary>Get if the custom color panel is opened by default when it is enabled.</summary> /// <returns>Returns true if the custom color panel is opened by default.</returns> bool GetOpenedCustomColor(); /// <summary>Set if the custom color panel is opened by default when it is enabled.</summary> /// <param name="value">Set to true to open custom color panel by default if it is enabled.</param> void SetOpenedCustomColor(bool value); /// <summary>Get the selected color.</summary> /// <returns>The selected color.</returns> Color GetSelectedColor(); /// <summary>Set the selected color.</summary> /// <param name="value">The selected color.</param> void SetSelectedColor(Color value); /// <summary>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.</summary> /// <returns>The list to access custom colors on the palette.</returns> collections::List<Color>& GetCustomColors(); /// <summary>Show the dialog.</summary> /// <returns>Returns true if the "OK" button is clicked.</returns> bool ShowDialog(); }; /// <summary>Font dialog.</summary> class GuiFontDialog : public GuiDialogBase, public Description<GuiFontDialog> { protected: FontProperties selectedFont; Color selectedColor; bool showSelection = true; bool showEffect = true; bool forceFontExist = true; public: /// <summary>Create a font dialog.</summary> GuiFontDialog(); ~GuiFontDialog(); /// <summary>Selected font changed event.</summary> compositions::GuiNotifyEvent SelectedFontChanged; /// <summary>Selected color changed event.</summary> compositions::GuiNotifyEvent SelectedColorChanged; /// <summary>Get the selected font.</summary> /// <returns>The selected font.</returns> const FontProperties& GetSelectedFont(); /// <summary>Set the selected font.</summary> /// <param name="value">The selected font.</param> void SetSelectedFont(const FontProperties& value); /// <summary>Get the selected color.</summary> /// <returns>The selected color.</returns> Color GetSelectedColor(); /// <summary>Set the selected color.</summary> /// <param name="value">The selected color.</param> void SetSelectedColor(Color value); /// <summary>Get if the selected font is already selected on the dialog when it is opened.</summary> /// <returns>Returns true if the selected font is already selected on the dialog when it is opened.</returns> bool GetShowSelection(); /// <summary>Set if the selected font is already selected on the dialog when it is opened.</summary> /// <param name="value">Set to true to select the selected font when the dialog is opened.</param> void SetShowSelection(bool value); /// <summary>Get if the font preview is enabled.</summary> /// <returns>Returns true if the font preview is enabled.</returns> bool GetShowEffect(); /// <summary>Set if the font preview is enabled.</summary> /// <param name="value">Set to true to enable the font preview.</param> void SetShowEffect(bool value); /// <summary>Get if the dialog only accepts an existing font.</summary> /// <returns>Returns true if the dialog only accepts an existing font.</returns> bool GetForceFontExist(); /// <summary>Set if the dialog only accepts an existing font.</summary> /// <param name="value">Set to true to let the dialog only accept an existing font.</param> void SetForceFontExist(bool value); /// <summary>Show the dialog.</summary> /// <returns>Returns true if the "OK" button is clicked.</returns> bool ShowDialog(); }; /// <summary>Base class for file dialogs.</summary> class GuiFileDialogBase abstract : public GuiDialogBase, public Description<GuiFileDialogBase> { 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(); /// <summary>File name changed event.</summary> compositions::GuiNotifyEvent FileNameChanged; /// <summary>Filter index changed event.</summary> compositions::GuiNotifyEvent FilterIndexChanged; /// <summary>Get the filter.</summary> /// <returns>The filter.</returns> const WString& GetFilter(); /// <summary>Set the filter. The filter is formed by pairs of filter name and wildcard concatenated by "|", like "Text Files (*.txt)|*.txt|All Files (*.*)|*.*".</summary> /// <param name="value">The filter.</param> void SetFilter(const WString& value); /// <summary>Get the filter index.</summary> /// <returns>The filter index.</returns> vint GetFilterIndex(); /// <summary>Set the filter index.</summary> /// <param name="value">The filter index.</param> void SetFilterIndex(vint value); /// <summary>Get if the file preview is enabled.</summary> /// <returns>Returns true if the file preview is enabled.</returns> bool GetEnabledPreview(); /// <summary>Set if the file preview is enabled.</summary> /// <param name="value">Set to true to enable the file preview.</param> void SetEnabledPreview(bool value); /// <summary>Get the title.</summary> /// <returns>The title.</returns> WString GetTitle(); /// <summary>Set the title.</summary> /// <param name="value">The title.</param> void SetTitle(const WString& value); /// <summary>Get the selected file name.</summary> /// <returns>The selected file name.</returns> WString GetFileName(); /// <summary>Set the selected file name.</summary> /// <param name="value">The selected file name.</param> void SetFileName(const WString& value); /// <summary>Get the default folder.</summary> /// <returns>The default folder.</returns> WString GetDirectory(); /// <summary>Set the default folder.</summary> /// <param name="value">The default folder.</param> void SetDirectory(const WString& value); /// <summary>Get the default file extension.</summary> /// <returns>The default file extension.</returns> WString GetDefaultExtension(); /// <summary>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.</summary> /// <param name="value">The default file extension.</param> void SetDefaultExtension(const WString& value); /// <summary>Get the dialog options.</summary> /// <returns>The dialog options.</returns> INativeDialogService::FileDialogOptions GetOptions(); /// <summary>Set the dialog options.</summary> /// <param name="value">The dialog options.</param> void SetOptions(INativeDialogService::FileDialogOptions value); }; /// <summary>Open file dialog.</summary> class GuiOpenFileDialog : public GuiFileDialogBase, public Description<GuiOpenFileDialog> { protected: collections::List<WString> fileNames; public: /// <summary>Create a open file dialog.</summary> GuiOpenFileDialog(); ~GuiOpenFileDialog(); /// <summary>Get the list to access multiple selected file names.</summary> /// <returns>The list to access multiple selected file names.</returns> collections::List<WString>& GetFileNames(); /// <summary>Show the dialog.</summary> /// <returns>Returns true if the "Open" button is clicked.</returns> bool ShowDialog(); }; /// <summary>Save file dialog.</summary> class GuiSaveFileDialog : public GuiFileDialogBase, public Description<GuiSaveFileDialog> { public: /// <summary>Create a save file dialog.</summary> GuiSaveFileDialog(); ~GuiSaveFileDialog(); /// <summary>Show the dialog.</summary> /// <returns>Returns true if the "Save" button is clicked.</returns> 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 ***********************************************************************/ /// <summary>A control to display a text.</summary> class GuiLabel : public GuiControl, public Description<GuiLabel> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(LabelTemplate, GuiControl) protected: Color textColor; bool textColorConsisted = true; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiLabel(theme::ThemeName themeName); ~GuiLabel(); /// <summary>Get the text color.</summary> /// <returns>The text color.</returns> Color GetTextColor(); /// <summary>Set the text color.</summary> /// <param name="value">The text color.</param> 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 ***********************************************************************/ /// <summary>A scroll control, which represents a one dimension sub range of a whole range.</summary> class GuiScroll : public GuiControl, public Description<GuiScroll> { 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> commandExecutor; vint totalSize = 100; vint pageSize = 10; vint position = 0; vint smallMove = 1; vint bigMove = 10; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiScroll(theme::ThemeName themeName); ~GuiScroll(); /// <summary>Total size changed event.</summary> compositions::GuiNotifyEvent TotalSizeChanged; /// <summary>Page size changed event.</summary> compositions::GuiNotifyEvent PageSizeChanged; /// <summary>Position changed event.</summary> compositions::GuiNotifyEvent PositionChanged; /// <summary>Small move changed event.</summary> compositions::GuiNotifyEvent SmallMoveChanged; /// <summary>Big move changed event.</summary> compositions::GuiNotifyEvent BigMoveChanged; /// <summary>Get the total size.</summary> /// <returns>The total size.</returns> virtual vint GetTotalSize(); /// <summary>Set the total size.</summary> /// <param name="value">The total size.</param> virtual void SetTotalSize(vint value); /// <summary>Get the page size.</summary> /// <returns>The page size.</returns> virtual vint GetPageSize(); /// <summary>Set the page size.</summary> /// <param name="value">The page size.</param> virtual void SetPageSize(vint value); /// <summary>Get the position.</summary> /// <returns>The position.</returns> virtual vint GetPosition(); /// <summary>Set the position.</summary> /// <param name="value">The position.</param> virtual void SetPosition(vint value); /// <summary>Get the small move.</summary> /// <returns>The small move.</returns> virtual vint GetSmallMove(); /// <summary>Set the small move.</summary> /// <param name="value">The small move.</param> virtual void SetSmallMove(vint value); /// <summary>Get the big move.</summary> /// <returns>The big move.</returns> virtual vint GetBigMove(); /// <summary>Set the big move.</summary> /// <param name="value">The big move.</param> virtual void SetBigMove(vint value); /// <summary>Get the minimum possible position.</summary> /// <returns>The minimum possible position.</returns> vint GetMinPosition(); /// <summary>Get the maximum possible position.</summary> /// <returns>The maximum possible position.</returns> vint GetMaxPosition(); }; } } } #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; /// <summary>Represnets a tab page control.</summary> class GuiTabPage : public GuiCustomControl, public AggregatableDescription<GuiTabPage> { friend class GuiTabPageList; protected: GuiTab* tab = nullptr; bool IsAltAvailable()override; public: /// <summary>Create a tab page control with a specified style controller.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiTabPage(theme::ThemeName themeName); ~GuiTabPage(); GuiTab* GetOwnerTab(); }; class GuiTabPageList : public collections::ObservableList<GuiTabPage*> { 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(); }; /// <summary>Represents a container with multiple named tabs.</summary> class GuiTab : public GuiControl, public Description<GuiTab> { 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)override; }; Ptr<CommandExecutor> commandExecutor; GuiTabPageList tabPages; GuiTabPage* selectedPage = nullptr; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiTab(theme::ThemeName themeName); ~GuiTab(); /// <summary>Selected page changed event.</summary> compositions::GuiNotifyEvent SelectedPageChanged; /// <summary>Get all pages.</summary> /// <returns>All pages.</returns> collections::ObservableList<GuiTabPage*>& GetPages(); /// <summary>Get the selected page.</summary> /// <returns>The selected page.</returns> GuiTabPage* GetSelectedPage(); /// <summary>Set the selected page.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The selected page.</param> bool SetSelectedPage(GuiTabPage* value); }; /*********************************************************************** Scroll View ***********************************************************************/ /// <summary>A control with a vertical scroll bar and a horizontal scroll bar to perform partial viewing.</summary> class GuiScrollView : public GuiControl, public Description<GuiScrollView> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ScrollViewTemplate, GuiControl) using IEventHandler = compositions::IGuiGraphicsEventHandler; protected: bool supressScrolling = false; Ptr<IEventHandler> hScrollHandler; Ptr<IEventHandler> vScrollHandler; Ptr<IEventHandler> hWheelHandler; Ptr<IEventHandler> vWheelHandler; Ptr<IEventHandler> containerBoundsChangedHandler; bool horizontalAlwaysVisible = true; bool verticalAlwaysVisible = true; 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); /// <summary>Calculate the full size of the content.</summary> /// <returns>The full size of the content.</returns> virtual Size QueryFullSize()=0; /// <summary>Update the visible content using a view bounds. The view bounds is in the space from (0,0) to full size.</summary> /// <param name="viewBounds">The view bounds.</param> virtual void UpdateView(Rect viewBounds)=0; /// <summary>Calculate the small move of the scroll bar.</summary> /// <returns>The small move of the scroll bar.</returns> virtual vint GetSmallMove(); /// <summary>Calculate the big move of the scroll bar.</summary> /// <returns>The big move of the scroll bar.</returns> virtual Size GetBigMove(); public: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiScrollView(theme::ThemeName themeName); ~GuiScrollView(); virtual void SetFont(const FontProperties& value)override; /// <summary>Force to update contents and scroll bars.</summary> void CalculateView(); /// <summary>Get the view size.</summary> /// <returns>The view size.</returns> Size GetViewSize(); /// <summary>Get the view bounds.</summary> /// <returns>The view bounds.</returns> Rect GetViewBounds(); /// <summary>Get the position of the left-top corner of the view bounds.</summary> /// <returns>The view position.</returns> Point GetViewPosition(); /// <summary>Set the position of the left-top corner of the view bounds.</summary> /// <param name="value">The position.</param> void SetViewPosition(Point value); /// <summary>Get the horizontal scroll control.</summary> /// <returns>The horizontal scroll control.</returns> GuiScroll* GetHorizontalScroll(); /// <summary>Get the vertical scroll control.</summary> /// <returns>The vertical scroll control.</returns> GuiScroll* GetVerticalScroll(); /// <summary>Test is the horizontal scroll bar always visible even the content doesn't exceed the view bounds.</summary> /// <returns>Returns true if the horizontal scroll bar always visible even the content doesn't exceed the view bounds</returns> bool GetHorizontalAlwaysVisible(); /// <summary>Set is the horizontal scroll bar always visible even the content doesn't exceed the view bounds.</summary> /// <param name="value">Set to true if the horizontal scroll bar always visible even the content doesn't exceed the view bounds</param> void SetHorizontalAlwaysVisible(bool value); /// <summary>Test is the vertical scroll bar always visible even the content doesn't exceed the view bounds.</summary> /// <returns>Returns true if the vertical scroll bar always visible even the content doesn't exceed the view bounds</returns> bool GetVerticalAlwaysVisible(); /// <summary>Set is the vertical scroll bar always visible even the content doesn't exceed the view bounds.</summary> /// <param name="value">Set to true if the vertical scroll bar always visible even the content doesn't exceed the view bounds</param> void SetVerticalAlwaysVisible(bool value); }; /// <summary>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.</summary> class GuiScrollContainer : public GuiScrollView, public Description<GuiScrollContainer> { protected: bool extendToFullWidth = false; bool extendToFullHeight = false; Size QueryFullSize()override; void UpdateView(Rect viewBounds)override; public: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiScrollContainer(theme::ThemeName themeName); ~GuiScrollContainer(); /// <summary>Test does the content container always extend its width to fill the scroll container.</summary> /// <returns>Return true if the content container always extend its width to fill the scroll container.</returns> bool GetExtendToFullWidth(); /// <summary>Set does the content container always extend its width to fill the scroll container.</summary> /// <param name="value">Set to true if the content container always extend its width to fill the scroll container.</param> void SetExtendToFullWidth(bool value); /// <summary>Test does the content container always extend its height to fill the scroll container.</summary> /// <returns>Return true if the content container always extend its height to fill the scroll container.</returns> bool GetExtendToFullHeight(); /// <summary>Set does the content container always extend its height to fill the scroll container.</summary> /// <param name="value">Set to true if the content container always extend its height to fill the scroll container.</param> 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 controls { /*********************************************************************** Control Host ***********************************************************************/ /// <summary> /// Represents a control that host by a <see cref="INativeWindow"/>. /// </summary> class GuiControlHost : public GuiControl, public GuiInstanceRootObject, protected INativeWindowListener, public Description<GuiControlHost> { friend class compositions::GuiGraphicsHost; protected: compositions::GuiGraphicsHost* host; virtual void OnNativeWindowChanged(); virtual void OnVisualStatusChanged(); protected: static const vint TooltipDelayOpenTime = 500; static const vint TooltipDelayCloseTime = 500; static const vint TooltipDelayLifeTime = 5000; Ptr<INativeDelay> tooltipOpenDelay; Ptr<INativeDelay> 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 clientSize); public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiControlHost(theme::ThemeName themeName); ~GuiControlHost(); /// <summary>Window got focus event.</summary> compositions::GuiNotifyEvent WindowGotFocus; /// <summary>Window lost focus event.</summary> compositions::GuiNotifyEvent WindowLostFocus; /// <summary>Window activated event.</summary> compositions::GuiNotifyEvent WindowActivated; /// <summary>Window deactivated event.</summary> compositions::GuiNotifyEvent WindowDeactivated; /// <summary>Window opened event.</summary> compositions::GuiNotifyEvent WindowOpened; /// <summary>Window closing event.</summary> compositions::GuiRequestEvent WindowClosing; /// <summary>Window closed event.</summary> compositions::GuiNotifyEvent WindowClosed; /// <summary>Window destroying event.</summary> compositions::GuiNotifyEvent WindowDestroying; /// <summary>Delete this control host after processing all events.</summary> void DeleteAfterProcessingAllEvents(); /// <summary>Get the internal <see cref="compositions::GuiGraphicsHost"/> object to host the window content.</summary> /// <returns>The internal <see cref="compositions::GuiGraphicsHost"/> object to host the window content.</returns> compositions::GuiGraphicsHost* GetGraphicsHost(); /// <summary>Get the main composition to host the window content.</summary> /// <returns>The main composition to host the window content.</returns> compositions::GuiGraphicsComposition* GetMainComposition(); /// <summary>Get the internal <see cref="INativeWindow"/> object to host the content.</summary> /// <returns>The the internal <see cref="INativeWindow"/> object to host the content.</returns> INativeWindow* GetNativeWindow(); /// <summary>Set the internal <see cref="INativeWindow"/> object to host the content.</summary> /// <param name="window">The the internal <see cref="INativeWindow"/> object to host the content.</param> void SetNativeWindow(INativeWindow* window); /// <summary>Force to calculate layout and size immediately</summary> void ForceCalculateSizeImmediately(); /// <summary>Test is the window enabled.</summary> /// <returns>Returns true if the window is enabled.</returns> bool GetEnabled()override; /// <summary>Enable or disable the window.</summary> /// <param name="value">Set to true to enable the window.</param> void SetEnabled(bool value)override; /// <summary>Test is the window focused.</summary> /// <returns>Returns true if the window is focused.</returns> bool GetFocused(); /// <summary>Focus the window.</summary> void SetFocused(); /// <summary>Test is the window activated.</summary> /// <returns>Returns true if the window is activated.</returns> bool GetActivated(); /// <summary>Activate the window.</summary> void SetActivated(); /// <summary>Test is the window icon shown in the task bar.</summary> /// <returns>Returns true if the window is icon shown in the task bar.</returns> bool GetShowInTaskBar(); /// <summary>Show or hide the window icon in the task bar.</summary> /// <param name="value">Set to true to show the window icon in the task bar.</param> void SetShowInTaskBar(bool value); /// <summary>Test is the window allowed to be activated.</summary> /// <returns>Returns true if the window is allowed to be activated.</returns> bool GetEnabledActivate(); /// <summary>Allow or forbid the window to be activated.</summary> /// <param name="value">Set to true to allow the window to be activated.</param> void SetEnabledActivate(bool value); /// <summary> /// Test is the window always on top of the desktop. /// </summary> /// <returns>Returns true if the window is always on top of the desktop.</returns> bool GetTopMost(); /// <summary> /// Make the window always or never on top of the desktop. /// </summary> /// <param name="topmost">True to make the window always on top of the desktop.</param> void SetTopMost(bool topmost); /// <summary>Get the <see cref="compositions::IGuiShortcutKeyManager"/> attached with this control host.</summary> /// <returns>The shortcut key manager.</returns> compositions::IGuiShortcutKeyManager* GetShortcutKeyManager(); /// <summary>Attach or detach the <see cref="compositions::IGuiShortcutKeyManager"/> associated with this control host. When this control host is disposing, the associated shortcut key manager will be deleted if exists.</summary> /// <param name="value">The shortcut key manager. Set to null to detach the previous shortcut key manager from this control host.</param> void SetShortcutKeyManager(compositions::IGuiShortcutKeyManager* value); /// <summary>Get the timer manager.</summary> /// <returns>The timer manager.</returns> compositions::GuiGraphicsTimerManager* GetTimerManager(); /// <summary>Get the client size of the window.</summary> /// <returns>The client size of the window.</returns> Size GetClientSize(); /// <summary>Set the client size of the window.</summary> /// <param name="value">The client size of the window.</param> void SetClientSize(Size value); /// <summary>Get the bounds of the window in screen space.</summary> /// <returns>The bounds of the window.</returns> Rect GetBounds(); /// <summary>Set the bounds of the window in screen space.</summary> /// <param name="value">The bounds of the window.</param> void SetBounds(Rect value); GuiControlHost* GetRelatedControlHost()override; const WString& GetText()override; void SetText(const WString& value)override; /// <summary>Get the screen that contains the window.</summary> /// <returns>The screen that contains the window.</returns> INativeScreen* GetRelatedScreen(); /// <summary> /// Show the window. /// </summary> void Show(); /// <summary> /// Show the window without activation. /// </summary> void ShowDeactivated(); /// <summary> /// Restore the window. /// </summary> void ShowRestored(); /// <summary> /// Maximize the window. /// </summary> void ShowMaximized(); /// <summary> /// Minimize the window. /// </summary> void ShowMinimized(); /// <summary> /// Hide the window. /// </summary> void Hide(); /// <summary> /// Close the window and destroy the internal <see cref="INativeWindow"/> object. /// </summary> void Close(); /// <summary>Test is the window opened.</summary> /// <returns>Returns true if the window is opened.</returns> bool GetOpening(); }; /*********************************************************************** Window ***********************************************************************/ /// <summary> /// Represents a normal window. /// </summary> class GuiWindow : public GuiControlHost, protected compositions::IGuiAltActionHost, public AggregatableDescription<GuiWindow> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(WindowTemplate, GuiControlHost) friend class GuiApplication; protected: compositions::IGuiAltActionHost* previousAltHost; bool hasMaximizedBox = true; bool hasMinimizedBox = true; bool hasBorder = true; bool hasSizeBox = true; bool isIconVisible = true; bool hasTitleBar = true; void SyncNativeWindowProperties(); void Moved()override; void OnNativeWindowChanged()override; void OnVisualStatusChanged()override; virtual void MouseClickedOnOtherWindow(GuiWindow* window); compositions::GuiGraphicsComposition* GetAltComposition()override; compositions::IGuiAltActionHost* GetPreviousAltHost()override; void OnActivatedAltHost(IGuiAltActionHost* previousHost)override; void OnDeactivatedAltHost()override; void CollectAltActions(collections::Group<WString, IGuiAltAction*>& actions)override; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiWindow(theme::ThemeName themeName); ~GuiWindow(); IDescriptable* QueryService(const WString& identifier)override; /// <summary>Clipboard updated event.</summary> compositions::GuiNotifyEvent ClipboardUpdated; /// <summary>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.</summary> void MoveToScreenCenter(); /// <summary>Move the window to the center of the specified screen.</summary> /// <param name="screen">The screen.</param> void MoveToScreenCenter(INativeScreen* screen); /// <summary> /// Test is the maximize box visible. /// </summary> /// <returns>Returns true if the maximize box is visible.</returns> bool GetMaximizedBox(); /// <summary> /// Make the maximize box visible or invisible. /// </summary> /// <param name="visible">True to make the maximize box visible.</param> void SetMaximizedBox(bool visible); /// <summary> /// Test is the minimize box visible. /// </summary> /// <returns>Returns true if the minimize box is visible.</returns> bool GetMinimizedBox(); /// <summary> /// Make the minimize box visible or invisible. /// </summary> /// <param name="visible">True to make the minimize box visible.</param> void SetMinimizedBox(bool visible); /// <summary> /// Test is the border visible. /// </summary> /// <returns>Returns true if the border is visible.</returns> bool GetBorder(); /// <summary> /// Make the border visible or invisible. /// </summary> /// <param name="visible">True to make the border visible.</param> void SetBorder(bool visible); /// <summary> /// Test is the size box visible. /// </summary> /// <returns>Returns true if the size box is visible.</returns> bool GetSizeBox(); /// <summary> /// Make the size box visible or invisible. /// </summary> /// <param name="visible">True to make the size box visible.</param> void SetSizeBox(bool visible); /// <summary> /// Test is the icon visible. /// </summary> /// <returns>Returns true if the icon is visible.</returns> bool GetIconVisible(); /// <summary> /// Make the icon visible or invisible. /// </summary> /// <param name="visible">True to make the icon visible.</param> void SetIconVisible(bool visible); /// <summary> /// Test is the title bar visible. /// </summary> /// <returns>Returns true if the title bar is visible.</returns> bool GetTitleBar(); /// <summary> /// Make the title bar visible or invisible. /// </summary> /// <param name="visible">True to make the title bar visible.</param> void SetTitleBar(bool visible); /// <summary> /// Show a model window, get a callback when the window is closed. /// </summary> /// <param name="owner">The window to disable as a parent window.</param> /// <param name="callback">The callback to call after the window is closed.</param> void ShowModal(GuiWindow* owner, const Func<void()>& callback); /// <summary> /// Show a model window, get a callback when the window is closed, and then delete itself. /// </summary> /// <param name="owner">The window to disable as a parent window.</param> /// <param name="callback">The callback to call after the window is closed.</param> void ShowModalAndDelete(GuiWindow* owner, const Func<void()>& callback); /// <summary> /// Show a model window as an async operation, which ends when the window is closed. /// </summary> /// <returns>Returns true if the size box is visible.</returns> /// <param name="owner">The window to disable as a parent window.</param> Ptr<reflection::description::IAsync> ShowModalAsync(GuiWindow* owner); }; /// <summary> /// Represents a popup window. When the mouse click on other window or the desktop, the popup window will be closed automatically. /// </summary> class GuiPopup : public GuiWindow, public Description<GuiPopup> { protected: union PopupInfo { struct _s1 { Point 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 clientSize)override; void MouseClickedOnOtherWindow(GuiWindow* window)override; void PopupOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void PopupClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); static bool IsClippedByScreen(Size size, Point location, INativeScreen* screen); static Point CalculatePopupPosition(Size size, Point location, INativeScreen* screen); static Point CalculatePopupPosition(Size size, GuiControl* control, INativeWindow* controlWindow, Rect bounds, bool preferredTopBottomSide); static Point CalculatePopupPosition(Size size, GuiControl* control, INativeWindow* controlWindow, Point location); static Point CalculatePopupPosition(Size size, GuiControl* control, INativeWindow* controlWindow, bool preferredTopBottomSide); static Point CalculatePopupPosition(Size size, vint popupType, const PopupInfo& popupInfo); void ShowPopupInternal(); public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiPopup(theme::ThemeName themeName); ~GuiPopup(); /// <summary>Test will the whole popup window be in the screen if the popup's left-top position is set to a specified value.</summary> /// <returns>Returns true if the whole popup window will be in the screen.</returns> /// <param name="location">The specified left-top position.</param> bool IsClippedByScreen(Point location); /// <summary>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.</summary> /// <param name="location">The specified left-top position.</param> /// <param name="screen">The expected screen. If you don't want to specify any screen, don't set this parameter.</param> void ShowPopup(Point location, INativeScreen* screen = 0); /// <summary>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.</summary> /// <param name="control">The control that owns this popup temporary. And the location is relative to this control.</param> /// <param name="bounds">The specified bounds.</param> /// <param name="preferredTopBottomSide">Set to true if the popup window is expected to be opened at the top or bottom side of that bounds.</param> void ShowPopup(GuiControl* control, Rect bounds, bool preferredTopBottomSide); /// <summary>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.</summary> /// <param name="control">The control that owns this popup temporary. And the location is relative to this control.</param> /// <param name="location">The specified left-top position.</param> void ShowPopup(GuiControl* control, Point location); /// <summary>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.</summary> /// <param name="control">The control that owns this popup temporary.</param> /// <param name="preferredTopBottomSide">Set to true if the popup window is expected to be opened at the top or bottom side of that control.</param> void ShowPopup(GuiControl* control, bool preferredTopBottomSide); }; /// <summary>Represents a tooltip window.</summary> class GuiTooltip : public GuiPopup, private INativeControllerListener, public Description<GuiTooltip> { protected: GuiControl* temporaryContentControl; void GlobalTimer()override; void TooltipOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void TooltipClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiTooltip(theme::ThemeName themeName); ~GuiTooltip(); /// <summary>Get the preferred content width.</summary> /// <returns>The preferred content width.</returns> vint GetPreferredContentWidth(); /// <summary>Set the preferred content width.</summary> /// <param name="value">The preferred content width.</param> void SetPreferredContentWidth(vint value); /// <summary>Get the temporary content control.</summary> /// <returns>The temporary content control.</returns> GuiControl* GetTemporaryContentControl(); /// <summary>Set the temporary content control.</summary> /// <param name="control">The temporary content control.</param> 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 ***********************************************************************/ /// <summary>Represents an GacUI application, for window management and asynchronized operation supporting. Use [M:vl.presentation.controls.GetApplication] to access the instance of this class.</summary> class GuiApplication : public Object, private INativeControllerListener, public Description<GuiApplication> { friend void GuiApplicationInitialize(); friend class GuiWindow; friend class GuiPopup; friend class Ptr<GuiApplication>; private: void InvokeClipboardNotify(compositions::GuiGraphicsComposition* composition, compositions::GuiEventArgs& arguments); void LeftButtonDown(Point position)override; void LeftButtonUp(Point position)override; void RightButtonDown(Point position)override; void RightButtonUp(Point position)override; 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<GuiWindow*> windows; collections::SortedList<GuiPopup*> openingPopups; GuiApplication(); ~GuiApplication(); INativeWindow* GetThreadContextNativeWindow(GuiControlHost* controlHost); void RegisterWindow(GuiWindow* window); void UnregisterWindow(GuiWindow* window); void RegisterPopupOpened(GuiPopup* popup); void RegisterPopupClosed(GuiPopup* popup); void OnMouseDown(Point location); void TooltipMouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void TooltipMouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// <summary>Locale changed event.</summary> Event<void()> LocaleChanged; /// <summary>Returns the selected locale for all windows.</summary> /// <returns>The selected locale.</returns> Locale GetLocale(); /// <summary>Set the locale for all windows.</summary> /// <param name="value">The selected locale.</param> void SetLocale(Locale value); /// <summary>Run a <see cref="GuiWindow"/> 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.</summary> /// <param name="_mainWindow">The main window.</param> void Run(GuiWindow* _mainWindow); /// <summary>Get the main window.</summary> /// <returns>The main window.</returns> GuiWindow* GetMainWindow(); /// <summary>Get all created <see cref="GuiWindow"/> instances. This contains normal windows, popup windows, menus, or other types of windows that inherits from <see cref="GuiWindow"/>.</summary> /// <returns>All created <see cref="GuiWindow"/> instances.</returns> const collections::List<GuiWindow*>& GetWindows(); /// <summary>Get the <see cref="GuiWindow"/> instance that the mouse cursor are directly in.</summary> /// <returns>The <see cref="GuiWindow"/> instance that the mouse cursor are directly in.</returns> /// <param name="location">The mouse cursor.</param> GuiWindow* GetWindow(Point location); /// <summary>Show a tooltip.</summary> /// <param name="owner">The control that owns this tooltip temporary.</param> /// <param name="tooltip">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).</param> /// <param name="preferredContentWidth">The preferred content width for this tooltip.</param> /// <param name="location">The relative location to specify the left-top position of the tooltip.</param> void ShowTooltip(GuiControl* owner, GuiControl* tooltip, vint preferredContentWidth, Point location); /// <summary>Close the tooltip</summary> void CloseTooltip(); /// <summary>Get the tooltip owner. When the tooltip closed, it returns null.</summary> /// <returns>The tooltip owner.</returns> GuiControl* GetTooltipOwner(); /// <summary>Get the file path of the current executable.</summary> /// <returns>The file path of the current executable.</returns> WString GetExecutablePath(); /// <summary>Get the folder of the current executable.</summary> /// <returns>The folder of the current executable.</returns> WString GetExecutableFolder(); /// <summary>Test is the current thread the main thread for GUI.</summary> /// <returns>Returns true if the current thread is the main thread for GUI.</returns> /// <param name="controlHost">A control host to access the corressponding main thread.</param> bool IsInMainThread(GuiControlHost* controlHost); /// <summary>Invoke a specified function asynchronously.</summary> /// <param name="proc">The specified function.</param> void InvokeAsync(const Func<void()>& proc); /// <summary>Invoke a specified function in the main thread.</summary> /// <param name="controlHost">A control host to access the corressponding main thread.</param> /// <param name="proc">The specified function.</param> void InvokeInMainThread(GuiControlHost* controlHost, const Func<void()>& proc); /// <summary>Invoke a specified function in the main thread and wait for the function to complete or timeout.</summary> /// <returns>Return true if the function complete. Return false if the function has not completed during a specified period of time.</returns> /// <param name="controlHost">A control host to access the corressponding main thread.</param> /// <param name="proc">The specified function.</param> /// <param name="milliseconds">The specified period of time to wait. Set to -1 (default value) to wait forever until the function completed.</param> bool InvokeInMainThreadAndWait(GuiControlHost* controlHost, const Func<void()>& proc, vint milliseconds=-1); /// <summary>Delay execute a specified function with an specified argument asynchronisly.</summary> /// <returns>The Delay execution controller for this task.</returns> /// <param name="proc">The specified function.</param> /// <param name="milliseconds">Time to delay.</param> Ptr<INativeDelay> DelayExecute(const Func<void()>& proc, vint milliseconds); /// <summary>Delay execute a specified function with an specified argument in the main thread.</summary> /// <returns>The Delay execution controller for this task.</returns> /// <param name="proc">The specified function.</param> /// <param name="milliseconds">Time to delay.</param> Ptr<INativeDelay> DelayExecuteInMainThread(const Func<void()>& proc, vint milliseconds); /// <summary>Run the specified function in the main thread. If the caller is in the main thread, then run the specified function directly.</summary> /// <param name="controlHost">A control host to access the corressponding main thread.</param> /// <param name="proc">The specified function.</param> void RunGuiTask(GuiControlHost* controlHost, const Func<void()>& proc); template<typename T> T RunGuiValue(GuiControlHost* controlHost, const Func<T()>& proc) { T result; RunGuiTask(controlHost, [&result, &proc]() { result=proc(); }); return result; } template<typename T> void InvokeLambdaInMainThread(GuiControlHost* controlHost, const T& proc) { InvokeInMainThread(controlHost, Func<void()>(proc)); } template<typename T> bool InvokeLambdaInMainThreadAndWait(GuiControlHost* controlHost, const T& proc, vint milliseconds=-1) { return InvokeInMainThreadAndWait(controlHost, Func<void()>(proc), milliseconds); } }; /*********************************************************************** Plugin ***********************************************************************/ /// <summary>Represents a plugin for the gui.</summary> class IGuiPlugin : public IDescriptable, public Description<IGuiPlugin> { public: /// <summary>Get the name of this plugin.</summary> /// <returns>Returns the name of the plugin.</returns> virtual WString GetName() = 0; /// <summary>Get all dependencies of this plugin.</summary> /// <param name="dependencies">To receive all dependencies.</param> virtual void GetDependencies(collections::List<WString>& dependencies) = 0; /// <summary>Called when the plugin manager want to load this plugin.</summary> virtual void Load()=0; /// <summary>Called when the plugin manager want to unload this plugin.</summary> virtual void Unload()=0; }; /// <summary>Represents a plugin manager.</summary> class IGuiPluginManager : public IDescriptable, public Description<IGuiPluginManager> { public: /// <summary>Add a plugin before [F:vl.presentation.controls.IGuiPluginManager.Load] is called.</summary> /// <param name="plugin">The plugin.</param> virtual void AddPlugin(Ptr<IGuiPlugin> plugin)=0; /// <summary>Load all plugins, and check if dependencies of all plugins are ready.</summary> virtual void Load()=0; /// <summary>Unload all plugins.</summary> virtual void Unload()=0; /// <returns>Returns true if all plugins are loaded.</returns> virtual bool IsLoaded()=0; }; /*********************************************************************** Helper Functions ***********************************************************************/ /// <summary>Get the global <see cref="GuiApplication"/> object.</summary> /// <returns>The global <see cref="GuiApplication"/> object.</returns> extern GuiApplication* GetApplication(); /// <summary>Get the global <see cref="IGuiPluginManager"/> object.</summary> /// <returns>The global <see cref="GuiApplication"/> object.</returns> extern IGuiPluginManager* GetPluginManager(); /// <summary>Destroy the global <see cref="IGuiPluginManager"/> object.</summary> 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<WString>& dependencies)override\ #define GUI_PLUGIN_DEPEND(NAME) dependencies.Add(L ## #NAME) #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 ***********************************************************************/ /// <summary>Represents a list control. A list control automatically read data sources and creates corresponding data item control from the item template.</summary> class GuiListControl : public GuiScrollView, public Description<GuiListControl> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ListControlTemplate, GuiScrollView) public: class IItemProvider; using ItemStyle = templates::GuiListItemTemplate; using ItemStyleProperty = TemplateProperty<templates::GuiListItemTemplate>; //----------------------------------------------------------- // Callback Interfaces //----------------------------------------------------------- /// <summary>Item provider callback. Item providers use this interface to notify item modification.</summary> class IItemProviderCallback : public virtual IDescriptable, public Description<IItemProviderCallback> { public: /// <summary>Called when an item provider callback object is attached to an item provider.</summary> /// <param name="provider">The item provider.</param> virtual void OnAttached(IItemProvider* provider)=0; /// <summary>Called when items in the item provider is modified.</summary> /// <param name="start">The index of the first modified item.</param> /// <param name="count">The number of all modified items.</param> /// <param name="newCount">The number of new items. If items are inserted or removed, newCount may not equals to count.</param> virtual void OnItemModified(vint start, vint count, vint newCount)=0; }; /// <summary>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].</summary> class IItemArrangerCallback : public virtual IDescriptable, public Description<IItemArrangerCallback> { public: /// <summary>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.</summary> /// <returns>The item control.</returns> /// <param name="itemIndex">The index of the item in the item provider.</param> /// <param name="itemComposition">The composition that represents the item. Set to null if the item style is expected to be put directly into the list control.</param> virtual ItemStyle* RequestItem(vint itemIndex, compositions::GuiBoundsComposition* itemComposition)=0; /// <summary>Release an item control. This function is suggested to call when an item control gets out of the visible area.</summary> /// <param name="style">The item control.</param> virtual void ReleaseItem(ItemStyle* style)=0; /// <summary>Update the view location. The view location is the left-top position in the logic space of the list control.</summary> /// <param name="value">The new view location.</param> virtual void SetViewLocation(Point value)=0; /// <summary>Get the preferred size of an item control.</summary> /// <returns>The preferred size of an item control.</returns> /// <param name="style">The item control.</param> virtual Size GetStylePreferredSize(compositions::GuiBoundsComposition* style)=0; /// <summary>Set the alignment of an item control.</summary> /// <param name="style">The item control.</param> /// <param name="margin">The new alignment.</param> virtual void SetStyleAlignmentToParent(compositions::GuiBoundsComposition* style, Margin margin)=0; /// <summary>Get the bounds of an item control.</summary> /// <returns>The bounds of an item control.</returns> /// <param name="style">The item control.</param> virtual Rect GetStyleBounds(compositions::GuiBoundsComposition* style)=0; /// <summary>Set the bounds of an item control.</summary> /// <param name="style">The item control.</param> /// <param name="bounds">The new bounds.</param> virtual void SetStyleBounds(compositions::GuiBoundsComposition* style, Rect bounds)=0; /// <summary>Get the <see cref="compositions::GuiGraphicsComposition"/> that directly contains item controls.</summary> /// <returns>The <see cref="compositions::GuiGraphicsComposition"/> that directly contains item controls.</returns> virtual compositions::GuiGraphicsComposition* GetContainerComposition()=0; /// <summary>Notify the list control that the total size of all item controls are changed.</summary> virtual void OnTotalSizeChanged()=0; }; //----------------------------------------------------------- // Data Source Interfaces //----------------------------------------------------------- /// <summary>Item provider for a <see cref="GuiListControl"/>.</summary> class IItemProvider : public virtual IDescriptable, public Description<IItemProvider> { public: /// <summary>Attach an item provider callback to this item provider.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The item provider callback.</param> virtual bool AttachCallback(IItemProviderCallback* value) = 0; /// <summary>Detach an item provider callback from this item provider.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The item provider callback.</param> virtual bool DetachCallback(IItemProviderCallback* value) = 0; /// <summary>Increase the editing counter indicating that an [T:vl.presentation.templates.GuiListItemTemplate] is editing an item.</summary> virtual void PushEditing() = 0; /// <summary>Decrease the editing counter indicating that an [T:vl.presentation.templates.GuiListItemTemplate] has stopped editing an item.</summary> /// <returns>Returns false if there is no supression before calling this function.</returns> virtual bool PopEditing() = 0; /// <summary>Test if an [T:vl.presentation.templates.GuiListItemTemplate] is editing an item.</summary> /// <returns>Returns false if there is no editing.</returns> virtual bool IsEditing() = 0; /// <summary>Get the number of items in this item proivder.</summary> /// <returns>The number of items in this item proivder.</returns> virtual vint Count() = 0; /// <summary>Get the text representation of an item.</summary> /// <returns>The text representation of an item.</returns> /// <param name="itemIndex">The index of the item.</param> virtual WString GetTextValue(vint itemIndex) = 0; /// <summary>Get the binding value of an item.</summary> /// <returns>The binding value of an item.</returns> /// <param name="itemIndex">The index of the item.</param> virtual description::Value GetBindingValue(vint itemIndex) = 0; /// <summary>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.</summary> /// <returns>The view object.</returns> /// <param name="identifier">The identifier for the requested view.</param> virtual IDescriptable* RequestView(const WString& identifier) = 0; }; //----------------------------------------------------------- // Item Layout Interfaces //----------------------------------------------------------- /// <summary>Item arranger for a <see cref="GuiListControl"/>. Item arranger decides how to arrange and item controls. When implementing an item arranger, <see cref="IItemArrangerCallback"/> is suggested to use when calculating locations and sizes for item controls.</summary> class IItemArranger : public virtual IItemProviderCallback, public Description<IItemArranger> { public: /// <summary>Called when an item arranger in installed to a <see cref="GuiListControl"/>.</summary> /// <param name="value">The list control.</param> virtual void AttachListControl(GuiListControl* value) = 0; /// <summary>Called when an item arranger in uninstalled from a <see cref="GuiListControl"/>.</summary> virtual void DetachListControl() = 0; /// <summary>Get the binded item arranger callback object.</summary> /// <returns>The binded item arranger callback object.</returns> virtual IItemArrangerCallback* GetCallback() = 0; /// <summary>Bind the item arranger callback object.</summary> /// <param name="value">The item arranger callback object to bind.</param> virtual void SetCallback(IItemArrangerCallback* value) = 0; /// <summary>Get the total size of all data controls.</summary> /// <returns>The total size.</returns> virtual Size GetTotalSize() = 0; /// <summary>Get the item style controller for an visible item index. If an item is not visible, it returns null.</summary> /// <returns>The item style controller.</returns> /// <param name="itemIndex">The item index.</param> virtual ItemStyle* GetVisibleStyle(vint itemIndex) = 0; /// <summary>Get the item index for an visible item style controller. If an item is not visible, it returns -1.</summary> /// <returns>The item index.</returns> /// <param name="style">The item style controller.</param> virtual vint GetVisibleIndex(ItemStyle* style) = 0; /// <summary>Reload all visible items.</summary> virtual void ReloadVisibleStyles() = 0; /// <summary>Called when the visible area of item container is changed.</summary> /// <param name="bounds">The new visible area.</param> virtual void OnViewChanged(Rect bounds) = 0; /// <summary>Find the item by an base item and a key direction.</summary> /// <returns>The item index that is found. Returns -1 if this operation failed.</returns> /// <param name="itemIndex">The base item index.</param> /// <param name="key">The key direction.</param> virtual vint FindItem(vint itemIndex, compositions::KeyDirection key) = 0; /// <summary>Adjust the view location to make an item visible.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="itemIndex">The item index of the item to be made visible.</param> virtual bool EnsureItemVisible(vint itemIndex) = 0; /// <summary>Get the adopted size for the view bounds.</summary> /// <returns>The adopted size, making the vids bounds just enough to display several items.</returns> /// <param name="expectedSize">The expected size, to provide a guidance.</param> virtual Size GetAdoptedSize(Size expectedSize) = 0; }; protected: //----------------------------------------------------------- // ItemCallback //----------------------------------------------------------- class ItemCallback : public IItemProviderCallback, public IItemArrangerCallback { typedef compositions::IGuiGraphicsEventHandler BoundsChangedHandler; typedef collections::List<ItemStyle*> StyleList; typedef collections::Dictionary<ItemStyle*, Ptr<BoundsChangedHandler>> InstalledStyleMap; protected: GuiListControl* listControl = nullptr; IItemProvider* itemProvider = nullptr; InstalledStyleMap installedStyles; Ptr<BoundsChangedHandler> 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<ItemCallback> callback; Ptr<IItemProvider> itemProvider; ItemStyleProperty itemStyleProperty; Ptr<IItemArranger> itemArranger; Ptr<compositions::IGuiAxis> 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<IItemArranger> arranger); //----------------------------------------------------------- // Item event management //----------------------------------------------------------- class VisibleStyleHelper { public: Ptr<compositions::IGuiGraphicsEventHandler> leftButtonDownHandler; Ptr<compositions::IGuiGraphicsEventHandler> leftButtonUpHandler; Ptr<compositions::IGuiGraphicsEventHandler> leftButtonDoubleClickHandler; Ptr<compositions::IGuiGraphicsEventHandler> middleButtonDownHandler; Ptr<compositions::IGuiGraphicsEventHandler> middleButtonUpHandler; Ptr<compositions::IGuiGraphicsEventHandler> middleButtonDoubleClickHandler; Ptr<compositions::IGuiGraphicsEventHandler> rightButtonDownHandler; Ptr<compositions::IGuiGraphicsEventHandler> rightButtonUpHandler; Ptr<compositions::IGuiGraphicsEventHandler> rightButtonDoubleClickHandler; Ptr<compositions::IGuiGraphicsEventHandler> mouseMoveHandler; Ptr<compositions::IGuiGraphicsEventHandler> mouseEnterHandler; Ptr<compositions::IGuiGraphicsEventHandler> mouseLeaveHandler; }; friend class collections::ArrayBase<Ptr<VisibleStyleHelper>>; collections::Dictionary<ItemStyle*, Ptr<VisibleStyleHelper>> visibleStyles; void OnClientBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnVisuallyEnabledChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnFontChanged(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: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_itemProvider">The item provider as a data source.</param> /// <param name="acceptFocus">Set to true if the list control is allowed to have a keyboard focus.</param> GuiListControl(theme::ThemeName themeName, IItemProvider* _itemProvider, bool acceptFocus=false); ~GuiListControl(); /// <summary>Style provider changed event.</summary> compositions::GuiNotifyEvent ItemTemplateChanged; /// <summary>Arranger changed event.</summary> compositions::GuiNotifyEvent ArrangerChanged; /// <summary>Coordinate transformer changed event.</summary> compositions::GuiNotifyEvent AxisChanged; /// <summary>Adopted size invalidated.</summary> compositions::GuiNotifyEvent AdoptedSizeInvalidated; /// <summary>Item left mouse button down event.</summary> compositions::GuiItemMouseEvent ItemLeftButtonDown; /// <summary>Item left mouse button up event.</summary> compositions::GuiItemMouseEvent ItemLeftButtonUp; /// <summary>Item left mouse button double click event.</summary> compositions::GuiItemMouseEvent ItemLeftButtonDoubleClick; /// <summary>Item middle mouse button down event.</summary> compositions::GuiItemMouseEvent ItemMiddleButtonDown; /// <summary>Item middle mouse button up event.</summary> compositions::GuiItemMouseEvent ItemMiddleButtonUp; /// <summary>Item middle mouse button double click event.</summary> compositions::GuiItemMouseEvent ItemMiddleButtonDoubleClick; /// <summary>Item right mouse button down event.</summary> compositions::GuiItemMouseEvent ItemRightButtonDown; /// <summary>Item right mouse button up event.</summary> compositions::GuiItemMouseEvent ItemRightButtonUp; /// <summary>Item right mouse button double click event.</summary> compositions::GuiItemMouseEvent ItemRightButtonDoubleClick; /// <summary>Item mouse move event.</summary> compositions::GuiItemMouseEvent ItemMouseMove; /// <summary>Item mouse enter event.</summary> compositions::GuiItemNotifyEvent ItemMouseEnter; /// <summary>Item mouse leave event.</summary> compositions::GuiItemNotifyEvent ItemMouseLeave; /// <summary>Get the item provider.</summary> /// <returns>The item provider.</returns> virtual IItemProvider* GetItemProvider(); /// <summary>Get the item style provider.</summary> /// <returns>The item style provider.</returns> virtual ItemStyleProperty GetItemTemplate(); /// <summary>Set the item style provider</summary> /// <param name="value">The new item style provider</param> virtual void SetItemTemplate(ItemStyleProperty value); /// <summary>Get the item arranger.</summary> /// <returns>The item arranger.</returns> virtual IItemArranger* GetArranger(); /// <summary>Set the item arranger</summary> /// <param name="value">The new item arranger</param> virtual void SetArranger(Ptr<IItemArranger> value); /// <summary>Get the item coordinate transformer.</summary> /// <returns>The item coordinate transformer.</returns> virtual compositions::IGuiAxis* GetAxis(); /// <summary>Set the item coordinate transformer</summary> /// <param name="value">The new item coordinate transformer</param> virtual void SetAxis(Ptr<compositions::IGuiAxis> value); /// <summary>Adjust the view location to make an item visible.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="itemIndex">The item index of the item to be made visible.</param> virtual bool EnsureItemVisible(vint itemIndex); /// <summary>Get the adopted size for the list control.</summary> /// <returns>The adopted size, making the list control just enough to display several items.</returns> /// <param name="expectedSize">The expected size, to provide a guidance.</param> virtual Size GetAdoptedSize(Size expectedSize); /// <summary>Test if the list control displays predefined item background.</summary> /// <returns>Returns true if the list control displays predefined item background.</returns> bool GetDisplayItemBackground(); /// <summary>Set if the list control displays predefined item background.</summary> /// <param name="value">Set to true to display item background.</param> void SetDisplayItemBackground(bool value); }; /*********************************************************************** Selectable List Control ***********************************************************************/ /// <summary>Represents a list control that each item is selectable.</summary> class GuiSelectableListControl : public GuiListControl, public Description<GuiSelectableListControl> { protected: collections::SortedList<vint> 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: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_itemProvider">The item provider as a data source.</param> GuiSelectableListControl(theme::ThemeName themeName, IItemProvider* _itemProvider); ~GuiSelectableListControl(); /// <summary>Selection changed event.</summary> compositions::GuiNotifyEvent SelectionChanged; /// <summary>Get the multiple selection mode.</summary> /// <returns>Returns true if multiple selection is enabled.</returns> bool GetMultiSelect(); /// <summary>Set the multiple selection mode.</summary> /// <param name="value">Set to true to enable multiple selection.</param> void SetMultiSelect(bool value); /// <summary>Get indices of all selected items.</summary> /// <returns>Indices of all selected items.</returns> const collections::SortedList<vint>& GetSelectedItems(); /// <summary>Get the index of the selected item.</summary> /// <returns>Returns the index of the selected item. If there are multiple selected items, or there is no selected item, -1 will be returned.</returns> vint GetSelectedItemIndex(); /// <summary>Get the text of the selected item.</summary> /// <returns>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.</returns> WString GetSelectedItemText(); /// <summary>Get the selection status of an item.</summary> /// <returns>The selection status of an item.</returns> /// <param name="itemIndex">The index of the item.</param> bool GetSelected(vint itemIndex); /// <summary>Set the selection status of an item.</summary> /// <param name="itemIndex">The index of the item.</param> /// <param name="value">Set to true to select the item.</param> void SetSelected(vint itemIndex, bool value); /// <summary>Set the selection status of an item, and affect other selected item according to key status.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="itemIndex">The index of the item.</param> /// <param name="ctrl">Set to true if the control key is pressing.</param> /// <param name="shift">Set to true if the shift key is pressing.</param> /// <param name="leftButton">Set to true if clicked by left mouse button, otherwise right mouse button.</param> bool SelectItemsByClick(vint itemIndex, bool ctrl, bool shift, bool leftButton); /// <summary>Set the selection status using keys.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="code">The key code that is pressing.</param> /// <param name="ctrl">Set to true if the control key is pressing.</param> /// <param name="shift">Set to true if the shift key is pressing.</param> bool SelectItemsByKey(vint code, bool ctrl, bool shift); /// <summary>Unselect all items.</summary> void ClearSelection(); }; /*********************************************************************** Predefined ItemProvider ***********************************************************************/ namespace list { /// <summary>Item provider base. This class provider common functionalities for item providers.</summary> class ItemProviderBase : public Object, public virtual GuiListControl::IItemProvider, public Description<ItemProviderBase> { protected: collections::List<GuiListControl::IItemProviderCallback*> callbacks; vint editingCounter = 0; virtual void InvokeOnItemModified(vint start, vint count, vint newCount); public: /// <summary>Create the item provider.</summary> ItemProviderBase(); ~ItemProviderBase(); bool AttachCallback(GuiListControl::IItemProviderCallback* value)override; bool DetachCallback(GuiListControl::IItemProviderCallback* value)override; void PushEditing()override; bool PopEditing()override; bool IsEditing()override; }; template<typename T> class ListProvider : public ItemProviderBase, public collections::ObservableListBase<T> { 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\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 ***********************************************************************/ /// <summary>The required <see cref="GuiListControl::IItemProvider"/> view for <see cref="GuiVirtualTextList"/>.</summary> class ITextItemView : public virtual IDescriptable, public Description<ITextItemView> { public: /// <summary>The identifier for this view.</summary> static const wchar_t* const Identifier; /// <summary>Get the check state of an item.</summary> /// <returns>The check state of an item.</returns> /// <param name="itemIndex">The index of an item.</param> virtual bool GetChecked(vint itemIndex) = 0; /// <summary>Set the check state of an item without invoving any UI action.</summary> /// <param name="itemIndex">The index of an item.</param> /// <param name="value">The new check state.</param> 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<BulletStyle> 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<BulletStyle> CreateBulletStyle()override; public: }; class DefaultRadioTextListItemTemplate : public DefaultTextListItemTemplate { protected: TemplateProperty<BulletStyle> CreateBulletStyle()override; public: }; /*********************************************************************** TextItemProvider ***********************************************************************/ class TextItemProvider; /// <summary>Text item. This is the item data structure for [T:vl.presentation.controls.list.TextItemProvider].</summary> class TextItem : public Object, public Description<TextItem> { friend class TextItemProvider; protected: TextItemProvider* owner; WString text; bool checked; public: /// <summary>Create an empty text item.</summary> TextItem(); /// <summary>Create a text item with specified text and check state.</summary> /// <param name="_text">The text.</param> /// <param name="_checked">The check state.</param> TextItem(const WString& _text, bool _checked=false); ~TextItem(); bool operator==(const TextItem& value)const; bool operator!=(const TextItem& value)const; /// <summary>Get the text of this item.</summary> /// <returns>The text of this item.</returns> const WString& GetText(); /// <summary>Set the text of this item.</summary> /// <param name="value">The text of this item.</param> void SetText(const WString& value); /// <summary>Get the check state of this item.</summary> /// <returns>The check state of this item.</returns> bool GetChecked(); /// <summary>Set the check state of this item.</summary> /// <param name="value">The check state of this item.</param> void SetChecked(bool value); }; /// <summary>Item provider for <see cref="GuiVirtualTextList"/> or <see cref="GuiSelectableListControl"/>.</summary> class TextItemProvider : public ListProvider<Ptr<TextItem>> , protected ITextItemView , public Description<TextItemProvider> { friend class TextItem; friend class vl::presentation::controls::GuiTextList; protected: GuiTextList* listControl; void AfterInsert(vint item, const Ptr<TextItem>& value)override; void BeforeRemove(vint item, const Ptr<TextItem>& 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, }; /// <summary>Text list control in virtual mode.</summary> class GuiVirtualTextList : public GuiSelectableListControl, public Description<GuiVirtualTextList> { 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: /// <summary>Create a Text list control in virtual mode.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_itemProvider">The item provider for this control.</param> GuiVirtualTextList(theme::ThemeName themeName, GuiListControl::IItemProvider* _itemProvider); ~GuiVirtualTextList(); /// <summary>Item checked changed event.</summary> compositions::GuiItemNotifyEvent ItemChecked; /// <summary>Get the current view.</summary> /// <returns>The current view. After [M:vl.presentation.controls.GuiListControl.SetItemTemplate] is called, the current view is reset to Unknown.</returns> TextListView GetView(); /// <summary>Set the current view.</summary> /// <param name="_view">The current view.</param> void SetView(TextListView _view); }; /*********************************************************************** GuiTextList ***********************************************************************/ /// <summary>Text list control.</summary> class GuiTextList : public GuiVirtualTextList, public Description<GuiTextList> { protected: list::TextItemProvider* items; public: /// <summary>Create a Text list control.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiTextList(theme::ThemeName themeName); ~GuiTextList(); /// <summary>Get all text items.</summary> /// <returns>All text items.</returns> list::TextItemProvider& GetItems(); /// <summary>Get the selected item.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> Ptr<list::TextItem> 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 //----------------------------------------------------------- /// <summary>Callback object for <see cref="INodeProvider"/>. A node will invoke this callback to notify any content modification.</summary> class INodeProviderCallback : public virtual IDescriptable, public Description<INodeProviderCallback> { public: /// <summary>Called when this callback is attached to a node root.</summary> /// <param name="provider">The root node.</param> virtual void OnAttached(INodeRootProvider* provider)=0; /// <summary>Called before sub items of a node are modified.</summary> /// <param name="parentNode">The node containing modified sub items.</param> /// <param name="start">The index of the first sub item.</param> /// <param name="count">The number of sub items to be modified.</param> /// <param name="newCount">The new number of modified sub items.</param> virtual void OnBeforeItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)=0; /// <summary>Called after sub items of a node are modified.</summary> /// <param name="parentNode">The node containing modified sub items.</param> /// <param name="start">The index of the first sub item.</param> /// <param name="count">The number of sub items to be modified.</param> /// <param name="newCount">The new number of modified sub items.</param> virtual void OnAfterItemModified(INodeProvider* parentNode, vint start, vint count, vint newCount)=0; /// <summary>Called when a node is expanded.</summary> /// <param name="node">The node.</param> virtual void OnItemExpanded(INodeProvider* node)=0; /// <summary>Called when a node is collapsed.</summary> /// <param name="node">The node.</param> virtual void OnItemCollapsed(INodeProvider* node)=0; }; //----------------------------------------------------------- // Provider Interfaces //----------------------------------------------------------- /// <summary>Represents a node.</summary> class INodeProvider : public virtual IDescriptable, public Description<INodeProvider> { public: /// <summary>Get the expanding state of this node.</summary> /// <returns>Returns true if this node is expanded.</returns> virtual bool GetExpanding()=0; /// <summary>Set the expanding state of this node.</summary> /// <param name="value">Set to true to expand this node.</param> virtual void SetExpanding(bool value)=0; /// <summary>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.</summary> /// <returns>The number of total visible nodes.</returns> virtual vint CalculateTotalVisibleNodes()=0; /// <summary>Get the number of all sub nodes.</summary> /// <returns>The number of all sub nodes.</returns> virtual vint GetChildCount()=0; /// <summary>Get the parent node.</summary> /// <returns>The parent node.</returns> virtual Ptr<INodeProvider> GetParent()=0; /// <summary>Get the instance of a specified sub node.</summary> /// <returns>The instance of a specified sub node.</returns> /// <param name="index">The index of the sub node.</param> virtual Ptr<INodeProvider> GetChild(vint index)=0; /// <summary>Increase the reference counter.</summary> }; /// <summary>Represents a root node provider.</summary> class INodeRootProvider : public virtual IDescriptable, public Description<INodeRootProvider> { public: /// <summary>Get the instance of the root node.</summary> /// <returns>Returns the instance of the root node.</returns> virtual Ptr<INodeProvider> GetRootNode()=0; /// <summary>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.</summary> /// <returns>Returns true if such an algorithm is provided.</returns> virtual bool CanGetNodeByVisibleIndex()=0; /// <summary>Get a node by the index in all visible nodes. This requires [M:vl.presentation.controls.tree.INodeRootProvider.CanGetNodeByVisibleIndex] returning true.</summary> /// <returns>The node for the index in all visible nodes.</returns> /// <param name="index">The index in all visible nodes.</param> virtual Ptr<INodeProvider> GetNodeByVisibleIndex(vint index)=0; /// <summary>Attach an node provider callback to this node provider.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The node provider callback.</param> virtual bool AttachCallback(INodeProviderCallback* value)=0; /// <summary>Detach an node provider callback from this node provider.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The node provider callback.</param> virtual bool DetachCallback(INodeProviderCallback* value)=0; /// <summary>Get the primary text of a node.</summary> /// <returns>The primary text of a node.</returns> /// <param name="node">The node.</param> virtual WString GetTextValue(INodeProvider* node) = 0; /// <summary>Get the binding value of a node.</summary> /// <returns>The binding value of a node.</returns> /// <param name="node">The node.</param> virtual description::Value GetBindingValue(INodeProvider* node) = 0; /// <summary>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.</summary> /// <returns>The view object.</returns> /// <param name="identifier">The identifier for the requested view.</param> virtual IDescriptable* RequestView(const WString& identifier)=0; }; } namespace tree { //----------------------------------------------------------- // Tree to ListControl (IItemProvider) //----------------------------------------------------------- /// <summary>The required <see cref="GuiListControl::IItemProvider"/> 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.</summary> class INodeItemView : public virtual IDescriptable, public Description<INodeItemView> { public: /// <summary>The identifier of this view.</summary> static const wchar_t* const Identifier; /// <summary>Get an instance of a node by the index in all visible nodes.</summary> /// <returns>The instance of a node by the index in all visible nodes.</returns> /// <param name="index">The index in all visible nodes.</param> virtual Ptr<INodeProvider> RequestNode(vint index)=0; /// <summary>Get the index in all visible nodes of a node.</summary> /// <returns>The index in all visible nodes of a node.</returns> /// <param name="node">The node to calculate the index.</param> virtual vint CalculateNodeVisibilityIndex(INodeProvider* node)=0; }; /// <summary>This is a general implementation to convert an <see cref="INodeRootProvider"/> to a <see cref="GuiListControl::IItemProvider"/>.</summary> class NodeItemProvider : public list::ItemProviderBase , protected virtual INodeProviderCallback , public virtual INodeItemView , public Description<NodeItemProvider> { typedef collections::Dictionary<INodeProvider*, vint> NodeIntMap; protected: Ptr<INodeRootProvider> root; NodeIntMap offsetBeforeChildModifieds; Ptr<INodeProvider> GetNodeByOffset(Ptr<INodeProvider> 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<INodeProvider> RequestNode(vint index)override; public: /// <summary>Create an item provider using a node root provider.</summary> /// <param name="_root">The node root provider.</param> NodeItemProvider(Ptr<INodeRootProvider> _root); ~NodeItemProvider(); /// <summary>Get the owned node root provider.</summary> /// <returns>The node root provider.</returns> Ptr<INodeRootProvider> GetRoot(); vint Count()override; WString GetTextValue(vint itemIndex)override; description::Value GetBindingValue(vint itemIndex)override; IDescriptable* RequestView(const WString& identifier)override; }; } /*********************************************************************** MemoryNodeProvider ***********************************************************************/ namespace tree { /// <summary>An in-memory <see cref="INodeProvider"/> implementation.</summary> class MemoryNodeProvider : public Object , public virtual INodeProvider , public Description<MemoryNodeProvider> { typedef collections::List<Ptr<MemoryNodeProvider>> ChildList; typedef collections::IEnumerator<Ptr<MemoryNodeProvider>> ChildListEnumerator; public: class NodeCollection : public collections::ObservableListBase<Ptr<MemoryNodeProvider>> { 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<MemoryNodeProvider> const& child)override; bool QueryRemove(vint index, Ptr<MemoryNodeProvider> const& child)override; void BeforeInsert(vint index, Ptr<MemoryNodeProvider> const& child)override; void BeforeRemove(vint index, Ptr<MemoryNodeProvider> const& child)override; void AfterInsert(vint index, Ptr<MemoryNodeProvider> 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<DescriptableObject> data; NodeCollection children; virtual INodeProviderCallback* GetCallbackProxyInternal(); void OnChildTotalVisibleNodesChanged(vint offset); public: /// <summary>Create a node provider with a data object.</summary> /// <param name="_data">The data object.</param> MemoryNodeProvider(Ptr<DescriptableObject> _data = nullptr); ~MemoryNodeProvider(); /// <summary>Get the data object.</summary> /// <returns>The data object.</returns> Ptr<DescriptableObject> GetData(); /// <summary>Set the data object.</summary> /// <param name="value">The data object.</param> void SetData(const Ptr<DescriptableObject>& value); /// <summary>Notify that the state in the binded data object is modified.</summary> void NotifyDataModified(); /// <summary>Get all sub nodes.</summary> /// <returns>All sub nodes.</returns> NodeCollection& Children(); bool GetExpanding()override; void SetExpanding(bool value)override; vint CalculateTotalVisibleNodes()override; vint GetChildCount()override; Ptr<INodeProvider> GetParent()override; Ptr<INodeProvider> GetChild(vint index)override; }; /// <summary>A general implementation for <see cref="INodeRootProvider"/>.</summary> class NodeRootProviderBase : public virtual INodeRootProvider, protected virtual INodeProviderCallback, public Description<NodeRootProviderBase> { collections::List<INodeProviderCallback*> 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: /// <summary>Create a node root provider.</summary> NodeRootProviderBase(); ~NodeRootProviderBase(); bool CanGetNodeByVisibleIndex()override; Ptr<INodeProvider> GetNodeByVisibleIndex(vint index)override; bool AttachCallback(INodeProviderCallback* value)override; bool DetachCallback(INodeProviderCallback* value)override; IDescriptable* RequestView(const WString& identifier)override; }; /// <summary>An in-memory <see cref="INodeRootProvider"/> implementation.</summary> class MemoryNodeRootProvider : public MemoryNodeProvider , public NodeRootProviderBase , public Description<MemoryNodeRootProvider> { protected: INodeProviderCallback* GetCallbackProxyInternal()override; public: /// <summary>Create a node root provider.</summary> MemoryNodeRootProvider(); ~MemoryNodeRootProvider(); Ptr<INodeProvider> GetRootNode()override; /// <summary>Get the <see cref="MemoryNodeProvider"/> object from an <see cref="INodeProvider"/> object.</summary> /// <returns>The corresponding <see cref="MemoryNodeProvider"/> object.</returns> /// <param name="node">The node to get the memory node.</param> MemoryNodeProvider* GetMemoryNode(INodeProvider* node); }; } /*********************************************************************** GuiVirtualTreeListControl ***********************************************************************/ /// <summary>Tree list control in virtual node.</summary> class GuiVirtualTreeListControl : public GuiSelectableListControl, protected virtual tree::INodeProviderCallback, public Description<GuiVirtualTreeListControl> { 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: /// <summary>Create a tree list control in virtual mode.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_nodeRootProvider">The node root provider for this control.</param> GuiVirtualTreeListControl(theme::ThemeName themeName, Ptr<tree::INodeRootProvider> _nodeRootProvider); ~GuiVirtualTreeListControl(); /// <summary>Node left mouse button down event.</summary> compositions::GuiNodeMouseEvent NodeLeftButtonDown; /// <summary>Node left mouse button up event.</summary> compositions::GuiNodeMouseEvent NodeLeftButtonUp; /// <summary>Node left mouse button double click event.</summary> compositions::GuiNodeMouseEvent NodeLeftButtonDoubleClick; /// <summary>Node middle mouse button down event.</summary> compositions::GuiNodeMouseEvent NodeMiddleButtonDown; /// <summary>Node middle mouse button up event.</summary> compositions::GuiNodeMouseEvent NodeMiddleButtonUp; /// <summary>Node middle mouse button double click event.</summary> compositions::GuiNodeMouseEvent NodeMiddleButtonDoubleClick; /// <summary>Node right mouse button down event.</summary> compositions::GuiNodeMouseEvent NodeRightButtonDown; /// <summary>Node right mouse button up event.</summary> compositions::GuiNodeMouseEvent NodeRightButtonUp; /// <summary>Node right mouse button double click event.</summary> compositions::GuiNodeMouseEvent NodeRightButtonDoubleClick; /// <summary>Node mouse move event.</summary> compositions::GuiNodeMouseEvent NodeMouseMove; /// <summary>Node mouse enter event.</summary> compositions::GuiNodeNotifyEvent NodeMouseEnter; /// <summary>Node mouse leave event.</summary> compositions::GuiNodeNotifyEvent NodeMouseLeave; /// <summary>Node expanded event.</summary> compositions::GuiNodeNotifyEvent NodeExpanded; /// <summary>Node collapsed event.</summary> compositions::GuiNodeNotifyEvent NodeCollapsed; /// <summary>Get the <see cref="tree::INodeItemView"/> from the item provider.</summary> /// <returns>The <see cref="tree::INodeItemView"/> from the item provider.</returns> tree::INodeItemView* GetNodeItemView(); /// <summary>Get the binded node root provider.</summary> /// <returns>The binded node root provider.</returns> tree::INodeRootProvider* GetNodeRootProvider(); }; /*********************************************************************** TreeViewItemRootProvider ***********************************************************************/ namespace tree { /// <summary>The required <see cref="INodeRootProvider"/> view for [T:vl.presentation.controls.GuiVirtualTreeView].</summary> class ITreeViewItemView : public virtual IDescriptable, public Description<ITreeViewItemView> { public: /// <summary>The identifier of this view.</summary> static const wchar_t* const Identifier; /// <summary>Get the image of a node.</summary> /// <returns>Get the image of a node.</returns> /// <param name="node">The node.</param> virtual Ptr<GuiImageData> GetNodeImage(INodeProvider* node)=0; }; /// <summary>A tree view item. This data structure is used in [T:vl.presentation.controls.tree.TreeViewItemRootProvider].</summary> class TreeViewItem : public Object, public Description<TreeViewItem> { public: /// <summary>The image of this item.</summary> Ptr<GuiImageData> image; /// <summary>The text of this item.</summary> WString text; /// <summary>Tag object.</summary> description::Value tag; /// <summary>Create a tree view item.</summary> TreeViewItem(); /// <summary>Create a tree view item with specified image and text.</summary> /// <param name="_image">The specified image.</param> /// <param name="_text">The specified text.</param> TreeViewItem(const Ptr<GuiImageData>& _image, const WString& _text); }; /// <summary>The default implementation of <see cref="INodeRootProvider"/> for [T:vl.presentation.controls.GuiVirtualTreeView].</summary> class TreeViewItemRootProvider : public MemoryNodeRootProvider , public virtual ITreeViewItemView , public Description<TreeViewItemRootProvider> { protected: Ptr<GuiImageData> GetNodeImage(INodeProvider* node)override; WString GetTextValue(INodeProvider* node)override; description::Value GetBindingValue(INodeProvider* node)override; public: /// <summary>Create a item root provider.</summary> TreeViewItemRootProvider(); ~TreeViewItemRootProvider(); IDescriptable* RequestView(const WString& identifier)override; /// <summary>Get the <see cref="TreeViewItem"/> object from a node.</summary> /// <returns>The <see cref="TreeViewItem"/> object.</returns> /// <param name="node">The node to get the tree view item.</param> Ptr<TreeViewItem> GetTreeViewData(INodeProvider* node); /// <summary>Set the <see cref="TreeViewItem"/> object to a node.</summary> /// <param name="node">The node.</param> /// <param name="value">The <see cref="TreeViewItem"/> object.</param> void SetTreeViewData(INodeProvider* node, Ptr<TreeViewItem> value); /// <summary>Notify the tree view control that the node is changed. This is required when content in a <see cref="TreeViewItem"/> is modified, but both <see cref="SetTreeViewData"/> or [M:vl.presentation.controls.tree.MemoryNodeProvider.SetData] are not called.</summary> /// <param name="node">The node.</param> void UpdateTreeViewData(INodeProvider* node); }; } /*********************************************************************** GuiVirtualTreeView ***********************************************************************/ /// <summary>Tree view control in virtual mode.</summary> class GuiVirtualTreeView : public GuiVirtualTreeListControl, public Description<GuiVirtualTreeView> { 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: /// <summary>Create a tree view control in virtual mode.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_nodeRootProvider">The node root provider for this control.</param> GuiVirtualTreeView(theme::ThemeName themeName, Ptr<tree::INodeRootProvider> _nodeRootProvider); ~GuiVirtualTreeView(); }; /*********************************************************************** GuiTreeView ***********************************************************************/ /// <summary>Tree view control.</summary> class GuiTreeView : public GuiVirtualTreeView, public Description<GuiTreeView> { protected: Ptr<tree::TreeViewItemRootProvider> nodes; public: /// <summary>Create a tree view control.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiTreeView(theme::ThemeName themeName); ~GuiTreeView(); /// <summary>Get the <see cref="tree::TreeViewItemRootProvider"/> as a node root providerl.</summary> /// <returns>The <see cref="tree::TreeViewItemRootProvider"/> as a node root provider.</returns> Ptr<tree::TreeViewItemRootProvider> Nodes(); /// <summary>Get the selected item.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> Ptr<tree::TreeViewItem> 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<presentation::controls::tree::MemoryNodeProvider> { static const bool CanRead = true; static const bool CanResize = false; }; } } } #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; /// <summary>IGuiMenuService is a required service for menu item container.</summary> class IGuiMenuService : public virtual IDescriptable, public Description<IGuiMenuService> { public: /// <summary>The identifier for this service.</summary> static const wchar_t* const Identifier; /// <summary>Direction to decide the position for a menu with specified control.</summary> enum Direction { /// <summary>Aligned to the top or bottom side.</summary> Horizontal, /// <summary>Aligned to the left or right side.</summary> Vertical, }; protected: GuiMenu* openingMenu; public: IGuiMenuService(); /// <summary>Get the parent service. This service represents the parent menu that host the menu item control that contains this menu.</summary> /// <returns>The parent service.</returns> virtual IGuiMenuService* GetParentMenuService()=0; /// <summary>Get the preferred direction to open the sub menu.</summary> /// <returns>The preferred direction to open the sub menu.</returns> virtual Direction GetPreferredDirection()=0; /// <summary>Test is this menu is active. When an menu is active, the sub menu is automatically opened when the corresponding menu item is opened.</summary> /// <returns>Returns true if this menu is active.</returns> virtual bool IsActiveState()=0; /// <summary>Test all sub menu items are actived by mouse down.</summary> /// <returns>Returns true if all sub menu items are actived by mouse down.</returns> virtual bool IsSubMenuActivatedByMouseDown()=0; /// <summary>Called when the menu item is executed.</summary> virtual void MenuItemExecuted(); /// <summary>Get the opening sub menu.</summary> /// <returns>The opening sub menu.</returns> virtual GuiMenu* GetOpeningMenu(); /// <summary>Called when the sub menu is opened.</summary> /// <param name="menu">The sub menu.</param> virtual void MenuOpened(GuiMenu* menu); /// <summary>Called when the sub menu is closed.</summary> /// <param name="menu">The sub menu.</param> virtual void MenuClosed(GuiMenu* menu); }; /// <summary>IGuiMenuService is a required service to tell a ribbon group that this control has a dropdown to display.</summary> class IGuiMenuDropdownProvider : public virtual IDescriptable, public Description<IGuiMenuDropdownProvider> { public: /// <summary>The identifier for this service.</summary> static const wchar_t* const Identifier; /// <summary>Get the dropdown to display.</summary> /// <returns>The dropdown to display. Returns null to indicate the dropdown cannot be displaied temporary.</returns> virtual GuiMenu* ProvideDropdownMenu() = 0; }; /*********************************************************************** Menu ***********************************************************************/ /// <summary>Popup menu.</summary> class GuiMenu : public GuiPopup, protected IGuiMenuService, public Description<GuiMenu> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(MenuTemplate, GuiPopup) private: IGuiMenuService* parentMenuService; IGuiMenuService* GetParentMenuService()override; Direction GetPreferredDirection()override; bool IsActiveState()override; bool IsSubMenuActivatedByMouseDown()override; void MenuItemExecuted()override; protected: GuiControl* owner; void OnDeactivatedAltHost()override; void MouseClickedOnOtherWindow(GuiWindow* window)override; void OnWindowOpened(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnWindowClosed(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_owner">The owner menu item of the parent menu.</param> GuiMenu(theme::ThemeName themeName, GuiControl* _owner); ~GuiMenu(); /// <summary>Update the reference to the parent <see cref="IGuiMenuService"/>. This function is not required to call outside the menu or menu item control.</summary> void UpdateMenuService(); IDescriptable* QueryService(const WString& identifier)override; }; /// <summary>Menu bar.</summary> class GuiMenuBar : public GuiControl, protected IGuiMenuService, public Description<GuiMenuBar> { private: IGuiMenuService* GetParentMenuService()override; Direction GetPreferredDirection()override; bool IsActiveState()override; bool IsSubMenuActivatedByMouseDown()override; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiMenuBar(theme::ThemeName themeName); ~GuiMenuBar(); IDescriptable* QueryService(const WString& identifier)override; }; /*********************************************************************** MenuButton ***********************************************************************/ /// <summary>Menu item.</summary> class GuiMenuButton : public GuiSelectableButton, private IGuiMenuDropdownProvider, public Description<GuiMenuButton> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ToolstripButtonTemplate, GuiSelectableButton) using IEventHandler = compositions::IGuiGraphicsEventHandler; protected: Ptr<IEventHandler> hostClickedHandler; Ptr<IEventHandler> hostMouseEnterHandler; Ptr<GuiImageData> image; Ptr<GuiImageData> largeImage; WString shortcutText; GuiMenu* subMenu; bool ownedSubMenu; Size preferredMenuClientSize; IGuiMenuService* ownerMenuService; bool cascadeAction; GuiButton* GetSubMenuHost(); void OpenSubMenuInternal(); void OnParentLineChanged()override; bool IsAltAvailable()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: GuiMenu* ProvideDropdownMenu()override; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiMenuButton(theme::ThemeName themeName); ~GuiMenuButton(); /// <summary>Before sub menu opening event.</summary> compositions::GuiNotifyEvent BeforeSubMenuOpening; /// <summary>Sub menu opening changed event.</summary> compositions::GuiNotifyEvent SubMenuOpeningChanged; /// <summary>Large image changed event.</summary> compositions::GuiNotifyEvent LargeImageChanged; /// <summary>Image changed event.</summary> compositions::GuiNotifyEvent ImageChanged; /// <summary>Shortcut text changed event.</summary> compositions::GuiNotifyEvent ShortcutTextChanged; /// <summary>Get the large image for the menu button.</summary> /// <returns>The large image for the menu button.</returns> Ptr<GuiImageData> GetLargeImage(); /// <summary>Set the large image for the menu button.</summary> /// <param name="value">The large image for the menu button.</param> void SetLargeImage(Ptr<GuiImageData> value); /// <summary>Get the image for the menu button.</summary> /// <returns>The image for the menu button.</returns> Ptr<GuiImageData> GetImage(); /// <summary>Set the image for the menu button.</summary> /// <param name="value">The image for the menu button.</param> void SetImage(Ptr<GuiImageData> value); /// <summary>Get the shortcut key text for the menu button.</summary> /// <returns>The shortcut key text for the menu button.</returns> const WString& GetShortcutText(); /// <summary>Set the shortcut key text for the menu button.</summary> /// <param name="value">The shortcut key text for the menu button.</param> void SetShortcutText(const WString& value); /// <summary>Test does the sub menu exist.</summary> /// <returns>Returns true if the sub menu exists.</returns> bool IsSubMenuExists(); /// <summary>Get the sub menu. If the sub menu is not created, it returns null.</summary> /// <returns>The sub menu.</returns> GuiMenu* GetSubMenu(); /// <summary>Create the sub menu if necessary. The created sub menu is owned by this menu button.</summary> /// <returns>The created sub menu.</returns> /// <param name="subMenuTemplate">The style controller for the sub menu. Set to null to use the default control template.</param> GuiMenu* CreateSubMenu(TemplateProperty<templates::GuiMenuTemplate> subMenuTemplate = {}); /// <summary>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.</summary> /// <param name="value">The sub menu to associate.</param> /// <param name="owned">Set to true if the menu is expected to be owned.</param> void SetSubMenu(GuiMenu* value, bool owned); /// <summary>Destroy the sub menu if necessary.</summary> void DestroySubMenu(); /// <summary>Test is the sub menu owned by this menu button. If the sub menu is owned, both deleting this menu button or calling <see cref="DestroySubMenu"/> will delete the sub menu.</summary> /// <returns>Returns true if the sub menu is owned by this menu button.</returns> bool GetOwnedSubMenu(); /// <summary>Test is the sub menu opened.</summary> /// <returns>Returns true if the sub menu is opened.</returns> bool GetSubMenuOpening(); /// <summary>Open or close the sub menu.</summary> /// <param name="value">Set to true to open the sub menu.</param> void SetSubMenuOpening(bool value); /// <summary>Get the preferred client size for the sub menu.</summary> /// <returns>The preferred client size for the sub menu.</returns> Size GetPreferredMenuClientSize(); /// <summary>Set the preferred client size for the sub menu.</summary> /// <param name="value">The preferred client size for the sub menu.</param> void SetPreferredMenuClientSize(Size value); /// <summary>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 <see cref="IGuiMenuService::IsActiveState"/>), closing the sub menu will also close the parent menu.</summary> /// <returns>Returns true if cascade action is enabled.</returns> bool GetCascadeAction(); /// <summary>Enable or disable cascade action.</summary> /// <param name="value">Set to true to enable cascade action.</param> void SetCascadeAction(bool value); IDescriptable* QueryService(const WString& identifier)override; }; } } } #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 { using namespace reflection; /*********************************************************************** IGuiResourceManager ***********************************************************************/ class GuiResourceClassNameRecord : public Object, public Description<GuiResourceClassNameRecord> { public: collections::List<WString> classNames; collections::Dictionary<WString, Ptr<GuiResourceItem>> classResources; }; class IGuiResourceManager : public IDescriptable, public Description<IGuiResourceManager> { public: virtual bool SetResource(Ptr<GuiResource> resource, GuiResourceUsage usage = GuiResourceUsage::DataOnly) = 0; virtual Ptr<GuiResource> GetResource(const WString& name) = 0; virtual Ptr<GuiResource> GetResourceFromClassName(const WString& classFullName) = 0; virtual void UnloadResource(const WString& name) = 0; virtual void LoadResourceOrPending(stream::IStream& stream, GuiResourceUsage usage = GuiResourceUsage::DataOnly) = 0; virtual void GetPendingResourceNames(collections::List<WString>& names) = 0; }; extern IGuiResourceManager* GetResourceManager(); } } #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<GuiCommonDatePickerLook> { 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<GuiSelectableButtonTemplate> dateButtonTemplate; TemplateProperty<GuiTextListTemplate> dateTextListTemplate; TemplateProperty<GuiComboBoxTemplate> 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<elements::GuiSolidLabelElement*> labelDaysOfWeek; collections::Array<controls::GuiSelectableButton*> buttonDays; collections::Array<elements::GuiSolidLabelElement*> labelDays; collections::Array<DateTime> dateDays; void SetDay(const DateTime& day, vint& index, bool currentMonth); 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<GuiSelectableButtonTemplate> GetDateButtonTemplate(); void SetDateButtonTemplate(const TemplateProperty<GuiSelectableButtonTemplate>& value); TemplateProperty<GuiTextListTemplate> GetDateTextListTemplate(); void SetDateTextListTemplate(const TemplateProperty<GuiTextListTemplate>& value); TemplateProperty<GuiComboBoxTemplate> GetDateComboBoxTemplate(); void SetDateComboBoxTemplate(const TemplateProperty<GuiComboBoxTemplate>& 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<GuiCommonScrollViewLook> { 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<GuiScrollTemplate> hScrollTemplate; TemplateProperty<GuiScrollTemplate> 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<GuiScrollTemplate> GetHScrollTemplate(); void SetHScrollTemplate(const TemplateProperty<GuiScrollTemplate>& value); TemplateProperty<GuiScrollTemplate> GetVScrollTemplate(); void SetVScrollTemplate(const TemplateProperty<GuiScrollTemplate>& value); }; /*********************************************************************** GuiCommonScrollBehavior ***********************************************************************/ class GuiCommonScrollBehavior : public controls::GuiComponent, public Description<GuiCommonScrollBehavior> { 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(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 }; /// <summary>Theme interface. A theme creates appropriate style controllers or style providers for default controls. Call [M:vl.presentation.theme.GetCurrentTheme] to access this interface.</summary> class ITheme : public virtual IDescriptable, public Description<ITheme> { public: virtual TemplateProperty<templates::GuiControlTemplate> CreateStyle(ThemeName themeName) = 0; }; class Theme; /// <summary>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.</summary> class ThemeTemplates : public controls::GuiInstanceRootObject, public AggregatableDescription<ThemeTemplates> { 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<templates::Gui##TEMPLATE> CONTROL; GUI_CONTROL_TEMPLATE_TYPES(GUI_DEFINE_ITEM_PROPERTY) #undef GUI_DEFINE_ITEM_PROPERTY }; /// <summary>Get the current theme style factory object. Call <see cref="RegisterTheme"/> or <see cref="UnregisterTheme"/> to change the default theme.</summary> /// <returns>The current theme style factory object.</returns> extern ITheme* GetCurrentTheme(); extern void InitializeTheme(); extern void FinalizeTheme(); /// <summary>Register a control template collection object.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="theme">The control template collection object.</param> extern bool RegisterTheme(Ptr<ThemeTemplates> theme); /// <summary>Unregister a control template collection object.</summary> /// <returns>The registered object. Returns null if it does not exist.</returns> /// <param name="name">The name of the theme.</param> extern Ptr<ThemeTemplates> UnregisterTheme(const WString& name); } } } #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 { /// <summary>Ranged item arranger. This arranger implements most of the common functionality for those arrangers that display a continuing subset of item at a time.</summary> class RangedItemArrangerBase : public Object, virtual public GuiListControl::IItemArranger, public Description<RangedItemArrangerBase> { protected: using ItemStyleRecord = collections::Pair<GuiListControl::ItemStyle*, GuiSelectableButton*>; typedef collections::List<ItemStyleRecord> 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, 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: /// <summary>Create the arranger.</summary> 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; }; /// <summary>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.</summary> class FixedHeightItemArranger : public RangedItemArrangerBase, public Description<FixedHeightItemArranger> { 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, 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: /// <summary>Create the arranger.</summary> FixedHeightItemArranger(); ~FixedHeightItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; /// <summary>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.</summary> class FixedSizeMultiColumnItemArranger : public RangedItemArrangerBase, public Description<FixedSizeMultiColumnItemArranger> { 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, 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: /// <summary>Create the arranger.</summary> FixedSizeMultiColumnItemArranger(); ~FixedSizeMultiColumnItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; /// <summary>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.</summary> class FixedHeightMultiColumnItemArranger : public RangedItemArrangerBase, public Description<FixedHeightMultiColumnItemArranger> { 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, 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: /// <summary>Create the arranger.</summary> FixedHeightMultiColumnItemArranger(); ~FixedHeightMultiColumnItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; } } } } #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 { ///<summary>List view column header control for detailed view.</summary> class GuiListViewColumnHeader : public GuiMenuButton, public Description<GuiListViewColumnHeader> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ListViewColumnHeaderTemplate, GuiMenuButton) protected: ColumnSortingState columnSortingState = ColumnSortingState::NotSorted; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiListViewColumnHeader(theme::ThemeName themeName); ~GuiListViewColumnHeader(); bool IsAltAvailable()override; /// <summary>Get the column sorting state.</summary> /// <returns>The column sorting state.</returns> ColumnSortingState GetColumnSortingState(); /// <summary>Set the column sorting state.</summary> /// <param name="value">The new column sorting state.</param> void SetColumnSortingState(ColumnSortingState value); }; /// <summary>List view base control. All list view controls inherit from this class.</summary> class GuiListViewBase : public GuiSelectableListControl, public Description<GuiListViewBase> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ListViewTemplate, GuiSelectableListControl) public: /// <summary>Create a list view base control.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_itemProvider">The item provider for this control.</param> GuiListViewBase(theme::ThemeName themeName, GuiListControl::IItemProvider* _itemProvider); ~GuiListViewBase(); /// <summary>Column clicked event.</summary> compositions::GuiItemNotifyEvent ColumnClicked; }; /*********************************************************************** ListView ItemStyleProvider ***********************************************************************/ namespace list { /// <summary>The required <see cref="GuiListControl::IItemProvider"/> view for <see cref="GuiVirtualListView"/>.</summary> class IListViewItemView : public virtual IDescriptable, public Description<IListViewItemView> { public: /// <summary>The identifier for this view.</summary> static const wchar_t* const Identifier; /// <summary>Get the small image of an item.</summary> /// <returns>The small image.</returns> /// <param name="itemIndex">The index of the item.</param> virtual Ptr<GuiImageData> GetSmallImage(vint itemIndex) = 0; /// <summary>Get the large image of an item.</summary> /// <returns>The large image.</returns> /// <param name="itemIndex">The index of the item.</param> virtual Ptr<GuiImageData> GetLargeImage(vint itemIndex) = 0; /// <summary>Get the text of an item.</summary> /// <returns>The text.</returns> /// <param name="itemIndex">The index of the item.</param> virtual WString GetText(vint itemIndex) = 0; /// <summary>Get the sub item text of an item. If the sub item index out of range, it returns an empty string.</summary> /// <returns>The sub item text.</returns> /// <param name="itemIndex">The index of the item.</param> /// <param name="index">The sub item index of the item.</param> virtual WString GetSubItem(vint itemIndex, vint index) = 0; /// <summary>Get the number of data columns.</summary> /// <returns>The number of data columns.</returns> virtual vint GetDataColumnCount() = 0; /// <summary>Get the column index of the index-th data column.</summary> /// <returns>The column index.</returns> /// <param name="index">The order of the data column.</param> virtual vint GetDataColumn(vint index) = 0; /// <summary>Get the number of all columns.</summary> /// <returns>The number of all columns.</returns> virtual vint GetColumnCount() = 0; /// <summary>Get the text of the column.</summary> /// <returns>The text of the column.</returns> /// <param name="index">The index of the column.</param> virtual WString GetColumnText(vint index) = 0; }; /*********************************************************************** ListViewColumnItemArranger ***********************************************************************/ /// <summary>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 <see cref="GuiListControl::IItemProvider"/>.</summary> class ListViewColumnItemArranger : public FixedHeightItemArranger, public Description<ListViewColumnItemArranger> { typedef collections::List<GuiListViewColumnHeader*> ColumnHeaderButtonList; typedef collections::List<compositions::GuiBoundsComposition*> ColumnHeaderSplitterList; public: static const vint SplitterWidth=8; /// <summary>Callback for [T:vl.presentation.controls.list.ListViewColumnItemArranger.IColumnItemView]. Column item view use this interface to notify column related modification.</summary> class IColumnItemViewCallback : public virtual IDescriptable, public Description<IColumnItemViewCallback> { public: /// <summary>Called when any column is changed (inserted, removed, text changed, etc.).</summary> virtual void OnColumnChanged()=0; }; /// <summary>The required <see cref="GuiListControl::IItemProvider"/> view for <see cref="ListViewColumnItemArranger"/>.</summary> class IColumnItemView : public virtual IDescriptable, public Description<IColumnItemView> { public: /// <summary>The identifier for this view.</summary> static const wchar_t* const Identifier; /// <summary>Attach an column item view callback to this view.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The column item view callback.</param> virtual bool AttachCallback(IColumnItemViewCallback* value)=0; /// <summary>Detach an column item view callback from this view.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The column item view callback.</param> virtual bool DetachCallback(IColumnItemViewCallback* value)=0; /// <summary>Get the size of the column.</summary> /// <returns>The size of the column.</returns> /// <param name="index">The index of the column.</param> virtual vint GetColumnSize(vint index)=0; /// <summary>Set the size of the column.</summary> /// <param name="index">The index of the column.</param> /// <param name="value">The new size of the column.</param> virtual void SetColumnSize(vint index, vint value)=0; /// <summary>Get the popup binded to the column.</summary> /// <returns>The popup binded to the column.</returns> /// <param name="index">The index of the column.</param> virtual GuiMenu* GetDropdownPopup(vint index)=0; /// <summary>Get the sorting state of the column.</summary> /// <returns>The sorting state of the column.</returns> /// <param name="index">The index of the column.</param> 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> 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<WString> { friend class ListViewItem; protected: ListViewItem* owner; void NotifyUpdateInternal(vint start, vint count, vint newCount)override; public: }; class ListViewItemProvider; /// <summary>List view item.</summary> class ListViewItem : public Object, public Description<ListViewItem> { friend class ListViewSubItems; friend class ListViewItemProvider; protected: ListViewItemProvider* owner; ListViewSubItems subItems; Ptr<GuiImageData> smallImage; Ptr<GuiImageData> largeImage; WString text; description::Value tag; void NotifyUpdate(); public: /// <summary>Create a list view item.</summary> ListViewItem(); /// <summary>Get all sub items of this item.</summary> /// <returns>All sub items of this item.</returns> ListViewSubItems& GetSubItems(); /// <summary>Get the small image of this item.</summary> /// <returns>The small image of this item.</returns> Ptr<GuiImageData> GetSmallImage(); /// <summary>Set the small image of this item.</summary> /// <param name="value">The small image of this item.</param> void SetSmallImage(Ptr<GuiImageData> value); /// <summary>Get the large image of this item.</summary> /// <returns>The large image of this item.</returns> Ptr<GuiImageData> GetLargeImage(); /// <summary>Set the large image of this item.</summary> /// <param name="value">The large image of this item.</param> void SetLargeImage(Ptr<GuiImageData> value); /// <summary>Get the text of this item.</summary> /// <returns>The text of this item.</returns> const WString& GetText(); /// <summary>Set the text of this item.</summary> /// <param name="value">The text of this item.</param> void SetText(const WString& value); /// <summary>Get the tag of this item.</summary> /// <returns>The tag of this item.</returns> description::Value GetTag(); /// <summary>Set the tag of this item.</summary> /// <param name="value">The tag of this item.</param> void SetTag(const description::Value& value); }; class ListViewColumns; /// <summary>List view column.</summary> class ListViewColumn : public Object, public Description<ListViewColumn> { friend class ListViewColumns; protected: ListViewColumns* owner = nullptr; WString text; ItemProperty<WString> textProperty; vint size; bool ownPopup = true; GuiMenu* dropdownPopup = nullptr; ColumnSortingState sortingState = ColumnSortingState::NotSorted; void NotifyUpdate(bool affectItem); public: /// <summary>Create a column with the specified text and size.</summary> /// <param name="_text">The specified text.</param> /// <param name="_size">The specified size.</param> ListViewColumn(const WString& _text=L"", vint _size=160); ~ListViewColumn(); /// <summary>Get the text of this item.</summary> /// <returns>The text of this item.</returns> const WString& GetText(); /// <summary>Set the text of this item.</summary> /// <param name="value">The text of this item.</param> void SetText(const WString& value); /// <summary>Get the text property of this item.</summary> /// <returns>The text property of this item.</returns> ItemProperty<WString> GetTextProperty(); /// <summary>Set the text property of this item.</summary> /// <param name="value">The text property of this item.</param> void SetTextProperty(const ItemProperty<WString>& value); /// <summary>Get the size of this item.</summary> /// <returns>The size of this item.</returns> vint GetSize(); /// <summary>Set the size of this item.</summary> /// <param name="value">The size of this item.</param> void SetSize(vint value); /// <summary>Test if the column owns the popup. Owned popup will be deleted in the destructor.</summary> /// <returns>Returns true if the column owns the popup.</returns> bool GetOwnPopup(); /// <summary>Set if the column owns the popup.</summary> /// <param name="value">Set to true to let the column own the popup.</param> void SetOwnPopup(bool value); /// <summary>Get the dropdown context menu of this item.</summary> /// <returns>The dropdown context menu of this item.</returns> GuiMenu* GetDropdownPopup(); /// <summary>Set the dropdown context menu of this item.</summary> /// <param name="value">The dropdown context menu of this item.</param> void SetDropdownPopup(GuiMenu* value); /// <summary>Get the sorting state of this item.</summary> /// <returns>The sorting state of this item.</returns> ColumnSortingState GetSortingState(); /// <summary>Set the sorting state of this item.</summary> /// <param name="value">The sorting state of this item.</param> void SetSortingState(ColumnSortingState value); }; class IListViewItemProvider : public virtual Interface { public: virtual void NotifyAllItemsUpdate() = 0; virtual void NotifyAllColumnsUpdate() = 0; }; /// <summary>List view data column container.</summary> class ListViewDataColumns : public collections::ObservableListBase<vint> { protected: IListViewItemProvider* itemProvider; void NotifyUpdateInternal(vint start, vint count, vint newCount)override; public: /// <summary>Create a container.</summary> /// <param name="_itemProvider">The item provider in the same control to receive notifications.</param> ListViewDataColumns(IListViewItemProvider* _itemProvider); ~ListViewDataColumns(); }; /// <summary>List view column container.</summary> class ListViewColumns : public collections::ObservableListBase<Ptr<ListViewColumn>> { friend class ListViewColumn; protected: IListViewItemProvider* itemProvider; bool affectItemFlag = true; void NotifyColumnUpdated(vint column, bool affectItem); void AfterInsert(vint index, const Ptr<ListViewColumn>& value)override; void BeforeRemove(vint index, const Ptr<ListViewColumn>& value)override; void NotifyUpdateInternal(vint start, vint count, vint newCount)override; public: /// <summary>Create a container.</summary> /// <param name="_itemProvider">The item provider in the same control to receive notifications.</param> ListViewColumns(IListViewItemProvider* _itemProvider); ~ListViewColumns(); }; /// <summary>Item provider for <see cref="GuiListViewBase"/>.</summary> class ListViewItemProvider : public ListProvider<Ptr<ListViewItem>> , protected virtual IListViewItemProvider , public virtual IListViewItemView , public virtual ListViewColumnItemArranger::IColumnItemView , public Description<ListViewItemProvider> { friend class ListViewItem; friend class ListViewColumns; friend class ListViewDataColumns; typedef collections::List<ListViewColumnItemArranger::IColumnItemViewCallback*> ColumnItemViewCallbackList; protected: ListViewDataColumns dataColumns; ListViewColumns columns; ColumnItemViewCallbackList columnItemViewCallbacks; void AfterInsert(vint index, const Ptr<ListViewItem>& value)override; void BeforeRemove(vint index, const Ptr<ListViewItem>& value)override; void NotifyAllItemsUpdate()override; void NotifyAllColumnsUpdate()override; Ptr<GuiImageData> GetSmallImage(vint itemIndex)override; Ptr<GuiImageData> 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; /// <summary>Get all data columns indices in columns.</summary> /// <returns>All data columns indices in columns.</returns> ListViewDataColumns& GetDataColumns(); /// <summary>Get all columns.</summary> /// <returns>All columns.</returns> ListViewColumns& GetColumns(); }; } /*********************************************************************** GuiVirtualListView ***********************************************************************/ enum class ListViewView { BigIcon, SmallIcon, List, Tile, Information, Detail, Unknown, }; /// <summary>List view control in virtual mode.</summary> class GuiVirtualListView : public GuiListViewBase, public Description<GuiVirtualListView> { protected: ListViewView view = ListViewView::Unknown; void OnStyleInstalled(vint itemIndex, ItemStyle* style)override; void OnItemTemplateChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// <summary>Create a list view control in virtual mode.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_itemProvider">The item provider for this control.</param> GuiVirtualListView(theme::ThemeName themeName, GuiListControl::IItemProvider* _itemProvider); ~GuiVirtualListView(); /// <summary>Get the current view.</summary> /// <returns>The current view. After [M:vl.presentation.controls.GuiListControl.SetItemTemplate] is called, the current view is reset to Unknown.</returns> ListViewView GetView(); /// <summary>Set the current view.</summary> /// <param name="_view">The current view.</param> void SetView(ListViewView _view); }; /*********************************************************************** GuiListView ***********************************************************************/ /// <summary>List view control in virtual mode.</summary> class GuiListView : public GuiVirtualListView, public Description<GuiListView> { protected: list::ListViewItemProvider* items; public: /// <summary>Create a list view control.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiListView(theme::ThemeName themeName); ~GuiListView(); /// <summary>Get all list view items.</summary> /// <returns>All list view items.</returns> list::ListViewItemProvider& GetItems(); /// <summary>Get all data columns indices in columns.</summary> /// <returns>All data columns indices in columns.</returns> list::ListViewDataColumns& GetDataColumns(); /// <summary>Get all columns.</summary> /// <returns>All columns.</returns> list::ListViewColumns& GetColumns(); /// <summary>Get the selected item.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> Ptr<list::ListViewItem> GetSelectedItem(); }; } } } #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 ***********************************************************************/ /// <summary>The base class of combo box control.</summary> class GuiComboBoxBase : public GuiMenuButton, public Description<GuiComboBoxBase> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(ComboBoxTemplate, GuiMenuButton) protected: class CommandExecutor : public Object, public virtual IComboBoxCommandExecutor { protected: GuiComboBoxBase* combo; public: CommandExecutor(GuiComboBoxBase* _combo); ~CommandExecutor(); void SelectItem()override; }; Ptr<CommandExecutor> commandExecutor; bool IsAltAvailable()override; IGuiMenuService::Direction GetSubMenuDirection()override; virtual void SelectItem(); void OnBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiComboBoxBase(theme::ThemeName themeName); ~GuiComboBoxBase(); /// <summary>Item selected event.</summary> compositions::GuiNotifyEvent ItemSelected; }; /*********************************************************************** ComboBox with GuiListControl ***********************************************************************/ /// <summary>Combo box list control. This control is a combo box with a list control in its popup.</summary> class GuiComboBoxListControl : public GuiComboBoxBase , private GuiListControl::IItemProviderCallback , public Description<GuiComboBoxListControl> { public: using ItemStyleProperty = TemplateProperty<templates::GuiTemplate>; protected: GuiSelectableListControl* containedListControl = nullptr; ItemStyleProperty itemStyleProperty; templates::GuiTemplate* itemStyleController = nullptr; Ptr<compositions::IGuiGraphicsEventHandler> boundsChangedHandler; void BeforeControlTemplateUninstalled()override; void AfterControlTemplateInstalled(bool initialize)override; bool IsAltAvailable()override; void OnActiveAlt()override; void RemoveStyleController(); void InstallStyleController(vint itemIndex); virtual void DisplaySelectedContent(vint itemIndex); void AdoptSubMenuSize(); void OnTextChanged(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); void OnListControlAdoptedSizeInvalidated(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnListControlBoundsChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnListControlSelectionChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); private: // ===================== GuiListControl::IItemProviderCallback ===================== void OnAttached(GuiListControl::IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; public: /// <summary>Create a control with a specified default theme and a list control that will be put in the popup control to show all items.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_containedListControl">The list controller.</param> GuiComboBoxListControl(theme::ThemeName themeName, GuiSelectableListControl* _containedListControl); ~GuiComboBoxListControl(); /// <summary>Style provider changed event.</summary> compositions::GuiNotifyEvent ItemTemplateChanged; /// <summary>Selected index changed event.</summary> compositions::GuiNotifyEvent SelectedIndexChanged; /// <summary>Get the list control.</summary> /// <returns>The list control.</returns> GuiSelectableListControl* GetContainedListControl(); /// <summary>Get the item style provider.</summary> /// <returns>The item style provider.</returns> virtual ItemStyleProperty GetItemTemplate(); /// <summary>Set the item style provider</summary> /// <param name="value">The new item style provider</param> virtual void SetItemTemplate(ItemStyleProperty value); /// <summary>Get the selected index.</summary> /// <returns>The selected index.</returns> vint GetSelectedIndex(); /// <summary>Set the selected index.</summary> /// <param name="value">The selected index.</param> void SetSelectedIndex(vint value); /// <summary>Get the selected item.</summary> /// <returns>The selected item.</returns> description::Value GetSelectedItem(); /// <summary>Get the item provider in the list control.</summary> /// <returns>The item provider in the list control.</returns> 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 ***********************************************************************/ /// <summary>Date picker control that display a calendar.</summary> class GuiDatePicker : public GuiControl, public Description<GuiDatePicker> { 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> commandExecutor; DateTime date; WString dateFormat; Locale dateLocale; void UpdateText(); public: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiDatePicker(theme::ThemeName themeName); ~GuiDatePicker(); /// <summary>Date changed event.</summary> compositions::GuiNotifyEvent DateChanged; /// <summary>Date navigated event. Called when the current month is changed.</summary> compositions::GuiNotifyEvent DateNavigated; /// <summary>Date selected event. Called when a day button is selected.</summary> compositions::GuiNotifyEvent DateSelected; /// <summary>Date format changed event.</summary> compositions::GuiNotifyEvent DateFormatChanged; /// <summary>Date locale changed event.</summary> compositions::GuiNotifyEvent DateLocaleChanged; /// <summary>Get the displayed date.</summary> /// <returns>The date.</returns> const DateTime& GetDate(); /// <summary>Display a date.</summary> /// <param name="value">The date.</param> void SetDate(const DateTime& value); /// <summary>Get the format.</summary> /// <returns>The format.</returns> const WString& GetDateFormat(); /// <summary>Set the format for the text of this control.</summary> /// <param name="value">The format.</param> void SetDateFormat(const WString& value); /// <summary>Get the locale.</summary> /// <returns>The locale.</returns> const Locale& GetDateLocale(); /// <summary>Set the locale to display texts.</summary> /// <param name="value">The locale.</param> void SetDateLocale(const Locale& value); void SetText(const WString& value)override; }; /*********************************************************************** DateComboBox ***********************************************************************/ /// <summary>A combo box control with a date picker control.</summary> class GuiDateComboBox : public GuiComboBoxBase, public Description<GuiDateComboBox> { 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: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_datePicker">The date picker control to show in the popup.</param> GuiDateComboBox(theme::ThemeName themeName, GuiDatePicker* _datePicker); ~GuiDateComboBox(); /// <summary>Selected data changed event.</summary> compositions::GuiNotifyEvent SelectedDateChanged; void SetFont(const FontProperties& value)override; /// <summary>Get the displayed date.</summary> /// <returns>The date.</returns> const DateTime& GetSelectedDate(); /// <summary>Display a date.</summary> /// <param name="value">The date.</param> void SetSelectedDate(const DateTime& value); /// <summary>Get the date picker control.</summary> /// <returns>The date picker control.</returns> GuiDatePicker* GetDatePicker(); }; } } } #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 ***********************************************************************/ /// <summary>An text edit callback for text box controls.</summary> class ICommonTextEditCallback : public virtual IDescriptable, public Description<ICommonTextEditCallback> { public: /// <summary>Callback data for text editing preview.</summary> struct TextEditPreviewStruct { /// <summary>The start position of the selection before replacing. This field can be modified.</summary> TextPos originalStart; /// <summary>The end position of the selection before replacing. This field can be modified.</summary> TextPos originalEnd; /// <summary>The text of the selection before replacing.</summary> WString originalText; /// <summary>The text of the selection after replacing. This field can be modified.</summary> WString inputText; /// <summary>The base edit version.</summary> vuint editVersion; /// <summary>True if this modification is raised by the keyboard.</summary> bool keyInput; TextEditPreviewStruct() :editVersion(0) ,keyInput(false) { } }; /// <summary>Callback data for text editing.</summary> struct TextEditNotifyStruct { /// <summary>The start position of the selection before replacing.</summary> TextPos originalStart; /// <summary>The end position of the selection before replacing.</summary> TextPos originalEnd; /// <summary>The text of the selection before replacing.</summary> WString originalText; /// <summary>The start position of the selection after replacing.</summary> TextPos inputStart; /// <summary>The end position of the selection after replacing.</summary> TextPos inputEnd; /// <summary>The text of the selection after replacing.</summary> WString inputText; /// <summary>The created edit version.</summary> vuint editVersion; /// <summary>True if this modification is raised by the keyboard.</summary> bool keyInput; TextEditNotifyStruct() :editVersion(0) ,keyInput(false) { } }; /// <summary>Callback data for text caret changing.</summary> struct TextCaretChangedStruct { /// <summary>The start position of the selection before caret changing.</summary> TextPos oldBegin; /// <summary>The end position of the selection before caret changing.</summary> TextPos oldEnd; /// <summary>The start position of the selection after caret changing.</summary> TextPos newBegin; /// <summary>The end position of the selection after caret changing.</summary> TextPos newEnd; /// <summary>The current edit version.</summary> vuint editVersion; TextCaretChangedStruct() :editVersion(0) { } }; /// <summary>Called when the callback is attached to a text box control.</summary> /// <param name="element">The element that used in the text box control.</param> /// <param name="elementModifyLock">The lock that pretect the element.</param> /// <param name="ownerComposition">The owner composition of this element.</param> /// <param name="editVersion">The current edit version.</param> virtual void Attach(elements::GuiColorizedTextElement* element, SpinLock& elementModifyLock, compositions::GuiGraphicsComposition* ownerComposition, vuint editVersion)=0; /// <summary>Called when the callback is detached from a text box control.</summary> virtual void Detach()=0; /// <summary>Called before the text is edited.</summary> /// <param name="arguments">The data for this callback.</param> virtual void TextEditPreview(TextEditPreviewStruct& arguments)=0; /// <summary>Called after the text is edited and before the caret is changed.</summary> /// <param name="arguments">The data for this callback.</param> virtual void TextEditNotify(const TextEditNotifyStruct& arguments)=0; /// <summary>Called after the caret is changed.</summary> /// <param name="arguments">The data for this callback.</param> virtual void TextCaretChanged(const TextCaretChangedStruct& arguments)=0; /// <summary>Called after the text is edited and after the caret is changed.</summary> /// <param name="editVersion">The current edit version.</param> virtual void TextEditFinished(vuint editVersion)=0; }; } } } #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 ***********************************************************************/ /// <summary>The base class of text box colorizer.</summary> class GuiTextBoxColorizerBase : public Object, public virtual ICommonTextEditCallback { public: typedef collections::Array<elements::text::ColorEntry> 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: /// <summary>Create a colorrizer.</summary> 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(); /// <summary>Get the lexical analyzer start state for the first line.</summary> /// <returns>The lexical analyzer start state for the first line.</returns> virtual vint GetLexerStartState()=0; /// <summary>Get the context sensitive start state for the first line.</summary> /// <returns>The context sensitive start state for the first line.</returns> virtual vint GetContextStartState()=0; /// <summary>Colorizer one line with a start state.</summary> /// <param name="lineIndex">Line index.</param> /// <param name="text">Text buffer.</param> /// <param name="colors">Color index buffer. The index should be in [0 .. [M:vl.presentation.controls.GuiTextBoxColorizerBase.GetColors]()-1].</param> /// <param name="length">The length of the buffer.</param> /// <param name="lexerState">The lexical analyzer state for this line. After executing this function, the new value of this argument indicates the new state.</param> /// <param name="contextState">The context sensitive state for this line. After executing this function, the new value of this argument indicates the new state.</param> virtual void ColorizeLineWithCRLF(vint lineIndex, const wchar_t* text, vuint32_t* colors, vint length, vint& lexerState, vint& contextState)=0; /// <summary>Get the supported colors ordered by their indices.</summary> /// <returns>The supported colors ordered by their indices.</returns> virtual const ColorArray& GetColors()=0; }; /*********************************************************************** GuiTextBoxRegexColorizer ***********************************************************************/ /// <summary>Regex based colorizer.</summary> class GuiTextBoxRegexColorizer : public GuiTextBoxColorizerBase { protected: Ptr<regex::RegexLexer> lexer; Ptr<regex::RegexLexerColorizer> colorizer; ColorArray colors; elements::text::ColorEntry defaultColor; collections::List<WString> tokenRegexes; collections::List<elements::text::ColorEntry> tokenColors; collections::List<elements::text::ColorEntry> extraTokenColors; static void ColorizerProc(void* argument, vint start, vint length, vint token); public: /// <summary>Create the colorizer.</summary> GuiTextBoxRegexColorizer(); ~GuiTextBoxRegexColorizer(); /// <summary>Get the default color.</summary> /// <returns>The default color.</returns> elements::text::ColorEntry GetDefaultColor(); /// <summary>Get all regular expressions for tokens.</summary> /// <returns>All regular expressions for tokens.</returns> collections::List<WString>& GetTokenRegexes(); /// <summary>Get all colors for tokens.</summary> /// <returns>All colors for tokens.</returns> collections::List<elements::text::ColorEntry>& GetTokenColors(); /// <summary>Get all colors for extra tokens.</summary> /// <returns>All colors for extra tokens.</returns> collections::List<elements::text::ColorEntry>& GetExtraTokenColors(); /// <summary>Get the first token index for the first extra token.</summary> /// <returns>The first token index for the first extra token. Returns -1 if this operation failed.</returns> vint GetExtraTokenIndexStart(); /// <summary>Set the default color. Call [M:vl.presentation.controls.GuiTextBoxRegexColorizer.Setup] after finishing all configuration.</summary> /// <returns>Returns the token index of this token. Returns -1 if this operation failed.</returns> /// <param name="value">The default color.</param> bool SetDefaultColor(elements::text::ColorEntry value); /// <summary>Add a token type. Call [M:vl.presentation.controls.GuiTextBoxRegexColorizer.Setup] after finishing all configuration.</summary> /// <returns>Returns the token index of this token. Returns -1 if this operation failed.</returns> /// <param name="regex">The regular expression for this token type.</param> /// <param name="color">The color for this token type.</param> vint AddToken(const WString& regex, elements::text::ColorEntry color); /// <summary>Add an extra token type. Call [M:vl.presentation.controls.GuiTextBoxRegexColorizer.Setup] after finishing all configuration.</summary> /// <returns>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.</returns> /// <param name="color">The color for this token type.</param> vint AddExtraToken(elements::text::ColorEntry color); /// <summary>Clear all token color settings.</summary> void ClearTokens(); /// <summary>Setup the colorizer. After that, the colorizer cannot be changed.</summary> void Setup(); /// <summary>Callback function to set context sensitive state and change token accordingly.</summary> /// <param name="lineIndex">Line index.</param> /// <param name="text">Text buffer.</param> /// <param name="start">The start position of the token.</param> /// <param name="length">The length of the token.</param> /// <param name="token">The token type. After executing this function, the new value of this argument indicates the new token type.</param> /// <param name="contextState">The context sensitive state. After executing this function, the new value of this argument indicates the new state.</param> 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\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 ***********************************************************************/ /// <summary>The base class of text box auto complete controller.</summary> class GuiTextBoxAutoCompleteBase : public Object, public virtual ICommonTextEditCallback { public: /// <summary>Represents an auto complete candidate item.</summary> struct AutoCompleteItem { /// <summary>Tag object for any purpose, e.g., data binding.</summary> description::Value tag; /// <summary>Display text for the item.</summary> WString text; }; /// <summary>Auto complete control provider.</summary> class IAutoCompleteControlProvider : public virtual Interface { public: /// <summary>Get the auto complete control that will be installed in a popup to show candidate items.</summary> /// <returns>The auto complete control.</returns> virtual GuiControl* GetAutoCompleteControl() = 0; /// <summary>Get the list control storing candidate items.</summary> /// <returns>The list control. It should be inside the auto complete control, or the auto complete control itself.</returns> virtual GuiSelectableListControl* GetListControl() = 0; /// <summary>Store candidate items in the list control.</summary> /// <param name="items">Candidate items.</param> virtual void SetSortedContent(const collections::List<AutoCompleteItem>& items) = 0; /// <summary>Get the numbers of all stored candidate items.</summary> /// <returns>The number of all stored candidate items.</returns> virtual vint GetItemCount() = 0; /// <summary>Get the text of a specified item.</summary> /// <param name="index">The index of the item.</param> /// <returns>The text of the item.</returns> virtual WString GetItemText(vint index) = 0; }; class TextListControlProvider : public Object, public virtual IAutoCompleteControlProvider { protected: GuiTextList* autoCompleteList; public: TextListControlProvider(TemplateProperty<templates::GuiTextListTemplate> controlTemplate = {}); ~TextListControlProvider(); GuiControl* GetAutoCompleteControl()override; GuiSelectableListControl* GetListControl()override; void SetSortedContent(const collections::List<AutoCompleteItem>& items)override; vint GetItemCount()override; WString GetItemText(vint index)override; }; protected: elements::GuiColorizedTextElement* element; SpinLock* elementModifyLock; compositions::GuiGraphicsComposition* ownerComposition; GuiPopup* autoCompletePopup; Ptr<IAutoCompleteControlProvider> autoCompleteControlProvider; TextPos autoCompleteStartPosition; bool IsPrefix(const WString& prefix, const WString& candidate); public: /// <summary>Create an auto complete.</summary> /// <param name="_autoCompleteControlProvider">A auto complete control provider. Set to null to use a default one.</param> GuiTextBoxAutoCompleteBase(Ptr<IAutoCompleteControlProvider> _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; /// <summary>Get the list state.</summary> /// <returns>Returns true if the list is visible.</returns> bool IsListOpening(); /// <summary>Notify the list to be visible.</summary> /// <param name="startPosition">The text position to show the list.</param> void OpenList(TextPos startPosition); /// <summary>Notify the list to be invisible.</summary> void CloseList(); /// <summary>Set the content of the list.</summary> /// <param name="items">The content of the list.</param> void SetListContent(const collections::List<AutoCompleteItem>& items); /// <summary>Get the last start position when the list is opened.</summary> /// <returns>The start position.</returns> TextPos GetListStartPosition(); /// <summary>Select the previous item.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool SelectPreviousListItem(); /// <summary>Select the next item.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool SelectNextListItem(); /// <summary>Apply the selected item into the text box.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool ApplySelectedListItem(); /// <summary>Get the selected item.</summary> /// <returns>The text of the selected item. Returns empty if there is no selected item.</returns> WString GetSelectedListItem(); /// <summary>Highlight a candidate item in the list.</summary> /// <param name="editingText">The text to match an item.</param> void HighlightList(const WString& editingText); }; } } } #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<Ptr<IEditStep>>; protected: collections::List<Ptr<IEditStep>> steps; vint firstFutureStep; vint savedStep; bool performingUndoRedo; void PushStep(Ptr<IEditStep> step); public: GuiGeneralUndoRedoProcessor(); ~GuiGeneralUndoRedoProcessor(); Event<void()> UndoRedoChanged; Event<void()> 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<DocumentModel> originalModel; TextPos inputStart; TextPos inputEnd; Ptr<DocumentModel> inputModel; ReplaceModelStruct() { } }; struct RenameStyleStruct { WString oldStyleName; WString newStyleName; RenameStyleStruct() { } }; struct SetAlignmentStruct { vint start; vint end; collections::Array<Nullable<Alignment>> originalAlignments; collections::Array<Nullable<Alignment>> 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<SetAlignmentStruct> 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<SetAlignmentStruct> 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 controls { /*********************************************************************** GuiDocumentCommonInterface ***********************************************************************/ class GuiDocumentCommonInterface; /// <summary>Embedded object in a document.</summary> class GuiDocumentItem : public Object, public Description<GuiDocumentItem> { friend class GuiDocumentCommonInterface; protected: bool visible = false; WString name; compositions::GuiBoundsComposition* container; bool owned = false; public: GuiDocumentItem(const WString& _name); ~GuiDocumentItem(); /// <summary>Get the container for all embedded controls and compositions in this item.</summary> /// <returns>The container.</returns> compositions::GuiGraphicsComposition* GetContainer(); /// <summary>Get the name of the document item.</summary> /// <returns>The name.</returns> WString GetName(); }; /// <summary>Document displayer control common interface for displaying <see cref="DocumentModel"/>.</summary> class GuiDocumentCommonInterface abstract : protected virtual elements::GuiDocumentElement::ICallback , public Description<GuiDocumentCommonInterface> { typedef collections::Dictionary<WString, Ptr<GuiDocumentItem>> DocumentItemMap; public: /// <summary>Represents the edit mode.</summary> enum EditMode { /// <summary>View the rich text only.</summary> ViewOnly, /// <summary>The rich text is selectable.</summary> Selectable, /// <summary>The rich text is editable.</summary> Editable, }; protected: Ptr<DocumentModel> baselineDocument; DocumentItemMap documentItems; GuiControl* documentControl = nullptr; elements::GuiDocumentElement* documentElement = nullptr; compositions::GuiBoundsComposition* documentComposition = nullptr; Ptr<DocumentHyperlinkRun::Package> activeHyperlinks; bool dragging = false; EditMode editMode = EditMode::ViewOnly; Ptr<GuiDocumentUndoRedoProcessor> undoRedoProcessor; Ptr<compositions::GuiShortcutKeyManager> internalShortcutKeyManager; protected: void InvokeUndoRedoChanged(); void InvokeModifiedChanged(); void UpdateCaretPoint(); void Move(TextPos caret, bool shift, bool frontSide); bool ProcessKey(vint code, bool shift, bool ctrl); void InstallDocumentViewer(GuiControl* _sender, compositions::GuiGraphicsComposition* _container, compositions::GuiGraphicsComposition* eventComposition, compositions::GuiGraphicsComposition* focusableComposition); void SetActiveHyperlink(Ptr<DocumentHyperlinkRun::Package> package); void ActivateActiveHyperlink(bool activate); void AddShortcutCommand(vint key, const Func<void()>& eventHandler); void EditTextInternal(TextPos begin, TextPos end, const Func<void(TextPos, TextPos, vint&, vint&)>& editor); void EditStyleInternal(TextPos begin, TextPos end, const Func<void(TextPos, TextPos)>& editor); void MergeBaselineAndDefaultFont(Ptr<DocumentModel> document); void OnFontChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); 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 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(); /// <summary>Active hyperlink changed event.</summary> compositions::GuiNotifyEvent ActiveHyperlinkChanged; /// <summary>Active hyperlink executed event.</summary> compositions::GuiNotifyEvent ActiveHyperlinkExecuted; /// <summary>Selection changed event.</summary> compositions::GuiNotifyEvent SelectionChanged; /// <summary>Undo redo status changed event.</summary> compositions::GuiNotifyEvent UndoRedoChanged; /// <summary>Modified status changed event.</summary> compositions::GuiNotifyEvent ModifiedChanged; /// <summary>Get the document.</summary> /// <returns>The document.</returns> Ptr<DocumentModel> GetDocument(); /// <summary>Set the document. When a document is set to this element, modifying the document without invoking <see cref="NotifyParagraphUpdated"/> will lead to undefined behavior.</summary> /// <param name="value">The document.</param> void SetDocument(Ptr<DocumentModel> value); //================ document items /// <summary>Add a document item. The name of the document item will display in the position of the &lt;object&gt; element with the same name in the document.</summary> /// <param name="value">The document item.</param> /// <returns>Returns true if this operation succeeded.</returns> bool AddDocumentItem(Ptr<GuiDocumentItem> value); /// <summary>Remove a document item.</summary> /// <param name="value">The document item.</param> /// <returns>Returns true if this operation succeeded.</returns> bool RemoveDocumentItem(Ptr<GuiDocumentItem> value); /// <summary>Get all document items.</summary> /// <returns>All document items.</returns> const DocumentItemMap& GetDocumentItems(); //================ caret operations /// <summary> /// Get the begin position of the selection area. /// </summary> /// <returns>The begin position of the selection area.</returns> TextPos GetCaretBegin(); /// <summary> /// Get the end position of the selection area. /// </summary> /// <returns>The end position of the selection area.</returns> TextPos GetCaretEnd(); /// <summary> /// Set the end position of the selection area. /// </summary> /// <param name="begin">The begin position of the selection area.</param> /// <param name="end">The end position of the selection area.</param> void SetCaret(TextPos begin, TextPos end); /// <summary>Calculate a caret using a specified point.</summary> /// <returns>The calculated caret.</returns> /// <param name="point">The specified point.</param> TextPos CalculateCaretFromPoint(Point point); /// <summary>Get the bounds of a caret.</summary> /// <returns>The bounds.</returns> /// <param name="caret">The caret.</param> /// <param name="frontSide">Set to true to get the bounds for the character before it.</param> Rect GetCaretBounds(TextPos caret, bool frontSide); //================ editing operations /// <summary>Notify that some paragraphs are updated.</summary> /// <param name="index">The start paragraph index.</param> /// <param name="oldCount">The number of paragraphs to be updated.</param> /// <param name="newCount">The number of updated paragraphs.</param> /// <param name="updatedText">Set to true to notify that the text is updated.</param> void NotifyParagraphUpdated(vint index, vint oldCount, vint newCount, bool updatedText); /// <summary>Edit run in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="model">The new run.</param> /// <param name="copy">Set to true to copy the model before editing. Otherwise, objects inside the model will be used directly</param> void EditRun(TextPos begin, TextPos end, Ptr<DocumentModel> model, bool copy); /// <summary>Edit text in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="frontSide">Set to true to use the text style in front of the specified range.</param> /// <param name="text">The new text.</param> void EditText(TextPos begin, TextPos end, bool frontSide, const collections::Array<WString>& text); /// <summary>Edit style in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="style">The new style.</param> void EditStyle(TextPos begin, TextPos end, Ptr<DocumentStyleProperties> style); /// <summary>Edit image in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="image">The new image.</param> void EditImage(TextPos begin, TextPos end, Ptr<GuiImageData> image); /// <summary>Set hyperlink in a specified range.</summary> /// <param name="paragraphIndex">The index of the paragraph to edit.</param> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="reference">The reference of the hyperlink.</param> /// <param name="normalStyleName">The normal style name of the hyperlink.</param> /// <param name="activeStyleName">The active style name of the hyperlink.</param> void EditHyperlink(vint paragraphIndex, vint begin, vint end, const WString& reference, const WString& normalStyleName=DocumentModel::NormalLinkStyleName, const WString& activeStyleName=DocumentModel::ActiveLinkStyleName); /// <summary>Remove hyperlink in a specified range.</summary> /// <param name="paragraphIndex">The index of the paragraph to edit.</param> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> void RemoveHyperlink(vint paragraphIndex, vint begin, vint end); /// <summary>Edit style name in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="styleName">The new style name.</param> void EditStyleName(TextPos begin, TextPos end, const WString& styleName); /// <summary>Remove style name in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> void RemoveStyleName(TextPos begin, TextPos end); /// <summary>Rename a style.</summary> /// <param name="oldStyleName">The name of the style.</param> /// <param name="newStyleName">The new name.</param> void RenameStyle(const WString& oldStyleName, const WString& newStyleName); /// <summary>Clear all styles in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> void ClearStyle(TextPos begin, TextPos end); /// <summary>Summarize the text style in a specified range.</summary> /// <returns>The text style summary.</returns> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> Ptr<DocumentStyleProperties> SummarizeStyle(TextPos begin, TextPos end); /// <summary>Summarize the style name in a specified range.</summary> /// <returns>The style name summary.</returns> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> Nullable<WString> SummarizeStyleName(TextPos begin, TextPos end); /// <summary>Set the alignment of paragraphs in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="alignments">The alignment for each paragraph.</param> void SetParagraphAlignments(TextPos begin, TextPos end, const collections::Array<Nullable<Alignment>>& alignments); /// <summary>Set the alignment of paragraphs in a specified range.</summary> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> /// <param name="alignment">The alignment for each paragraph.</param> void SetParagraphAlignment(TextPos begin, TextPos end, Nullable<Alignment> alignment); /// <summary>Summarize the text alignment in a specified range.</summary> /// <returns>The text alignment summary.</returns> /// <param name="begin">The begin position of the range.</param> /// <param name="end">The end position of the range.</param> Nullable<Alignment> SummarizeParagraphAlignment(TextPos begin, TextPos end); //================ editing control /// <summary>Get the href attribute of the active hyperlink.</summary> /// <returns>The href attribute of the active hyperlink.</returns> WString GetActiveHyperlinkReference(); /// <summary>Get the edit mode of this control.</summary> /// <returns>The edit mode.</returns> EditMode GetEditMode(); /// <summary>Set the edit mode of this control.</summary> /// <param name="value">The edit mode.</param> void SetEditMode(EditMode value); //================ selection operations /// <summary>Select all text.</summary> void SelectAll(); /// <summary>Get the selected text.</summary> /// <returns>The selected text.</returns> WString GetSelectionText(); /// <summary>Set the selected text.</summary> /// <param name="value">The selected text.</param> void SetSelectionText(const WString& value); /// <summary>Get the selected model.</summary> /// <returns>The selected model.</returns> Ptr<DocumentModel> GetSelectionModel(); /// <summary>Set the selected model.</summary> /// <param name="value">The selected model.</param> void SetSelectionModel(Ptr<DocumentModel> value); //================ clipboard operations /// <summary>Test can the selection be cut.</summary> /// <returns>Returns true if the selection can be cut.</returns> bool CanCut(); /// <summary>Test can the selection be copied.</summary> /// <returns>Returns true if the selection can be cut.</returns> bool CanCopy(); /// <summary>Test can the content in the clipboard be pasted.</summary> /// <returns>Returns true if the content in the clipboard can be pasted.</returns> bool CanPaste(); /// <summary>Cut the selection text.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Cut(); /// <summary>Copy the selection text.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Copy(); /// <summary>Paste the content from the clipboard and replace the selected text.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Paste(); //================ undo redo control /// <summary>Test can undo.</summary> /// <returns>Returns true if this action can be performed.</returns> bool CanUndo(); /// <summary>Test can redo.</summary> /// <returns>Returns true if this action can be performed.</returns> bool CanRedo(); /// <summary>Clear all undo and redo information.</summary> void ClearUndoRedo(); /// <summary>Test is the text box modified.</summary> /// <returns>Returns true if the text box is modified.</returns> bool GetModified(); /// <summary>Notify the text box that the current status is considered saved.</summary> void NotifyModificationSaved(); /// <summary>Perform the undo action.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Undo(); /// <summary>Perform the redo action.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Redo(); }; /*********************************************************************** GuiDocumentViewer ***********************************************************************/ /// <summary>Scrollable document viewer for displaying <see cref="DocumentModel"/>.</summary> class GuiDocumentViewer : public GuiScrollContainer, public GuiDocumentCommonInterface, public Description<GuiDocumentViewer> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(DocumentViewerTemplate, GuiScrollContainer) protected: Point GetDocumentViewPosition()override; void EnsureRectVisible(Rect bounds)override; public: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiDocumentViewer(theme::ThemeName themeName); ~GuiDocumentViewer(); const WString& GetText()override; void SetText(const WString& value)override; }; /*********************************************************************** GuiDocumentViewer ***********************************************************************/ /// <summary>Static document viewer for displaying <see cref="DocumentModel"/>.</summary> class GuiDocumentLabel : public GuiControl, public GuiDocumentCommonInterface, public Description<GuiDocumentLabel> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(DocumentLabelTemplate, GuiControl) public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> 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 controls { /*********************************************************************** Common Interface ***********************************************************************/ /// <summary>Common interface for text box controls.</summary> class GuiTextBoxCommonInterface abstract : public Description<GuiTextBoxCommonInterface> { typedef collections::Array<elements::text::ColorEntry> ColorArray; protected: class ICallback : public virtual IDescriptable, public Description<ICallback> { 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<DefaultCallback> { 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<GuiTextBoxColorizerBase> colorizer; Ptr<GuiTextBoxAutoCompleteBase> autoComplete; Ptr<GuiTextBoxUndoRedoProcessor> undoRedoProcessor; bool filledDefaultColors = false; ColorArray defaultColors; SpinLock elementModifyLock; collections::List<Ptr<ICommonTextEditCallback>> textEditCallbacks; Ptr<compositions::GuiShortcutKeyManager> 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(vint 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<ICommonTextEditCallback> value); bool DetachTextEditCallback(Ptr<ICommonTextEditCallback> value); void AddShortcutCommand(vint key, const Func<void()>& eventHandler); elements::GuiColorizedTextElement* GetTextElement(); void UnsafeSetText(const WString& value); public: GuiTextBoxCommonInterface(); ~GuiTextBoxCommonInterface(); /// <summary>Selection changed event.</summary> compositions::GuiNotifyEvent SelectionChanged; /// <summary>Undo redo status changed event.</summary> compositions::GuiNotifyEvent UndoRedoChanged; /// <summary>Modified status changed event.</summary> compositions::GuiNotifyEvent ModifiedChanged; //================ clipboard operations /// <summary>Test can the selection be cut.</summary> /// <returns>Returns true if the selection can be cut.</returns> bool CanCut(); /// <summary>Test can the selection be copied.</summary> /// <returns>Returns true if the selection can be cut.</returns> bool CanCopy(); /// <summary>Test can the content in the clipboard be pasted.</summary> /// <returns>Returns true if the content in the clipboard can be pasted.</returns> bool CanPaste(); /// <summary>Cut the selection text.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Cut(); /// <summary>Copy the selection text.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Copy(); /// <summary>Paste the content from the clipboard and replace the selected text.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Paste(); //================ editing control /// <summary>Get the readonly mode.</summary> /// <returns>Returns true if the text box is readonly.</returns> bool GetReadonly(); /// <summary>Set the readonly mode.</summary> /// <param name="value">Set to true to make the texg box readonly.</param> void SetReadonly(bool value); //================ text operations /// <summary>Select all text.</summary> void SelectAll(); /// <summary>Select (highlight) a part of text.</summary> /// <param name="begin">The begin position.</param> /// <param name="end">The end position. This is also the caret position.</param> void Select(TextPos begin, TextPos end); /// <summary>Get the selected text.</summary> /// <returns>The selected text.</returns> WString GetSelectionText(); /// <summary>Set the selected text.</summary> /// <param name="value">The selected text.</param> void SetSelectionText(const WString& value); /// <summary>Set the selected text and let to text box treat this changing as input by the keyboard.</summary> /// <param name="value">The selected text.</param> void SetSelectionTextAsKeyInput(const WString& value); /// <summary>Get the text from a specified row number.</summary> /// <returns>The text from a specified row number.</returns> /// <param name="row">The specified row number.</param> WString GetRowText(vint row); /// <summary>Get the number of rows.</summary> /// <returns>The number of rows.</returns> vint GetRowCount(); /// <summary>Get the text from a specified range.</summary> /// <returns>The text from a specified range.</returns> /// <param name="start">The specified start position.</param> /// <param name="end">The specified end position.</param> WString GetFragmentText(TextPos start, TextPos end); /// <summary>Get the begin text position of the selection.</summary> /// <returns>The begin text position of the selection.</returns> TextPos GetCaretBegin(); /// <summary>Get the end text position of the selection.</summary> /// <returns>The end text position of the selection.</returns> TextPos GetCaretEnd(); /// <summary>Get the left-top text position of the selection.</summary> /// <returns>The left-top text position of the selection.</returns> TextPos GetCaretSmall(); /// <summary>Get the right-bottom text position of the selection.</summary> /// <returns>The right-bottom text position of the selection.</returns> TextPos GetCaretLarge(); //================ position query /// <summary>Get the width of a row.</summary> /// <returns>The width of a row in pixel.</returns> /// <param name="row">The specified row number</param> vint GetRowWidth(vint row); /// <summary>Get the height of a row.</summary> /// <returns>The height of a row in pixel.</returns> vint GetRowHeight(); /// <summary>Get the maximum width of all rows.</summary> /// <returns>The maximum width of all rows.</returns> vint GetMaxWidth(); /// <summary>Get the total height of all rows.</summary> /// <returns>The total height of all rows.</returns> vint GetMaxHeight(); /// <summary>Get the nearest position of a character from a specified display position.</summary> /// <returns>Get the nearest position of a character.</returns> /// <param name="point">The specified display position.</param> TextPos GetTextPosFromPoint(Point point); /// <summary>Get the display position of a character from a specified text position.</summary> /// <returns>Get the display position of a character.</returns> /// <param name="pos">The specified text position.</param> Point GetPointFromTextPos(TextPos pos); /// <summary>Get the display bounds of a character from a specified text position.</summary> /// <returns>Get the display bounds of a character.</returns> /// <param name="pos">The specified text position.</param> Rect GetRectFromTextPos(TextPos pos); /// <summary>Get the nearest text position from a specified display position.</summary> /// <returns>Get the nearest text position.</returns> /// <param name="point">The specified display position.</param> TextPos GetNearestTextPos(Point point); //================ colorizing /// <summary>Get the current colorizer.</summary> /// <returns>The current colorizer.</returns> Ptr<GuiTextBoxColorizerBase> GetColorizer(); /// <summary>Set the current colorizer.</summary> /// <param name="value">The current colorizer.</param> void SetColorizer(Ptr<GuiTextBoxColorizerBase> value); //================ auto complete /// <summary>Get the current auto complete controller.</summary> /// <returns>The current auto complete controller.</returns> Ptr<GuiTextBoxAutoCompleteBase> GetAutoComplete(); /// <summary>Set the current auto complete controller.</summary> /// <param name="value">The current auto complete controller.</param> void SetAutoComplete(Ptr<GuiTextBoxAutoCompleteBase> value); //================ undo redo control /// <summary>Get the current edit version. When the control is modified, the edit version increased. Calling <see cref="NotifyModificationSaved"/> will not reset the edit version.</summary> /// <returns>The current edit version.</returns> vuint GetEditVersion(); /// <summary>Test can undo.</summary> /// <returns>Returns true if this action can be performed.</returns> bool CanUndo(); /// <summary>Test can redo.</summary> /// <returns>Returns true if this action can be performed.</returns> bool CanRedo(); /// <summary>Clear all undo and redo information.</summary> void ClearUndoRedo(); /// <summary>Test is the text box modified.</summary> /// <returns>Returns true if the text box is modified.</returns> bool GetModified(); /// <summary>Notify the text box that the current status is considered saved.</summary> void NotifyModificationSaved(); /// <summary>Perform the undo action.</summary> /// <returns>Returns true if this operation succeeded.</returns> bool Undo(); /// <summary>Perform the redo action.</summary> /// <returns>Returns true if this operation succeeded.</returns> 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 ***********************************************************************/ /// <summary>Multiline text box control.</summary> class GuiMultilineTextBox : public GuiScrollView, public GuiTextBoxCommonInterface, public Description<GuiMultilineTextBox> { 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<TextElementOperatorCallback> { 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<TextElementOperatorCallback> callback; Ptr<CommandExecutor> commandExecutor; elements::GuiColorizedTextElement* textElement = nullptr; compositions::GuiBoundsComposition* textComposition = nullptr; void CalculateViewAndSetScroll(); void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)override; Size QueryFullSize()override; void UpdateView(Rect viewBounds)override; void OnVisuallyEnabledChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBoundsMouseButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); public: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiMultilineTextBox(theme::ThemeName themeName); ~GuiMultilineTextBox(); const WString& GetText()override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; }; /*********************************************************************** SinglelineTextBox ***********************************************************************/ /// <summary>Single text box control.</summary> class GuiSinglelineTextBox : public GuiControl, public GuiTextBoxCommonInterface, public Description<GuiSinglelineTextBox> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(SinglelineTextBoxTemplate, GuiControl) public: static const vint TextMargin=2; protected: class TextElementOperatorCallback : public GuiTextBoxCommonInterface::DefaultCallback, public Description<TextElementOperatorCallback> { 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<TextElementOperatorCallback> callback; elements::GuiColorizedTextElement* textElement = nullptr; compositions::GuiTableComposition* textCompositionTable = nullptr; compositions::GuiCellComposition* textComposition = nullptr; void RearrangeTextElement(); void OnRenderTargetChanged(elements::IGuiGraphicsRenderTarget* renderTarget)override; void OnVisuallyEnabledChanged(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnBoundsMouseButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments); public: /// <summary>Create a control with a specified style provider.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiSinglelineTextBox(theme::ThemeName themeName); ~GuiSinglelineTextBox(); const WString& GetText()override; void SetText(const WString& value)override; void SetFont(const FontProperties& value)override; /// <summary> /// Get the password mode displaying character. /// </summary> /// <returns>The password mode displaying character. Returns L'\0' means the password mode is not activated.</returns> wchar_t GetPasswordChar(); /// <summary> /// Set the password mode displaying character. /// </summary> /// <param name="value">The password mode displaying character. Set to L'\0' to deactivate the password mode.</param> void SetPasswordChar(wchar_t value); }; } } } #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; /// <summary>The data grid context.</summary> class IDataGridContext : public virtual IDescriptable, public Description<IDataGridContext> { public: virtual GuiListControl::IItemProvider* GetItemProvider() = 0; virtual templates::GuiListViewTemplate* GetListViewControlTemplate() = 0; virtual void RequestSaveData() = 0; }; /// <summary>The visualizer factory.</summary> class IDataVisualizerFactory : public virtual IDescriptable, public Description<IDataVisualizerFactory> { public: /// <summary>Create a data visualizer.</summary> /// <returns>The created data visualizer.</returns> /// <param name="dataGridContext">Context information of the data grid.</param> virtual Ptr<IDataVisualizer> CreateVisualizer(IDataGridContext* dataGridContext) = 0; }; /// <summary>The visualizer for each cell in [T:vl.presentation.controls.GuiVirtualDataGrid].</summary> class IDataVisualizer : public virtual IDescriptable, public Description<IDataVisualizer> { public: /// <summary>Get the factory object that creates this visualizer.</summary> /// <returns>The factory object.</returns> virtual IDataVisualizerFactory* GetFactory() = 0; /// <summary>Get the template that renders the data. The data visualizer should maintain this template, and delete it when necessary.</summary> /// <returns>The template.</returns> virtual templates::GuiGridVisualizerTemplate* GetTemplate() = 0; /// <summary>Notify that the template has been deleted during the deconstruction of UI objects.</summary> virtual void NotifyDeletedTemplate() = 0; /// <summary>Called before visualizing a cell.</summary> /// <param name="itemProvider">The item provider.</param> /// <param name="row">The row number of the cell.</param> /// <param name="column">The column number of the cell.</param> virtual void BeforeVisualizeCell(GuiListControl::IItemProvider* itemProvider, vint row, vint column) = 0; /// <summary>Set the selected state.</summary> /// <param name="value">Set to true to make this data visualizer looks selected.</param> virtual void SetSelected(bool value) = 0; }; /// <summary>The editor factory.</summary> class IDataEditorFactory : public virtual IDescriptable, public Description<IDataEditorFactory> { public: /// <summary>Create a data editor.</summary> /// <returns>The created data editor.</returns> /// <param name="dataGridContext">Context information of the data grid.</param> virtual Ptr<IDataEditor> CreateEditor(IDataGridContext* dataGridContext) = 0; }; /// <summary>The editor for each cell in [T:vl.presentation.controls.GuiVirtualDataGrid].</summary> class IDataEditor : public virtual IDescriptable, public Description<IDataEditor> { public: /// <summary>Get the factory object that creates this editor.</summary> /// <returns>The factory object.</returns> virtual IDataEditorFactory* GetFactory() = 0; /// <summary>Get the template that edit the data. The data editor should maintain this template, and delete it when necessary.</summary> /// <returns>The template.</returns> virtual templates::GuiGridEditorTemplate* GetTemplate() = 0; /// <summary>Notify that the template has been deleted during the deconstruction of UI objects.</summary> virtual void NotifyDeletedTemplate() = 0; /// <summary>Called before editing a cell.</summary> /// <param name="itemProvider">The item provider.</param> /// <param name="row">The row number of the cell.</param> /// <param name="column">The column number of the cell.</param> virtual void BeforeEditCell(GuiListControl::IItemProvider* itemProvider, vint row, vint column) = 0; /// <summary>Test if the edit has saved the data.</summary> /// <returns>Returns true if the data is saved.</returns> virtual bool GetCellValueSaved() = 0; }; /// <summary>The required <see cref="GuiListControl::IItemProvider"/> view for [T:vl.presentation.controls.GuiVirtualDataGrid].</summary> class IDataGridView : public virtual IDescriptable, public Description<IDataGridView> { public: /// <summary>The identifier for this view.</summary> static const wchar_t* const Identifier; /// <summary>Test is a column sortable.</summary> /// <returns>Returns true if this column is sortable.</returns> /// <param name="column">The index of the column.</param> virtual bool IsColumnSortable(vint column) = 0; /// <summary>Set the column sorting state to update the data.</summary> /// <param name="column">The index of the column. Set to -1 means go back to the unsorted state.</param> /// <param name="ascending">Set to true if the data is sorted in ascending order.</param> virtual void SortByColumn(vint column, bool ascending) = 0; /// <summary>Get the sorted columm. If no column is under a sorted state, it returns -1.</summary> /// <returns>The column number.</returns> virtual vint GetSortedColumn() = 0; /// <summary>Test is the sort order ascending. </summary> /// <returns>Returns true if the sort order is ascending.</returns> virtual bool IsSortOrderAscending() = 0; /// <summary>Get the column span for the cell.</summary> /// <returns>The column span for the cell.</returns> /// <param name="row">The row number for the cell.</param> /// <param name="column">The column number for the cell.</param> virtual vint GetCellSpan(vint row, vint column) = 0; /// <summary>Get the data visualizer factory that creates data visualizers for visualizing the cell.</summary> /// <returns>The data visualizer factory. The data grid control to use the predefined data visualizer if this function returns null.</returns> /// <param name="row">The row number for the cell.</param> /// <param name="column">The column number for the cell.</param> virtual IDataVisualizerFactory* GetCellDataVisualizerFactory(vint row, vint column) = 0; /// <summary>Get the data editor factory that creates data editors for editing the cell.</summary> /// <returns>The data editor factory. Returns null to disable editing.</returns> /// <param name="row">The row number for the cell.</param> /// <param name="column">The column number for the cell.</param> virtual IDataEditorFactory* GetCellDataEditorFactory(vint row, vint column) = 0; /// <summary>Get the binding value of a cell.</summary> /// <returns>The binding value of cell.</returns> /// <param name="row">The row index of the cell.</param> /// <param name="column">The column index of the cell.</param> virtual description::Value GetBindingCellValue(vint row, vint column) = 0; /// <summary>Set the binding value of a cell.</summary> /// <param name="row">The row index of the cell.</param> /// <param name="column">The column index of the cell.</param> /// <param name="value">The value to set.</param> 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; /// <summary>Base class for all data visualizers.</summary> 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: /// <summary>Create the data visualizer.</summary> 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<DataVisualizerFactory> { using ItemTemplate = templates::GuiGridVisualizerTemplate; protected: TemplateProperty<ItemTemplate> templateFactory; Ptr<DataVisualizerFactory> decoratedFactory; ItemTemplate* CreateItemTemplate(controls::list::IDataGridContext* dataGridContext); public: DataVisualizerFactory(TemplateProperty<ItemTemplate> _templateFactory, Ptr<DataVisualizerFactory> _decoratedFactory = nullptr); ~DataVisualizerFactory(); Ptr<IDataVisualizer> CreateVisualizer(IDataGridContext* dataGridContext)override; }; /// <summary>Base class for all data editors.</summary> 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: /// <summary>Create the data editor.</summary> 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<DataEditorFactory> { using ItemTemplate = templates::GuiGridEditorTemplate; protected: TemplateProperty<ItemTemplate> templateFactory; public: DataEditorFactory(TemplateProperty<ItemTemplate> _templateFactory); ~DataEditorFactory(); Ptr<IDataEditor> CreateEditor(IDataGridContext* dataGridContext)override; }; /*********************************************************************** Visualizer Extensions ***********************************************************************/ class MainColumnVisualizerTemplate : public templates::GuiGridVisualizerTemplate { protected: elements::GuiImageFrameElement* image = nullptr; elements::GuiSolidLabelElement* text = nullptr; void OnTextChanged(GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnFontChanged(GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextColorChanged(GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnSmallImageChanged(GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: MainColumnVisualizerTemplate(); ~MainColumnVisualizerTemplate(); }; class SubColumnVisualizerTemplate : public templates::GuiGridVisualizerTemplate { protected: elements::GuiSolidLabelElement* text = nullptr; void OnTextChanged(GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnFontChanged(GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void OnTextColorChanged(GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void Initialize(bool fixTextColor); SubColumnVisualizerTemplate(bool fixTextColor); public: SubColumnVisualizerTemplate(); ~SubColumnVisualizerTemplate(); }; class HyperlinkVisualizerTemplate : public SubColumnVisualizerTemplate { protected: void label_MouseEnter(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); void label_MouseLeave(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments); public: HyperlinkVisualizerTemplate(); ~HyperlinkVisualizerTemplate(); }; class CellBorderVisualizerTemplate : public templates::GuiGridVisualizerTemplate { 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<elements::GuiSolidLabelElement*> 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<elements::GuiSolidLabelElement*> 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<elements::GuiSolidLabelElement*> 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 { namespace list { /*********************************************************************** DefaultDataGridItemTemplate ***********************************************************************/ class DefaultDataGridItemTemplate : public DefaultListViewItemTemplate , public ListViewColumnItemArranger::IColumnItemViewCallback { protected: compositions::GuiTableComposition* textTable = nullptr; collections::Array<Ptr<IDataVisualizer>> dataVisualizers; IDataEditor* currentEditor = nullptr; IDataVisualizerFactory* GetDataVisualizerFactory(vint row, vint column); IDataEditorFactory* GetDataEditorFactory(vint row, vint column); vint GetCellColumnIndex(compositions::GuiGraphicsComposition* composition); void OnCellButtonUp(compositions::GuiGraphicsComposition* sender, bool openEditor); bool IsInEditor(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); public: DefaultDataGridItemTemplate(); ~DefaultDataGridItemTemplate(); void UpdateSubItemSize(); bool IsEditorOpened(); void NotifyOpenEditor(vint column, IDataEditor* editor); void NotifyCloseEditor(); void NotifySelectCell(vint column); void NotifyCellEdited(); }; } /*********************************************************************** GuiVirtualDataGrid ***********************************************************************/ /// <summary>Data grid control in virtual mode.</summary> class GuiVirtualDataGrid : public GuiVirtualListView , private list::IDataGridContext , public Description<GuiVirtualDataGrid> { friend class list::DefaultDataGridItemTemplate; protected: list::IListViewItemView* listViewItemView = nullptr; list::ListViewColumnItemArranger::IColumnItemView* columnItemView = nullptr; list::IDataGridView* dataGridView = nullptr; Ptr<list::IDataVisualizerFactory> defaultMainColumnVisualizerFactory; Ptr<list::IDataVisualizerFactory> defaultSubColumnVisualizerFactory; GridPos selectedCell{ -1,-1 }; Ptr<list::IDataEditor> currentEditor; GridPos currentEditorPos{ -1,-1 }; bool currentEditorOpeningEditor = false; void OnItemModified(vint start, vint count, vint newCount)override; void OnStyleUninstalled(ItemStyle* style)override; void NotifyCloseEditor(); void NotifySelectCell(vint row, vint column); bool StartEdit(vint row, vint column); void StopEdit(bool forOpenNewEditor); void OnColumnClicked(compositions::GuiGraphicsComposition* sender, compositions::GuiItemEventArgs& arguments); public: templates::GuiListViewTemplate* GetListViewControlTemplate()override; void RequestSaveData()override; public: /// <summary>Create a data grid control in virtual mode.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_itemProvider">The item provider for this control.</param> GuiVirtualDataGrid(theme::ThemeName themeName, GuiListControl::IItemProvider* _itemProvider); ~GuiVirtualDataGrid(); /// <summary>Selected cell changed event.</summary> compositions::GuiNotifyEvent SelectedCellChanged; IItemProvider* GetItemProvider()override; /// <summary>Change the view to data grid's default view.</summary> void SetViewToDefault(); /// <summary>Get the row index and column index of the selected cell.</summary> /// <returns>The row index and column index of the selected cell.</returns> GridPos GetSelectedCell(); /// <summary>Set the row index and column index of the selected cell.</summary> /// <param name="value">The row index and column index of the selected cell.</param> void SetSelectedCell(const GridPos& value); }; } } } #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<IDataProcessorCallback> { public: virtual GuiListControl::IItemProvider* GetItemProvider() = 0; virtual void OnProcessorChanged() = 0; }; class IDataFilter : public virtual IDescriptable, public Description<IDataFilter> { public: virtual void SetCallback(IDataProcessorCallback* value) = 0; virtual bool Filter(const description::Value& row) = 0; }; class IDataSorter : public virtual IDescriptable, public Description<IDataSorter> { public: virtual void SetCallback(IDataProcessorCallback* value) = 0; virtual vint Compare(const description::Value& row1, const description::Value& row2) = 0; }; /*********************************************************************** Filter Extensions ***********************************************************************/ /// <summary>Base class for <see cref="IDataFilter"/>.</summary> class DataFilterBase : public Object, public virtual IDataFilter, public Description<DataFilterBase> { protected: IDataProcessorCallback* callback = nullptr; /// <summary>Called when the structure or properties for this filter is changed.</summary> void InvokeOnProcessorChanged(); public: DataFilterBase(); void SetCallback(IDataProcessorCallback* value)override; }; /// <summary>Base class for a <see cref="IDataFilter"/> that contains multiple sub filters.</summary> class DataMultipleFilter : public DataFilterBase, public Description<DataMultipleFilter> { protected: collections::List<Ptr<IDataFilter>> filters; public: DataMultipleFilter(); /// <summary>Add a sub filter.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The sub filter.</param> bool AddSubFilter(Ptr<IDataFilter> value); /// <summary>Remove a sub filter.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The sub filter.</param> bool RemoveSubFilter(Ptr<IDataFilter> value); void SetCallback(IDataProcessorCallback* value)override; }; /// <summary>A filter that keep a row if all sub filters agree.</summary> class DataAndFilter : public DataMultipleFilter, public Description<DataAndFilter> { public: /// <summary>Create the filter.</summary> DataAndFilter(); bool Filter(const description::Value& row)override; }; /// <summary>A filter that keep a row if one of all sub filters agrees.</summary> class DataOrFilter : public DataMultipleFilter, public Description<DataOrFilter> { public: /// <summary>Create the filter.</summary> DataOrFilter(); bool Filter(const description::Value& row)override; }; /// <summary>A filter that keep a row if the sub filter not agrees.</summary> class DataNotFilter : public DataFilterBase, public Description<DataNotFilter> { protected: Ptr<IDataFilter> filter; public: /// <summary>Create the filter.</summary> DataNotFilter(); /// <summary>Set a sub filter.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The sub filter.</param> bool SetSubFilter(Ptr<IDataFilter> value); void SetCallback(IDataProcessorCallback* value)override; bool Filter(const description::Value& row)override; }; /*********************************************************************** Sorter Extensions ***********************************************************************/ /// <summary>Base class for <see cref="IDataSorter"/>.</summary> class DataSorterBase : public Object, public virtual IDataSorter, public Description<DataSorterBase> { protected: IDataProcessorCallback* callback = nullptr; /// <summary>Called when the structure or properties for this filter is changed.</summary> void InvokeOnProcessorChanged(); public: DataSorterBase(); void SetCallback(IDataProcessorCallback* value)override; }; /// <summary>A multi-level <see cref="IDataSorter"/>.</summary> class DataMultipleSorter : public DataSorterBase, public Description<DataMultipleSorter> { protected: Ptr<IDataSorter> leftSorter; Ptr<IDataSorter> rightSorter; public: /// <summary>Create the sorter.</summary> DataMultipleSorter(); /// <summary>Set the first sub sorter.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The sub sorter.</param> bool SetLeftSorter(Ptr<IDataSorter> value); /// <summary>Set the second sub sorter.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The sub sorter.</param> bool SetRightSorter(Ptr<IDataSorter> value); void SetCallback(IDataProcessorCallback* value)override; vint Compare(const description::Value& row1, const description::Value& row2)override; }; /// <summary>A reverse order <see cref="IDataSorter"/>.</summary> class DataReverseSorter : public DataSorterBase, public Description<DataReverseSorter> { protected: Ptr<IDataSorter> sorter; public: /// <summary>Create the sorter.</summary> DataReverseSorter(); /// <summary>Set the sub sorter.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The sub sorter.</param> bool SetSubSorter(Ptr<IDataSorter> value); void SetCallback(IDataProcessorCallback* value)override; vint Compare(const description::Value& row1, const description::Value& row2)override; }; /*********************************************************************** DataColumn ***********************************************************************/ class DataColumns; class DataProvider; /// <summary>Datagrid Column.</summary> class DataColumn : public Object, public Description<DataColumn> { friend class DataColumns; friend class DataProvider; protected: DataProvider* dataProvider = nullptr; ItemProperty<WString> textProperty; WritableItemProperty<description::Value> valueProperty; WString text; vint size = 160; ColumnSortingState sortingState = ColumnSortingState::NotSorted; bool ownPopup = true; GuiMenu* popup = nullptr; Ptr<IDataFilter> associatedFilter; Ptr<IDataSorter> associatedSorter; Ptr<IDataVisualizerFactory> visualizerFactory; Ptr<IDataEditorFactory> editorFactory; void NotifyAllColumnsUpdate(bool affectItem); public: DataColumn(); ~DataColumn(); /// <summary>Value property name changed event.</summary> compositions::GuiNotifyEvent ValuePropertyChanged; /// <summary>Text property name changed event.</summary> compositions::GuiNotifyEvent TextPropertyChanged; /// <summary>Get the text for the column.</summary> /// <returns>The text for the column.</returns> WString GetText(); /// <summary>Set the text for the column.</summary> /// <param name="value">The text for the column.</param> void SetText(const WString& value); /// <summary>Get the size for the column.</summary> /// <returns>The size for the column.</returns> vint GetSize(); /// <summary>Set the size for the column.</summary> /// <param name="value">The size for the column.</param> void SetSize(vint value); /// <summary>Test if the column owns the popup. Owned popup will be deleted in the destructor.</summary> /// <returns>Returns true if the column owns the popup.</returns> bool GetOwnPopup(); /// <summary>Set if the column owns the popup.</summary> /// <param name="value">Set to true to let the column own the popup.</param> void SetOwnPopup(bool value); /// <summary>Get the popup for the column.</summary> /// <returns>The popup for the column.</returns> GuiMenu* GetPopup(); /// <summary>Set the popup for the column.</summary> /// <param name="value">The popup for the column.</param> void SetPopup(GuiMenu* value); /// <summary>Get the filter for the column.</summary> /// <returns>The filter for the column.</returns> Ptr<IDataFilter> GetFilter(); /// <summary>Set the filter for the column.</summary> /// <param name="value">The filter.</param> void SetFilter(Ptr<IDataFilter> value); /// <summary>Get the sorter for the column.</summary> /// <returns>The sorter for the column.</returns> Ptr<IDataSorter> GetSorter(); /// <summary>Set the sorter for the column.</summary> /// <param name="value">The sorter.</param> void SetSorter(Ptr<IDataSorter> value); /// <summary>Get the visualizer factory for the column.</summary> /// <returns>The the visualizer factory for the column.</returns> Ptr<IDataVisualizerFactory> GetVisualizerFactory(); /// <summary>Set the visualizer factory for the column.</summary> /// <param name="value">The visualizer factory.</param> void SetVisualizerFactory(Ptr<IDataVisualizerFactory> value); /// <summary>Get the editor factory for the column.</summary> /// <returns>The the editor factory for the column.</returns> Ptr<IDataEditorFactory> GetEditorFactory(); /// <summary>Set the editor factory for the column.</summary> /// <param name="value">The editor factory.</param> void SetEditorFactory(Ptr<IDataEditorFactory> value); /// <summary>Get the text value from an item.</summary> /// <returns>The text value.</returns> /// <param name="row">The row index of the item.</param> WString GetCellText(vint row); /// <summary>Get the cell value from an item.</summary> /// <returns>The cell value.</returns> /// <param name="row">The row index of the item.</param> description::Value GetCellValue(vint row); /// <summary>Set the cell value to an item.</summary> /// <param name="row">The row index of the item.</param> /// <param name="value">The value property name.</param> void SetCellValue(vint row, description::Value value); /// <summary>Get the text property name to get the cell text from an item.</summary> /// <returns>The text property name.</returns> ItemProperty<WString> GetTextProperty(); /// <summary>Set the text property name to get the cell text from an item.</summary> /// <param name="value">The text property name.</param> void SetTextProperty(const ItemProperty<WString>& value); /// <summary>Get the value property name to get the cell value from an item.</summary> /// <returns>The value property name.</returns> WritableItemProperty<description::Value> GetValueProperty(); /// <summary>Set the value property name to get the cell value from an item.</summary> /// <param name="value">The value property name.</param> void SetValueProperty(const WritableItemProperty<description::Value>& value); }; class DataColumns : public collections::ObservableListBase<Ptr<DataColumn>> { 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<DataColumn>& value)override; void AfterInsert(vint index, const Ptr<DataColumn>& value)override; void BeforeRemove(vint index, const Ptr<DataColumn>& 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<DataProvider> { friend class DataColumn; friend class DataColumns; friend class controls::GuiBindableDataGrid; protected: ListViewDataColumns dataColumns; DataColumns columns; ListViewColumnItemArranger::IColumnItemViewCallback* columnItemViewCallback = nullptr; Ptr<description::IValueReadonlyList> itemSource; Ptr<EventHandler> itemChangedEventHandler; Ptr<IDataFilter> additionalFilter; Ptr<IDataFilter> currentFilter; Ptr<IDataSorter> currentSorter; collections::List<vint> 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<Ptr<GuiImageData>> largeImageProperty; ItemProperty<Ptr<GuiImageData>> smallImageProperty; public: /// <summary>Create a data provider.</summary> DataProvider(); ~DataProvider(); ListViewDataColumns& GetDataColumns(); DataColumns& GetColumns(); Ptr<description::IValueEnumerable> GetItemSource(); void SetItemSource(Ptr<description::IValueEnumerable> _itemSource); Ptr<IDataFilter> GetAdditionalFilter(); void SetAdditionalFilter(Ptr<IDataFilter> 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<GuiImageData> GetSmallImage(vint itemIndex)override; Ptr<GuiImageData> 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 ***********************************************************************/ /// <summary>A bindable Data grid control.</summary> class GuiBindableDataGrid : public GuiVirtualDataGrid, public Description<GuiBindableDataGrid> { protected: list::DataProvider* dataProvider = nullptr; public: /// <summary>Create a bindable Data grid control.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiBindableDataGrid(theme::ThemeName themeName); ~GuiBindableDataGrid(); /// <summary>Get all data columns indices in columns.</summary> /// <returns>All data columns indices in columns.</returns> list::ListViewDataColumns& GetDataColumns(); /// <summary>Get all columns.</summary> /// <returns>All columns.</returns> list::DataColumns& GetColumns(); /// <summary>Get the item source.</summary> /// <returns>The item source.</returns> Ptr<description::IValueEnumerable> GetItemSource(); /// <summary>Set the item source.</summary> /// <param name="_itemSource">The item source. Null is acceptable if you want to clear all data.</param> void SetItemSource(Ptr<description::IValueEnumerable> _itemSource); /// <summary>Get the additional filter.</summary> /// <returns>The additional filter.</returns> Ptr<list::IDataFilter> GetAdditionalFilter(); /// <summary>Set the additional filter. This filter will be composed with filters of all column to be the final filter.</summary> /// <param name="value">The additional filter.</param> void SetAdditionalFilter(Ptr<list::IDataFilter> value); /// <summary>Large image property name changed event.</summary> compositions::GuiNotifyEvent LargeImagePropertyChanged; /// <summary>Small image property name changed event.</summary> compositions::GuiNotifyEvent SmallImagePropertyChanged; /// <summary>Get the large image property name to get the large image from an item.</summary> /// <returns>The large image property name.</returns> ItemProperty<Ptr<GuiImageData>> GetLargeImageProperty(); /// <summary>Set the large image property name to get the large image from an item.</summary> /// <param name="value">The large image property name.</param> void SetLargeImageProperty(const ItemProperty<Ptr<GuiImageData>>& value); /// <summary>Get the small image property name to get the small image from an item.</summary> /// <returns>The small image property name.</returns> ItemProperty<Ptr<GuiImageData>> GetSmallImageProperty(); /// <summary>Set the small image property name to get the small image from an item.</summary> /// <param name="value">The small image property name.</param> void SetSmallImageProperty(const ItemProperty<Ptr<GuiImageData>>& value); /// <summary>Get the selected cell.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> description::Value GetSelectedRowValue(); /// <summary>Get the selected cell.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> description::Value GetSelectedCellValue(); }; } } } #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<typename T> struct DefaultValueOf { static T Get() { return reflection::description::TypedValueSerializerProvider<T>::GetDefaultValue(); } }; template<typename T> struct DefaultValueOf<Ptr<T>> { static Ptr<T> Get() { return nullptr; } }; template<> struct DefaultValueOf<description::Value> { static description::Value Get() { return description::Value(); } }; template<typename T> T ReadProperty(const description::Value& thisObject, const ItemProperty<T>& propertyName) { if (!thisObject.IsNull() && propertyName) { return propertyName(thisObject); } else { return DefaultValueOf<T>::Get(); } } template<typename T> T ReadProperty(const description::Value& thisObject, const WritableItemProperty<T>& propertyName) { auto defaultValue = DefaultValueOf<T>::Get(); if (!thisObject.IsNull() && propertyName) { return propertyName(thisObject, defaultValue, false); } else { return defaultValue; } } template<typename T> void WriteProperty(const description::Value& thisObject, const WritableItemProperty<T>& propertyName, const T& value) { if (!thisObject.IsNull() && propertyName) { propertyName(thisObject, value, true); } } /*********************************************************************** GuiBindableTextList ***********************************************************************/ /// <summary>A bindable Text list control.</summary> class GuiBindableTextList : public GuiVirtualTextList, public Description<GuiBindableTextList> { protected: class ItemSource : public list::ItemProviderBase , protected list::ITextItemView { protected: Ptr<EventHandler> itemChangedEventHandler; Ptr<description::IValueReadonlyList> itemSource; public: ItemProperty<WString> textProperty; WritableItemProperty<bool> checkedProperty; public: ItemSource(); ~ItemSource(); Ptr<description::IValueEnumerable> GetItemSource(); void SetItemSource(Ptr<description::IValueEnumerable> _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: /// <summary>Create a bindable Text list control.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiBindableTextList(theme::ThemeName themeName); ~GuiBindableTextList(); /// <summary>Text property name changed event.</summary> compositions::GuiNotifyEvent TextPropertyChanged; /// <summary>Checked property name changed event.</summary> compositions::GuiNotifyEvent CheckedPropertyChanged; /// <summary>Get the item source.</summary> /// <returns>The item source.</returns> Ptr<description::IValueEnumerable> GetItemSource(); /// <summary>Set the item source.</summary> /// <param name="_itemSource">The item source. Null is acceptable if you want to clear all data.</param> void SetItemSource(Ptr<description::IValueEnumerable> _itemSource); /// <summary>Get the text property name to get the item text from an item.</summary> /// <returns>The text property name.</returns> ItemProperty<WString> GetTextProperty(); /// <summary>Set the text property name to get the item text from an item.</summary> /// <param name="value">The text property name.</param> void SetTextProperty(const ItemProperty<WString>& value); /// <summary>Get the checked property name to get the check state from an item.</summary> /// <returns>The checked property name.</returns> WritableItemProperty<bool> GetCheckedProperty(); /// <summary>Set the checked property name to get the check state from an item.</summary> /// <param name="value">The checked property name.</param> void SetCheckedProperty(const WritableItemProperty<bool>& value); /// <summary>Get the selected item.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> description::Value GetSelectedItem(); }; /*********************************************************************** GuiBindableListView ***********************************************************************/ /// <summary>A bindable List view control.</summary> class GuiBindableListView : public GuiVirtualListView, public Description<GuiBindableListView> { protected: class ItemSource : public list::ItemProviderBase , protected virtual list::IListViewItemProvider , public virtual list::IListViewItemView , public virtual list::ListViewColumnItemArranger::IColumnItemView { typedef collections::List<list::ListViewColumnItemArranger::IColumnItemViewCallback*> ColumnItemViewCallbackList; protected: list::ListViewDataColumns dataColumns; list::ListViewColumns columns; ColumnItemViewCallbackList columnItemViewCallbacks; Ptr<EventHandler> itemChangedEventHandler; Ptr<description::IValueReadonlyList> itemSource; public: ItemProperty<Ptr<GuiImageData>> largeImageProperty; ItemProperty<Ptr<GuiImageData>> smallImageProperty; public: ItemSource(); ~ItemSource(); Ptr<description::IValueEnumerable> GetItemSource(); void SetItemSource(Ptr<description::IValueEnumerable> _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<GuiImageData> GetSmallImage(vint itemIndex)override; Ptr<GuiImageData> 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: /// <summary>Create a bindable List view control.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiBindableListView(theme::ThemeName themeName); ~GuiBindableListView(); /// <summary>Get all data columns indices in columns.</summary> /// <returns>All data columns indices in columns.</returns> list::ListViewDataColumns& GetDataColumns(); /// <summary>Get all columns.</summary> /// <returns>All columns.</returns> list::ListViewColumns& GetColumns(); /// <summary>Get the item source.</summary> /// <returns>The item source.</returns> Ptr<description::IValueEnumerable> GetItemSource(); /// <summary>Set the item source.</summary> /// <param name="_itemSource">The item source. Null is acceptable if you want to clear all data.</param> void SetItemSource(Ptr<description::IValueEnumerable> _itemSource); /// <summary>Large image property name changed event.</summary> compositions::GuiNotifyEvent LargeImagePropertyChanged; /// <summary>Small image property name changed event.</summary> compositions::GuiNotifyEvent SmallImagePropertyChanged; /// <summary>Get the large image property name to get the large image from an item.</summary> /// <returns>The large image property name.</returns> ItemProperty<Ptr<GuiImageData>> GetLargeImageProperty(); /// <summary>Set the large image property name to get the large image from an item.</summary> /// <param name="value">The large image property name.</param> void SetLargeImageProperty(const ItemProperty<Ptr<GuiImageData>>& value); /// <summary>Get the small image property name to get the small image from an item.</summary> /// <returns>The small image property name.</returns> ItemProperty<Ptr<GuiImageData>> GetSmallImageProperty(); /// <summary>Set the small image property name to get the small image from an item.</summary> /// <param name="value">The small image property name.</param> void SetSmallImageProperty(const ItemProperty<Ptr<GuiImageData>>& value); /// <summary>Get the selected item.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> description::Value GetSelectedItem(); }; /*********************************************************************** GuiBindableTreeView ***********************************************************************/ /// <summary>A bindable Tree view control.</summary> class GuiBindableTreeView : public GuiVirtualTreeView, public Description<GuiBindableTreeView> { using IValueEnumerable = reflection::description::IValueEnumerable; protected: class ItemSource; class ItemSourceNode : public Object , public virtual tree::INodeProvider { friend class ItemSource; typedef collections::List<Ptr<ItemSourceNode>> NodeList; protected: description::Value itemSource; ItemSource* rootProvider; ItemSourceNode* parent; tree::INodeProviderCallback* callback; bool expanding = false; Ptr<EventHandler> itemChangedEventHandler; Ptr<description::IValueReadonlyList> childrenVirtualList; NodeList children; void PrepareChildren(); 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<tree::INodeProvider> GetParent()override; Ptr<tree::INodeProvider> GetChild(vint index)override; }; class ItemSource : public tree::NodeRootProviderBase , public virtual tree::ITreeViewItemView { friend class ItemSourceNode; public: ItemProperty<WString> textProperty; ItemProperty<Ptr<GuiImageData>> imageProperty; ItemProperty<Ptr<IValueEnumerable>> childrenProperty; Ptr<ItemSourceNode> rootNode; public: ItemSource(); ~ItemSource(); description::Value GetItemSource(); void SetItemSource(const description::Value& _itemSource); void UpdateBindingProperties(bool updateChildrenProperty); // ===================== tree::INodeRootProvider ===================== Ptr<tree::INodeProvider> GetRootNode()override; WString GetTextValue(tree::INodeProvider* node)override; description::Value GetBindingValue(tree::INodeProvider* node)override; IDescriptable* RequestView(const WString& identifier)override; // ===================== tree::ITreeViewItemView ===================== Ptr<GuiImageData> GetNodeImage(tree::INodeProvider* node)override; }; protected: ItemSource* itemSource; public: /// <summary>Create a bindable Tree view control.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiBindableTreeView(theme::ThemeName themeName); ~GuiBindableTreeView(); /// <summary>Text property name changed event.</summary> compositions::GuiNotifyEvent TextPropertyChanged; /// <summary>Image property name changed event.</summary> compositions::GuiNotifyEvent ImagePropertyChanged; /// <summary>Children property name changed event.</summary> compositions::GuiNotifyEvent ChildrenPropertyChanged; /// <summary>Get the item source.</summary> /// <returns>The item source.</returns> description::Value GetItemSource(); /// <summary>Set the item source.</summary> /// <param name="_itemSource">The item source. Null is acceptable if you want to clear all data.</param> void SetItemSource(description::Value _itemSource); /// <summary>Get the text property name to get the item text from an item.</summary> /// <returns>The text property name.</returns> ItemProperty<WString> GetTextProperty(); /// <summary>Set the text property name to get the item text from an item.</summary> /// <param name="value">The text property name.</param> void SetTextProperty(const ItemProperty<WString>& value); /// <summary>Get the image property name to get the image from an item.</summary> /// <returns>The image property name.</returns> ItemProperty<Ptr<GuiImageData>> GetImageProperty(); /// <summary>Set the image property name to get the image from an item.</summary> /// <param name="value">The image property name.</param> void SetImageProperty(const ItemProperty<Ptr<GuiImageData>>& value); /// <summary>Get the children property name to get the children from an item.</summary> /// <returns>The children property name.</returns> ItemProperty<Ptr<IValueEnumerable>> GetChildrenProperty(); /// <summary>Set the children property name to get the children from an item.</summary> /// <param name="value">The children property name.</param> void SetChildrenProperty(const ItemProperty<Ptr<IValueEnumerable>>& value); /// <summary>Get the selected item.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> description::Value GetSelectedItem(); }; } } } #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 controls { /// <summary>A command for toolstrip controls.</summary> class GuiToolstripCommand : public GuiComponent, public Description<GuiToolstripCommand> { public: class ShortcutBuilder : public Object { public: WString text; bool ctrl; bool shift; bool alt; vint key; }; protected: Ptr<GuiImageData> image; Ptr<GuiImageData> largeImage; WString text; compositions::IGuiShortcutKeyItem* shortcutKeyItem = nullptr; bool enabled = true; bool selected = false; Ptr<compositions::IGuiGraphicsEventHandler> shortcutKeyItemExecutedHandler; Ptr<ShortcutBuilder> shortcutBuilder; GuiInstanceRootObject* attachedRootObject = nullptr; Ptr<compositions::IGuiGraphicsEventHandler> 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<ShortcutBuilder> builder); void BuildShortcut(const WString& builderText); void UpdateShortcutOwner(); public: /// <summary>Create the command.</summary> GuiToolstripCommand(); ~GuiToolstripCommand(); void Attach(GuiInstanceRootObject* rootObject)override; void Detach(GuiInstanceRootObject* rootObject)override; /// <summary>Executed event.</summary> compositions::GuiNotifyEvent Executed; /// <summary>Description changed event, raised when any description property is modified.</summary> compositions::GuiNotifyEvent DescriptionChanged; /// <summary>Get the large image for this command.</summary> /// <returns>The large image for this command.</returns> Ptr<GuiImageData> GetLargeImage(); /// <summary>Set the large image for this command.</summary> /// <param name="value">The large image for this command.</param> void SetLargeImage(Ptr<GuiImageData> value); /// <summary>Get the image for this command.</summary> /// <returns>The image for this command.</returns> Ptr<GuiImageData> GetImage(); /// <summary>Set the image for this command.</summary> /// <param name="value">The image for this command.</param> void SetImage(Ptr<GuiImageData> value); /// <summary>Get the text for this command.</summary> /// <returns>The text for this command.</returns> const WString& GetText(); /// <summary>Set the text for this command.</summary> /// <param name="value">The text for this command.</param> void SetText(const WString& value); /// <summary>Get the shortcut key item for this command.</summary> /// <returns>The shortcut key item for this command.</returns> compositions::IGuiShortcutKeyItem* GetShortcut(); /// <summary>Set the shortcut key item for this command.</summary> /// <param name="value">The shortcut key item for this command.</param> void SetShortcut(compositions::IGuiShortcutKeyItem* value); /// <summary>Get the shortcut builder for this command.</summary> /// <returns>The shortcut builder for this command.</returns> WString GetShortcutBuilder(); /// <summary>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.</summary> /// <param name="value">The shortcut builder for this command.</param> void SetShortcutBuilder(const WString& value); /// <summary>Get the enablility for this command.</summary> /// <returns>The enablility for this command.</returns> bool GetEnabled(); /// <summary>Set the enablility for this command.</summary> /// <param name="value">The enablility for this command.</param> void SetEnabled(bool value); /// <summary>Get the selection for this command.</summary> /// <returns>The selection for this command.</returns> bool GetSelected(); /// <summary>Set the selection for this command.</summary> /// <param name="value">The selection for this command.</param> 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 ***********************************************************************/ /// <summary>IToolstripUpdateLayout is a required service for all menu item container.</summary> class IToolstripUpdateLayout : public IDescriptable { public: virtual void UpdateLayout() = 0; }; /// <summary>IToolstripUpdateLayout is a required service for a menu item which want to force the container to redo layout.</summary> class IToolstripUpdateLayoutInvoker : public IDescriptable { public: /// <summary>The identifier for this service.</summary> static const wchar_t* const Identifier; virtual void SetCallback(IToolstripUpdateLayout* callback) = 0; }; /// <summary>Toolstrip item collection.</summary> class GuiToolstripCollectionBase : public collections::ObservableListBase<GuiControl*> { 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(); }; /// <summary>Toolstrip item collection.</summary> class GuiToolstripCollection : public GuiToolstripCollectionBase { using EventHandlerList = collections::List<Ptr<compositions::IGuiGraphicsEventHandler>>; 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 ***********************************************************************/ /// <summary>Toolstrip menu.</summary> class GuiToolstripMenu : public GuiMenu, protected IToolstripUpdateLayout, Description<GuiToolstripMenu> { protected: compositions::GuiSharedSizeRootComposition* sharedSizeRootComposition; compositions::GuiStackComposition* stackComposition; Ptr<GuiToolstripCollection> toolstripItems; void UpdateLayout()override; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_owner">The owner menu item of the parent menu.</param> GuiToolstripMenu(theme::ThemeName themeName, GuiControl* _owner); ~GuiToolstripMenu(); /// <summary>Get all managed child controls ordered by their positions.</summary> /// <returns>All managed child controls.</returns> collections::ObservableListBase<GuiControl*>& GetToolstripItems(); }; /// <summary>Toolstrip menu bar.</summary> class GuiToolstripMenuBar : public GuiMenuBar, public Description<GuiToolstripMenuBar> { protected: compositions::GuiStackComposition* stackComposition; Ptr<GuiToolstripCollection> toolstripItems; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiToolstripMenuBar(theme::ThemeName themeName); ~GuiToolstripMenuBar(); /// <summary>Get all managed child controls ordered by their positions.</summary> /// <returns>All managed child controls.</returns> collections::ObservableListBase<GuiControl*>& GetToolstripItems(); }; /// <summary>Toolstrip tool bar.</summary> class GuiToolstripToolBar : public GuiControl, public Description<GuiToolstripToolBar> { protected: compositions::GuiStackComposition* stackComposition; Ptr<GuiToolstripCollection> toolstripItems; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiToolstripToolBar(theme::ThemeName themeName); ~GuiToolstripToolBar(); /// <summary>Get all managed child controls ordered by their positions.</summary> /// <returns>All managed child controls.</returns> collections::ObservableListBase<GuiControl*>& GetToolstripItems(); }; /*********************************************************************** Toolstrip Component ***********************************************************************/ /// <summary>Toolstrip button that can connect with a <see cref="GuiToolstripCommand"/>.</summary> class GuiToolstripButton : public GuiMenuButton, protected IToolstripUpdateLayoutInvoker, public Description<GuiToolstripButton> { protected: GuiToolstripCommand* command; IToolstripUpdateLayout* callback = nullptr; Ptr<compositions::IGuiGraphicsEventHandler> descriptionChangedHandler; void SetCallback(IToolstripUpdateLayout* _callback)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: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiToolstripButton(theme::ThemeName themeName); ~GuiToolstripButton(); /// <summary>Get the attached <see cref="GuiToolstripCommand"/>.</summary> /// <returns>The attached toolstrip command.</returns> GuiToolstripCommand* GetCommand(); /// <summary>Detach from the previous <see cref="GuiToolstripCommand"/> and attach to a new one. If the command is null, this function only do detaching.</summary> /// <param name="value">The new toolstrip command.</param> void SetCommand(GuiToolstripCommand* value); /// <summary>Get the toolstrip sub menu. If the sub menu is not created, it returns null.</summary> /// <returns>The toolstrip sub menu.</returns> GuiToolstripMenu* GetToolstripSubMenu(); /// <summary>Get the toolstrip sub menu. If the sub menu is not created, it returns null.</summary> /// <returns>The toolstrip sub menu.</returns> GuiToolstripMenu* EnsureToolstripSubMenu(); /// <summary>Create the toolstrip sub menu if necessary. The created toolstrip sub menu is owned by this menu button.</summary> /// <param name="subMenuTemplate">The style controller for the toolstrip sub menu. Set to null to use the default control template.</param> void CreateToolstripSubMenu(TemplateProperty<templates::GuiMenuTemplate> 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; }; /// <summary>A toolstrip item, which is also a toolstrip item container, automatically maintaining splitters between items.</summary> class GuiToolstripGroupContainer : public GuiToolstripNestedContainer, public Description<GuiToolstripGroupContainer> { 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> groupCollection; void OnParentLineChanged()override; public: GuiToolstripGroupContainer(theme::ThemeName themeName); ~GuiToolstripGroupContainer(); ControlTemplatePropertyType GetSplitterTemplate(); void SetSplitterTemplate(const ControlTemplatePropertyType& value); /// <summary>Get all managed child controls ordered by their positions.</summary> /// <returns>All managed child controls.</returns> collections::ObservableListBase<GuiControl*>& GetToolstripItems(); }; /// <summary>A toolstrip item, which is also a toolstrip item container.</summary> class GuiToolstripGroup : public GuiToolstripNestedContainer, public Description<GuiToolstripGroup> { protected: compositions::GuiStackComposition* stackComposition; Ptr<GuiToolstripCollection> toolstripItems; void OnParentLineChanged()override; public: GuiToolstripGroup(theme::ThemeName themeName); ~GuiToolstripGroup(); /// <summary>Get all managed child controls ordered by their positions.</summary> /// <returns>All managed child controls.</returns> collections::ObservableListBase<GuiControl*>& GetToolstripItems(); }; } } namespace collections { namespace randomaccess_internal { template<> struct RandomAccessable<presentation::controls::GuiToolstripCollection> { 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; /// <summary>Ribbon tab control, for displaying ribbon tab pages.</summary> class GuiRibbonTab : public GuiTab, public Description<GuiRibbonTab> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonTabTemplate, GuiTab) protected: compositions::GuiBoundsComposition* beforeHeaders = nullptr; compositions::GuiBoundsComposition* afterHeaders = nullptr; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiRibbonTab(theme::ThemeName themeName); ~GuiRibbonTab(); /// <summary>Get the composition representing the space before tabs.</summary> /// <returns>The composition representing the space before tabs.</returns> compositions::GuiGraphicsComposition* GetBeforeHeaders(); /// <summary>Get the composition representing the space after tabs.</summary> /// <returns>The composition representing the space after tabs.</returns> compositions::GuiGraphicsComposition* GetAfterHeaders(); }; class GuiRibbonGroupCollection : public collections::ObservableListBase<GuiRibbonGroup*> { 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(); }; /// <summary>Ribbon tab page control, adding to the Pages property of a <see cref="GuiRibbonTab"/>.</summary> class GuiRibbonTabPage : public GuiTabPage, public Description<GuiRibbonTabPage> { friend class GuiRibbonGroupCollection; protected: bool highlighted = false; GuiRibbonGroupCollection groups; compositions::GuiResponsiveStackComposition* responsiveStack = nullptr; compositions::GuiResponsiveContainerComposition* responsiveContainer = nullptr; compositions::GuiStackComposition* stack = nullptr; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiRibbonTabPage(theme::ThemeName themeName); ~GuiRibbonTabPage(); /// <summary>Highlighted changed event.</summary> compositions::GuiNotifyEvent HighlightedChanged; /// <summary>Test if this is a highlighted tab page.</summary> /// <returns>Returns true if this is a highlighted tab page.</returns> bool GetHighlighted(); /// <summary>Set if this is a highlighted tab page.</summary> /// <param name="value">Set to true to highlight the tab page.</param> void SetHighlighted(bool value); /// <summary>Get the collection of ribbon groups.</summary> /// <returns>The collection of ribbon groups.</returns> collections::ObservableListBase<GuiRibbonGroup*>& GetGroups(); }; class GuiRibbonGroupItemCollection : public collections::ObservableListBase<GuiControl*> { 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(); }; /// <summary>Ribbon group control, adding to the Groups property of a <see cref="GuiRibbonTabPage"/>.</summary> class GuiRibbonGroup : public GuiControl, public Description<GuiRibbonGroup> { 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<GuiImageData> largeImage; GuiRibbonGroupItemCollection items; compositions::GuiResponsiveStackComposition* responsiveStack = nullptr; compositions::GuiStackComposition* stack = nullptr; Ptr<CommandExecutor> commandExecutor; compositions::GuiResponsiveViewComposition* responsiveView = nullptr; compositions::GuiResponsiveFixedComposition* responsiveFixedButton = nullptr; GuiToolstripButton* dropdownButton = nullptr; GuiMenu* dropdownMenu = nullptr; 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: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiRibbonGroup(theme::ThemeName themeName); ~GuiRibbonGroup(); /// <summary>Expandable changed event.</summary> compositions::GuiNotifyEvent ExpandableChanged; /// <summary>Expand button clicked event.</summary> compositions::GuiNotifyEvent ExpandButtonClicked; /// <summary>Large image changed event.</summary> compositions::GuiNotifyEvent LargeImageChanged; /// <summary>Test if this group is expandable. An expandable group will display an extra small button, which raises <see cref="ExpandButtonClicked"/>.</summary> /// <returns>Returns true if this group is expandable.</returns> bool GetExpandable(); /// <summary>Set if this group is expandable.</summary> /// <param name="value">Set to true to make this group is expandable.</param> void SetExpandable(bool value); /// <summary>Get the large image for the collapsed ribbon group.</summary> /// <returns>The large image for the collapsed ribbon group.</returns> Ptr<GuiImageData> GetLargeImage(); /// <summary>Set the large image for the collapsed ribbon group.</summary> /// <param name="value">The large image for the collapsed ribbon group.</param> void SetLargeImage(Ptr<GuiImageData> value); /// <summary>Get the collection of controls in this group.</summary> /// <returns>The collection of controls.</returns> collections::ObservableListBase<GuiControl*>& GetItems(); }; /*********************************************************************** Ribbon Buttons ***********************************************************************/ /// <summary>Auto resizable ribbon icon label.</summary> class GuiRibbonIconLabel : public GuiControl, public Description<GuiRibbonIconLabel> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonIconLabelTemplate, GuiControl) protected: Ptr<GuiImageData> image; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiRibbonIconLabel(theme::ThemeName themeName); ~GuiRibbonIconLabel(); /// <summary>Image changed event.</summary> compositions::GuiNotifyEvent ImageChanged; /// <summary>Get the image for the menu button.</summary> /// <returns>The image for the menu button.</returns> Ptr<GuiImageData> GetImage(); /// <summary>Set the image for the menu button.</summary> /// <param name="value">The image for the menu button.</param> void SetImage(Ptr<GuiImageData> value); }; /// <summary>Represents the size of a ribbon button in a <see cref="GuiRibbonButtons"/> control.</summary> enum class RibbonButtonSize { /// <summary>Large icon with text.</summary> Large = 0, /// <summary>Small icon with text.</summary> Small = 1, /// <summary>Small icon only.</summary> Icon = 2, }; class GuiRibbonButtons; class GuiRibbonButtonsItemCollection : public collections::ObservableListBase<GuiControl*> { 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(); }; /// <summary>Auto resizable ribbon buttons.</summary> class GuiRibbonButtons : public GuiControl, public Description<GuiRibbonButtons> { 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: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="_maxSize">Max allowed size.</param> /// <param name="_minSize">Min allowed size.</param> GuiRibbonButtons(theme::ThemeName themeName, RibbonButtonSize _maxSize, RibbonButtonSize _minSize); ~GuiRibbonButtons(); /// <summary>Get the collection of buttons. <see cref="GuiToolstripButton"/> is expected.</summary> /// <returns>The collection of buttons.</returns> collections::ObservableListBase<GuiControl*>& GetButtons(); }; /*********************************************************************** Ribbon Toolstrips ***********************************************************************/ class GuiRibbonToolstrips; class GuiRibbonToolstripsGroupCollection : public collections::ObservableListBase<GuiToolstripGroup*> { 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(); }; /// <summary>Auto resizable ribbon toolstrips.</summary> class GuiRibbonToolstrips : public GuiControl, public Description<GuiRibbonToolstrips> { 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: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiRibbonToolstrips(theme::ThemeName themeName); ~GuiRibbonToolstrips(); /// <summary>Get the collection of toolstrip groups. <see cref="GuiRibbonToolstrips"/> will decide the order of these toolstrip groups.</summary> /// <returns>The collection of toolstrip groups.</returns> collections::ObservableListBase<GuiToolstripGroup*>& GetGroups(); }; /*********************************************************************** Ribbon Gallery ***********************************************************************/ /// <summary>Ribbon gallery, with scroll up, scroll down, dropdown buttons.</summary> class GuiRibbonGallery : public GuiControl, public Description<GuiRibbonGallery> { using ItemStyle = templates::GuiListItemTemplate; using ItemStyleProperty = TemplateProperty<templates::GuiListItemTemplate>; 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> commandExecutor; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiRibbonGallery(theme::ThemeName themeName); ~GuiRibbonGallery(); /// <summary>Scroll up enabled changed event.</summary> compositions::GuiNotifyEvent ScrollUpEnabledChanged; /// <summary>Scroll down enabled changed event.</summary> compositions::GuiNotifyEvent ScrollDownEnabledChanged; /// <summary>Scroll up button clicked event.</summary> compositions::GuiNotifyEvent RequestedScrollUp; /// <summary>Scroll down button clicked event.</summary> compositions::GuiNotifyEvent RequestedScrollDown; /// <summary>Dropdown button clicked event.</summary> compositions::GuiNotifyEvent RequestedDropdown; /// <summary>Test if the scroll up button is enabled.</summary> /// <returns>Returns true if the scroll up button is enabled.</returns> bool GetScrollUpEnabled(); /// <summary>Set if the scroll up button is enabled.</summary> /// <param name="value">Set to true to enable the scroll up button.</param> void SetScrollUpEnabled(bool value); /// <summary>Test if the scroll down button is enabled.</summary> /// <returns>Returns true if the scroll down button is enabled.</returns> bool GetScrollDownEnabled(); /// <summary>Set if the scroll down button is enabled.</summary> /// <param name="value">Set to true to enable the scroll down button.</param> void SetScrollDownEnabled(bool value); }; /// <summary>Resizable ribbon toolstrip menu with a space above of all menu items to display extra content.</summary> class GuiRibbonToolstripMenu : public GuiToolstripMenu, public Description<GuiRibbonToolstripMenu> { GUI_SPECIFY_CONTROL_TEMPLATE_TYPE(RibbonToolstripMenuTemplate, GuiToolstripMenu) protected: compositions::GuiBoundsComposition* contentComposition; public: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> /// <param name="owner">The owner menu item of the parent menu.</param> GuiRibbonToolstripMenu(theme::ThemeName themeName, GuiControl* owner); ~GuiRibbonToolstripMenu(); /// <summary>Get the composition representing the space above of menu items.</summary> /// <returns>The composition representing the space above of menu items.</returns> 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 ***********************************************************************/ /// <summary>Represents the position of an item in the gallery list.</summary> struct GalleryPos { /// <summary>Group index.</summary> vint group; /// <summary>Item index.</summary> vint item; GalleryPos() :group(-1), item(-1) { } GalleryPos(vint _group, vint _item) :group(_group), item(_item) { } vint Compare(GalleryPos value)const { vint result = group - value.group; if (result != 0) return result; return item - value.item; } bool operator==(const GalleryPos& value)const { return Compare(value) == 0; } bool operator!=(const GalleryPos& value)const { return Compare(value) != 0; } bool operator<(const GalleryPos& value)const { return Compare(value)<0; } bool operator<=(const GalleryPos& value)const { return Compare(value) <= 0; } bool operator>(const GalleryPos& value)const { return Compare(value)>0; } bool operator>=(const GalleryPos& value)const { return Compare(value) >= 0; } }; namespace list { class GroupedDataSource; /// <summary>A gallery group.</summary> class GalleryGroup : public Description<GalleryGroup> { friend class GroupedDataSource; using IValueList = reflection::description::IValueList; protected: Ptr<EventHandler> eventHandler; WString name; Ptr<IValueList> itemValues; public: GalleryGroup(); ~GalleryGroup(); /// <summary>Get the title of this group.</summary> /// <returns>The title of this group.</returns> WString GetName(); /// <summary>Get the all items of this group, could be null.</summary> /// <returns>All items of this group.</returns> Ptr<IValueList> GetItemValues(); }; class GroupedDataSource : public Description<GroupedDataSource> { using IValueEnumerable = reflection::description::IValueEnumerable; using IValueList = reflection::description::IValueList; using IValueObservableList = reflection::description::IValueObservableList; using GalleryItemList = collections::ObservableList<reflection::description::Value>; using GalleryGroupList = collections::ObservableList<Ptr<GalleryGroup>>; protected: compositions::GuiGraphicsComposition* associatedComposition; Ptr<IValueEnumerable> itemSource; ItemProperty<WString> titleProperty; ItemProperty<Ptr<IValueEnumerable>> childrenProperty; GalleryItemList joinedItemSource; GalleryGroupList groupedItemSource; collections::List<vint> cachedGroupItemCounts; Ptr<EventHandler> groupChangedHandler; bool ignoreGroupChanged = false; void RebuildItemSource(); Ptr<IValueList> GetChildren(Ptr<IValueEnumerable> children); void AttachGroupChanged(Ptr<GalleryGroup> 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(); /// <summary>Group enabled event.</summary> compositions::GuiNotifyEvent GroupEnabledChanged; /// <summary>Group title property changed event.</summary> compositions::GuiNotifyEvent GroupTitlePropertyChanged; /// <summary>Group children property changed event.</summary> compositions::GuiNotifyEvent GroupChildrenPropertyChanged; /// <summary>Get the item source.</summary> /// <returns>The item source.</returns> Ptr<IValueEnumerable> GetItemSource(); /// <summary>Set the item source.</summary> /// <param name="value">The item source. Null is acceptable if you want to clear all data.</param> void SetItemSource(Ptr<IValueEnumerable> value); /// <summary>Test if grouping is enabled. Enabled means there is really both GroupTitleProperty and GroupChildrenProperty is not empty.</summary> /// <returns>Returns true if grouping is enabled.</returns> bool GetGroupEnabled(); /// <summary>Get the group title property.</summary> /// <returns>The group title property.</returns> ItemProperty<WString> GetGroupTitleProperty(); /// <summary>Get the group title property.</summary> /// <param name="value">The group title property.</param> void SetGroupTitleProperty(const ItemProperty<WString>& value); /// <summary>Get the group children property.</summary> /// <returns>The group children property.</returns> ItemProperty<Ptr<IValueEnumerable>> GetGroupChildrenProperty(); /// <summary>Get the group children property.</summary> /// <param name="value">The children title property.</param> void SetGroupChildrenProperty(const ItemProperty<Ptr<IValueEnumerable>>& value); /// <summary>Get all groups.</summary> /// <returns>All groups.</returns> const GalleryGroupList& GetGroups(); }; } namespace ribbon_impl { class GalleryItemArranger; class GalleryResponsiveLayout; } /// <summary>Auto resizable ribbon gallyer list.</summary> class GuiBindableRibbonGalleryList : public GuiRibbonGallery, public list::GroupedDataSource, private IGuiMenuDropdownProvider, public Description<GuiBindableRibbonGalleryList> { friend class ribbon_impl::GalleryItemArranger; using IValueEnumerable = reflection::description::IValueEnumerable; using IValueObservableList = reflection::description::IValueObservableList; using ItemStyleProperty = TemplateProperty<templates::GuiListItemTemplate>; 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: /// <summary>Create a control with a specified default theme.</summary> /// <param name="themeName">The theme name for retriving a default control template.</param> GuiBindableRibbonGalleryList(theme::ThemeName themeName); ~GuiBindableRibbonGalleryList(); /// <summary>Item template changed event.</summary> compositions::GuiNotifyEvent ItemTemplateChanged; /// <summary>Selection changed event.</summary> compositions::GuiNotifyEvent SelectionChanged; /// <summary>Preview started event.</summary> compositions::GuiItemNotifyEvent PreviewStarted; /// <summary>Preview stopped event.</summary> compositions::GuiItemNotifyEvent PreviewStopped; /// <summary>Item applied event.</summary> compositions::GuiItemNotifyEvent ItemApplied; /// <summary>Get the item style provider.</summary> /// <returns>The item style provider.</returns> ItemStyleProperty GetItemTemplate(); /// <summary>Set the item style provider</summary> /// <param name="value">The new item style provider</param> void SetItemTemplate(ItemStyleProperty value); /// <summary>Convert an item index to a gallery item position.</summary> /// <returns>The gallery item position.</returns> /// <param name="index">The item index.</param> GalleryPos IndexToGalleryPos(vint index); /// <summary>Convert a gallery item position to an item index.</summary> /// <returns>The item index.</returns> /// <param name="pos">The gallery item position.</param> vint GalleryPosToIndex(GalleryPos pos); /// <summary>Get the minimum number of items should be displayed.</summary> /// <returns>The minimum number of items should be displayed.</returns> vint GetMinCount(); /// <summary>Set the minimum number of items should be displayed.</summary> /// <param name="value">The minimum number of items should be displayed.</param> void SetMinCount(vint value); /// <summary>Get the maximum number of items should be displayed.</summary> /// <returns>The maximum number of items should be displayed.</returns> vint GetMaxCount(); /// <summary>Set the maximum number of items should be displayed.</summary> /// <param name="value">The maximum number of items should be displayed.</param> void SetMaxCount(vint value); /// <summary>Get the selected item index.</summary> /// <returns>The index of the selected item. If there are multiple selected items, or there is no selected item, -1 will be returned.</returns> vint GetSelectedIndex(); /// <summary>Get the selected item.</summary> /// <returns>Returns the selected item. If there are multiple selected items, or there is no selected item, null will be returned.</returns> description::Value GetSelectedItem(); /// <summary>Select an item with <see cref="ItemApplied"/> event raised.</summary> /// <param name="index">The index of the item to select. Set to -1 to clear the selection.</param> void ApplyItem(vint index); /// <summary>Select an item without <see cref="ItemApplied"/> event raised.</summary> /// <param name="index">The index of the item to select. Set to -1 to clear the selection.</param> void SelectItem(vint index); /// <summary>Get the minimum items visible in the drop down menu.</summary> /// <returns>The minimum items visible in the drop down menu.</returns> vint GetVisibleItemCount(); /// <summary>Set minimum items visible in the drop down menu.</summary> /// <param name="value">The minimum items visible in the drop down menu.</param> void SetVisibleItemCount(vint value); /// <summary>Get the dropdown menu.</summary> /// <returns>The dropdown menu.</returns> GuiToolstripMenu* GetSubMenu(); IDescriptable* QueryService(const WString& identifier)override; }; } } } #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 reflection { namespace description { /*********************************************************************** Serialization ***********************************************************************/ template<> struct TypedValueSerializerProvider<presentation::Color> { 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<presentation::DocumentFontSize> { 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<presentation::GlobalStringKey> { 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<presentation::INativeImage> INativeImage_Constructor(const WString& path); extern presentation::INativeCursor* INativeCursor_Constructor1(); extern presentation::INativeCursor* INativeCursor_Constructor2(presentation::INativeCursor::SystemCursorType type); template<typename T> Ptr<T> 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<presentation::compositions::IGuiAltAction*>& actions); template<typename T> WString Interface_GetIdentifier() { return T::Identifier; } } } } #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 { using namespace reflection; /*********************************************************************** Parser ***********************************************************************/ /// <summary>Represents a parser.</summary> class IGuiGeneralParser : public IDescriptable, public Description<IGuiGeneralParser> { public: }; template<typename T> class IGuiParser : public IGuiGeneralParser { using ErrorList = collections::List<Ptr<parsing::ParsingError>>; public: virtual Ptr<T> ParseInternal(const WString& text, ErrorList& errors) = 0; Ptr<T> Parse(GuiResourceLocation location, const WString& text, collections::List<GuiResourceError>& errors) { ErrorList parsingErrors; auto result = ParseInternal(text, parsingErrors); GuiResourceError::Transform(location, errors, parsingErrors); return result; } Ptr<T> Parse(GuiResourceLocation location, const WString& text, parsing::ParsingTextPos position, collections::List<GuiResourceError>& errors) { ErrorList parsingErrors; auto result = ParseInternal(text, parsingErrors); GuiResourceError::Transform(location, errors, parsingErrors, position); return result; } Ptr<T> Parse(GuiResourceLocation location, const WString& text, GuiResourceTextPos position, collections::List<GuiResourceError>& errors) { ErrorList parsingErrors; auto result = ParseInternal(text, parsingErrors); GuiResourceError::Transform(location, errors, parsingErrors, position); return result; } }; /*********************************************************************** Parser Manager ***********************************************************************/ /// <summary>Parser manager for caching parsing table globally.</summary> class IGuiParserManager : public IDescriptable, public Description<IGuiParserManager> { protected: typedef parsing::tabling::ParsingTable Table; public: /// <summary>Get a parsing table by name.</summary> /// <returns>The parsing table.</returns> /// <param name="name">The name.</param> virtual Ptr<Table> GetParsingTable(const WString& name)=0; /// <summary>Set a parsing table loader by name.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="name">The name.</param> /// <param name="loader">The parsing table loader.</param> virtual bool SetParsingTable(const WString& name, Func<Ptr<Table>()> loader)=0; /// <summary>Get a parser.</summary> /// <returns>The parser.</returns> /// <param name="name">The name.</param> virtual Ptr<IGuiGeneralParser> GetParser(const WString& name)=0; /// <summary>Set a parser by name.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="name">The name.</param> /// <param name="parser">The parser.</param> virtual bool SetParser(const WString& name, Ptr<IGuiGeneralParser> parser)=0; template<typename T> Ptr<IGuiParser<T>> GetParser(const WString& name); template<typename T> bool SetTableParser(const WString& tableName, const WString& parserName, Ptr<T>(*function)(const WString&, Ptr<Table>, collections::List<Ptr<parsing::ParsingError>>&, vint)); }; /// <summary>Get the global <see cref="IGuiParserManager"/> object.</summary> /// <returns>The parser manager.</returns> extern IGuiParserManager* GetParserManager(); /*********************************************************************** Strong Typed Table Parser ***********************************************************************/ template<typename T> class GuiStrongTypedTableParser : public Object, public IGuiParser<T> { protected: typedef parsing::tabling::ParsingTable Table; typedef Ptr<T>(ParserFunction)(const WString&, Ptr<Table>, collections::List<Ptr<parsing::ParsingError>>&, vint); protected: WString name; Ptr<Table> table; Func<ParserFunction> function; public: GuiStrongTypedTableParser(const WString& _name, ParserFunction* _function) :name(_name) ,function(_function) { } Ptr<T> ParseInternal(const WString& text, collections::List<Ptr<parsing::ParsingError>>& errors)override { if (!table) { table = GetParserManager()->GetParsingTable(name); } if (table) { collections::List<Ptr<parsing::ParsingError>> parsingErrors; auto result = function(text, table, parsingErrors, -1); if (parsingErrors.Count() > 0) { errors.Add(parsingErrors[0]); } return result; } return nullptr; } }; /*********************************************************************** Parser Manager ***********************************************************************/ template<typename T> Ptr<IGuiParser<T>> IGuiParserManager::GetParser(const WString& name) { return GetParser(name).Cast<IGuiParser<T>>(); } template<typename T> bool IGuiParserManager::SetTableParser(const WString& tableName, const WString& parserName, Ptr<T>(*function)(const WString&, Ptr<Table>, collections::List<Ptr<parsing::ParsingError>>&, vint)) { Ptr<IGuiParser<T>> parser=new GuiStrongTypedTableParser<T>(tableName, function); return SetParser(parserName, parser); } } } #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; /// <summary>A data structure storing the parsing input for text box control.</summary> struct RepeatingParsingInput { /// <summary>The text box edit version of the code.</summary> vuint editVersion = 0; /// <summary>The code.</summary> WString code; }; /*********************************************************************** ParsingOutput ***********************************************************************/ /// <summary>A data structure storing the parsing result for text box control.</summary> struct RepeatingParsingOutput { /// <summary>The parsed syntax tree.</summary> Ptr<parsing::ParsingTreeObject> node; /// <summary>The text box edit version of the code.</summary> vuint editVersion = 0; /// <summary>The code.</summary> WString code; /// <summary>The cache created from [T:vl.presentation.controls.RepeatingParsingExecutor.IParsingAnalyzer].</summary> Ptr<DescriptableObject> cache; }; /*********************************************************************** PartialParsingOutput ***********************************************************************/ /// <summary>A data structure storing the parsing result for partial updating when a text box control is modified.</summary> struct RepeatingPartialParsingOutput { /// <summary>The input data.</summary> RepeatingParsingOutput input; /// <summary>The rule name that can parse the code of the selected context.</summary> WString rule; /// <summary>Range of the original context in the input.</summary> parsing::ParsingTextRange originalRange; /// <summary>The original context in the syntax tree.</summary> Ptr<parsing::ParsingTreeObject> originalNode; /// <summary>The modified context in the syntax tree.</summary> Ptr<parsing::ParsingTreeObject> modifiedNode; /// <summary>The modified code of the selected context.</summary> WString modifiedCode; }; /*********************************************************************** PartialParsingOutput ***********************************************************************/ /// <summary>A data structure storing the information for a candidate item.</summary> struct ParsingCandidateItem { /// <summary>Semantic id.</summary> vint semanticId = -1; /// <summary>Display name.</summary> WString name; /// <summary>Tag object for any purpose, e.g., data binding.</summary> description::Value tag; }; /*********************************************************************** ParsingContext ***********************************************************************/ /// <summary>A data structure storing the context of a token.</summary> struct ParsingTokenContext { /// <summary>Token syntax tree for the selected token.</summary> parsing::ParsingTreeToken* foundToken = nullptr; /// <summary>The object syntax tree parent of the token.</summary> parsing::ParsingTreeObject* tokenParent = nullptr; /// <summary>Type of the parent.</summary> WString type; /// <summary>Field of the parent that contains the token.</summary> WString field; /// <summary>All acceptable semantic ids.</summary> Ptr<collections::List<vint>> 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 ***********************************************************************/ /// <summary>Repeating parsing executor.</summary> class RepeatingParsingExecutor : public RepeatingTaskExecutor<RepeatingParsingInput>, public Description<RepeatingParsingExecutor> { public: /// <summary>Callback.</summary> class ICallback : public virtual Interface { public: /// <summary>Callback when a parsing task is finished.</summary> /// <param name="output">the result of the parsing.</param> virtual void OnParsingFinishedAsync(const RepeatingParsingOutput& output)=0; /// <summary>Callback when <see cref="RepeatingParsingExecutor"/> requires enabling or disabling automatically repeating calling to the SubmitTask function.</summary> /// <param name="enabled">Set to true to require an automatically repeating calling to the SubmitTask function</param> virtual void RequireAutoSubmitTask(bool enabled)=0; }; /// <summary>Parsing analyzer.</summary> 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<parsing::ParsingTreeNode> ToChild(Ptr<parsing::ParsingTreeNode> node, const RepeatingPartialParsingOutput* output); protected: /// <summary>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.</summary> /// <returns>Returns the parent node.</returns> /// <param name="node">The node.</param> /// <param name="output">The partial parsing output, which describes how the whole tree is partial modified.</param> parsing::ParsingTreeNode* GetParent(parsing::ParsingTreeNode* node, const RepeatingPartialParsingOutput* output); /// <summary>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.</summary> /// <returns>Returns the member node.</returns> /// <param name="node">The node.</param> /// <param name="name">The name of the member.</param> /// <param name="output">The partial parsing output, which describes how the whole tree is partial modified.</param> Ptr<parsing::ParsingTreeNode> GetMember(parsing::ParsingTreeObject* node, const WString& name, const RepeatingPartialParsingOutput* output); /// <summary>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.</summary> /// <returns>Returns the item node.</returns> /// <param name="node">The node.</param> /// <param name="index">The index of the item.</param> /// <param name="output">The partial parsing output, which describes how the whole tree is partial modified.</param> Ptr<parsing::ParsingTreeNode> GetItem(parsing::ParsingTreeArray* node, vint index, const RepeatingPartialParsingOutput* output); public: /// <summary>Called when a <see cref="RepeatingParsingExecutor"/> is created.</summary> /// <param name="executor">The releated <see cref="RepeatingParsingExecutor"/>.</param> virtual void Attach(RepeatingParsingExecutor* executor) = 0; /// <summary>Called when a <see cref="RepeatingParsingExecutor"/> is destroyed.</summary> /// <param name="executor">The releated <see cref="RepeatingParsingExecutor"/>.</param> virtual void Detach(RepeatingParsingExecutor* executor) = 0; /// <summary>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.</summary> /// <param name="output">The new parsing result.</param> /// <returns>The created cache object, which can be null.</returns> virtual Ptr<DescriptableObject> CreateCacheAsync(const RepeatingParsingOutput& output) = 0; /// <summary>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.</summary> /// <param name="tokenContext">The token context.</param> /// <param name="output">The current parsing result.</param> /// <returns>The semantic id.</returns> virtual vint GetSemanticIdForTokenAsync(const ParsingTokenContext& tokenContext, const RepeatingParsingOutput& output) = 0; /// <summary>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.</summary> /// <param name="tokenContext">The token context.</param> /// <param name="partialOutput">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.</param> /// <param name="candidateItems">The candidate items.</param> virtual void GetCandidateItemsAsync(const ParsingTokenContext& tokenContext, const RepeatingPartialParsingOutput& partialOutput, collections::List<ParsingCandidateItem>& candidateItems) = 0; /// <summary>Create a tag object for a candidate item without a tag object. An candidate item without a tag maybe created by calling <see cref="GetCandidateItemsAsync"/> or any token marked by a @Candidate attribute in the grammar.</summary> /// <param name="item">The candidate item.</param> /// <returns>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.</returns> virtual description::Value CreateTagForCandidateItem(ParsingCandidateItem& item) = 0; }; /// <summary>A base class for implementing a callback.</summary> class CallbackBase : public virtual ICallback, public virtual ICommonTextEditCallback { private: bool callbackAutoPushing; elements::GuiColorizedTextElement* callbackElement; SpinLock* callbackElementModifyLock; protected: Ptr<RepeatingParsingExecutor> parsingExecutor; public: CallbackBase(Ptr<RepeatingParsingExecutor> _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<collections::List<vint>> semantics; }; private: Ptr<parsing::tabling::ParsingGeneralParser> grammarParser; WString grammarRule; Ptr<IParsingAnalyzer> analyzer; collections::List<ICallback*> callbacks; collections::List<ICallback*> activatedCallbacks; ICallback* autoPushingCallback; typedef collections::Pair<WString, WString> FieldDesc; collections::Dictionary<WString, vint> tokenIndexMap; collections::SortedList<WString> semanticIndexMap; collections::Dictionary<vint, TokenMetaData> tokenMetaDatas; collections::Dictionary<FieldDesc, FieldMetaData> fieldMetaDatas; protected: void Execute(const RepeatingParsingInput& input)override; void PrepareMetaData(); /// <summary>Called when semantic analyzing is needed. It is encouraged to set the "cache" fields in "context" argument. If there is an <see cref="RepeatingParsingExecutor::IParsingAnalyzer"/> binded to the <see cref="RepeatingParsingExecutor"/>, this function can be automatically done.</summary> /// <param name="context">The parsing result.</param> virtual void OnContextFinishedAsync(RepeatingParsingOutput& context); public: /// <summary>Initialize the parsing executor.</summary> /// <param name="_grammarParser">Parser generated from a grammar.</param> /// <param name="_grammarRule">The rule name to parse a complete code.</param> /// <param name="_analyzer">The parsing analyzer to create semantic metadatas, it can be null.</param> RepeatingParsingExecutor(Ptr<parsing::tabling::ParsingGeneralParser> _grammarParser, const WString& _grammarRule, Ptr<IParsingAnalyzer> _analyzer = 0); ~RepeatingParsingExecutor(); /// <summary>Get the internal parser that parse the text.</summary> /// <returns>The internal parser.</returns> Ptr<parsing::tabling::ParsingGeneralParser> GetParser(); /// <summary>Detach callback.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The callback.</param> bool AttachCallback(ICallback* value); /// <summary>Detach callback.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The callback.</param> bool DetachCallback(ICallback* value); /// <summary>Activate a callback. Activating a callback means that the callback owner has an ability to watch a text box modification, e.g., an attached <see cref="ICommonTextEditCallback"/> that is also an <see cref="ICallback"/>. The <see cref="RepeatingParsingExecutor"/> may require one of the activated callback to push code for parsing automatically via a call to <see cref="ICallback::RequireAutoSubmitTask"/>.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The callback.</param> bool ActivateCallback(ICallback* value); /// <summary>Deactivate a callback. See <see cref="ActivateCallback"/> for deatils.</summary> /// <returns>Returns true if this operation succeeded.</returns> /// <param name="value">The callback.</param> bool DeactivateCallback(ICallback* value); /// <summary>Get the parsing analyzer.</summary> /// <returns>The parsing analyzer.</returns> Ptr<IParsingAnalyzer> 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<parsing::tabling::ParsingTable::AttributeInfo> GetAttribute(vint index, const WString& name, vint argumentCount); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetColorAttribute(vint index); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetContextColorAttribute(vint index); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetSemanticAttribute(vint index); Ptr<parsing::tabling::ParsingTable::AttributeInfo> GetCandidateAttribute(vint index); Ptr<parsing::tabling::ParsingTable::AttributeInfo> 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 /*********************************************************************** .\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 /*********************************************************************** .\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 ***********************************************************************/ /// <summary>Grammar based auto complete controller.</summary> class GuiGrammarAutoComplete : public GuiTextBoxAutoCompleteBase , protected RepeatingParsingExecutor::CallbackBase , private RepeatingTaskExecutor<RepeatingParsingOutput> { public: /// <summary>The auto complete list data.</summary> struct AutoCompleteData : ParsingTokenContext { /// <summary>Available candidate tokens (in lexer token index).</summary> collections::List<vint> candidates; /// <summary>Available candidate tokens (in lexer token index) that marked with @AutoCompleteCandidate().</summary> collections::List<vint> shownCandidates; /// <summary>Candidate items.</summary> collections::List<ParsingCandidateItem> candidateItems; /// <summary>The start position of the editing token in global coordination.</summary> TextPos startPosition; }; /// <summary>The analysed data from an input code.</summary> struct AutoCompleteContext : RepeatingPartialParsingOutput { /// <summary>The edit version of modified code.</summary> vuint modifiedEditVersion = 0; /// <summary>The analysed auto complete list data.</summary> Ptr<AutoCompleteData> autoComplete; }; private: Ptr<parsing::tabling::ParsingGeneralParser> grammarParser; collections::SortedList<WString> leftRecursiveRules; bool editing; SpinLock editTraceLock; collections::List<TextEditNotifyStruct> 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<parsing::tabling::ParsingState::Future*>& futures); regex::RegexToken* TraverseTransitions( parsing::tabling::ParsingState& state, parsing::tabling::ParsingTransitionCollector& transitionCollector, TextPos stopPosition, collections::List<parsing::tabling::ParsingState::Future*>& nonRecoveryFutures, collections::List<parsing::tabling::ParsingState::Future*>& recoveryFutures ); regex::RegexToken* SearchValidInputToken( parsing::tabling::ParsingState& state, parsing::tabling::ParsingTransitionCollector& transitionCollector, TextPos stopPosition, AutoCompleteContext& newContext, collections::SortedList<vint>& 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: /// <summary>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 <see cref="RepeatingParsingExecutor::IParsingAnalyzer"/> binded to the <see cref="RepeatingParsingExecutor"/>, this function can be automatically done.</summary> /// <param name="context">The selected context.</param> virtual void OnContextFinishedAsync(AutoCompleteContext& context); /// <summary>Call this function in the derived class's destructor when it overrided <see cref="OnContextFinishedAsync"/>.</summary> void EnsureAutoCompleteFinished(); public: /// <summary>Create the auto complete controller with a created parsing executor.</summary> /// <param name="_parsingExecutor">The parsing executor.</param> GuiGrammarAutoComplete(Ptr<RepeatingParsingExecutor> _parsingExecutor); /// <summary>Create the auto complete controller with a specified grammar and start rule to create a <see cref="RepeatingParsingExecutor"/>.</summary> /// <param name="_grammarParser">Parser generated from a grammar.</param> /// <param name="_grammarRule"></param> GuiGrammarAutoComplete(Ptr<parsing::tabling::ParsingGeneralParser> _grammarParser, const WString& _grammarRule); ~GuiGrammarAutoComplete(); /// <summary>Get the internal parsing executor.</summary> /// <returns>The parsing executor.</returns> Ptr<RepeatingParsingExecutor> 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 ***********************************************************************/ /// <summary>Grammar based colorizer.</summary> class GuiGrammarColorizer : public GuiTextBoxRegexColorizer, protected RepeatingParsingExecutor::CallbackBase { typedef collections::Pair<WString, WString> FieldDesc; typedef collections::Dictionary<FieldDesc, vint> FieldContextColors; typedef collections::Dictionary<FieldDesc, vint> FieldSemanticColors; typedef elements::text::ColorEntry ColorEntry; public: /// <summary>Context for doing semantic colorizing.</summary> struct SemanticColorizeContext : ParsingTokenContext { /// <summary>Output semantic id that comes from one the argument in the @Semantic attribute.</summary> vint semanticId; }; private: collections::Dictionary<WString, ColorEntry> colorSettings; collections::Dictionary<vint, vint> semanticColorMap; SpinLock contextLock; RepeatingParsingOutput context; void OnParsingFinishedAsync(const RepeatingParsingOutput& output)override; protected: /// <summary>Called when the node is parsed successfully before restarting colorizing.</summary> /// <param name="context">The result of the parsing.</param> 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; /// <summary>Called when a @SemanticColor attribute in a grammar is activated during colorizing to determine a color for the token. If there is an <see cref="RepeatingParsingExecutor::IParsingAnalyzer"/> binded to the <see cref="RepeatingParsingExecutor"/>, this function can be automatically done.</summary> /// <param name="context">Context for doing semantic colorizing.</param> /// <param name="input">The corressponding result from the <see cref="RepeatingParsingExecutor"/>.</param> virtual void OnSemanticColorize(SemanticColorizeContext& context, const RepeatingParsingOutput& input); /// <summary>Call this function in the derived class's destructor when it overrided <see cref="OnSemanticColorize"/>.</summary> void EnsureColorizerFinished(); public: /// <summary>Create the colorizer with a created parsing executor.</summary> /// <param name="_parsingExecutor">The parsing executor.</param> GuiGrammarColorizer(Ptr<RepeatingParsingExecutor> _parsingExecutor); /// <summary>Create the colorizer with a specified grammar and start rule to create a <see cref="RepeatingParsingExecutor"/>.</summary> /// <param name="_grammarParser">Parser generated from a grammar.</param> /// <param name="_grammarRule"></param> GuiGrammarColorizer(Ptr<parsing::tabling::ParsingGeneralParser> _grammarParser, const WString& _grammarRule); ~GuiGrammarColorizer(); /// <summary>Reset all color settings.</summary> void BeginSetColors(); /// <summary>Get all color names.</summary> /// <returns>All color names.</returns> const collections::SortedList<WString>& GetColorNames(); /// <summary>Get the color for a token theme name (@Color or @ContextColor("theme-name") in the grammar).</summary> /// <returns>The color.</returns> /// <param name="name">The token theme name.</param> ColorEntry GetColor(const WString& name); /// <summary>Set a color for a token theme name (@Color or @ContextColor("theme-name") in the grammar).</summary> /// <param name="name">The token theme name.</param> /// <param name="entry">The color.</param> void SetColor(const WString& name, const ColorEntry& entry); /// <summary>Set a color for a token theme name (@Color or @ContextColor("theme-name") in the grammar).</summary> /// <param name="name">The token theme name.</param> /// <param name="color">The color.</param> void SetColor(const WString& name, const Color& color); /// <summary>Submit all color settings.</summary> void EndSetColors(); void ColorizeTokenContextSensitive(vint lineIndex, const wchar_t* text, vint start, vint length, vint& token, vint& contextState)override; /// <summary>Get the internal parsing executor.</summary> /// <returns>The parsing executor.</returns> Ptr<RepeatingParsingExecutor> GetParsingExecutor(); }; } } } #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<GalleryItemArranger> { 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, 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; bool EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; void ScrollUp(); void ScrollDown(); void UnblockScrollUpdate(); }; class GalleryResponsiveLayout : public compositions::GuiResponsiveCompositionBase, public Description<GalleryResponsiveLayout> { 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 /*********************************************************************** .\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<DocumentContainerRun*>& locatedRuns); extern Ptr<DocumentHyperlinkRun::Package> LocateHyperlink(DocumentParagraphRun* run, RunRangeMap& runRanges, vint row, vint start, vint end); extern Ptr<DocumentStyleProperties> CopyStyle(Ptr<DocumentStyleProperties> style); extern Ptr<DocumentRun> CopyRun(DocumentRun* run); extern Ptr<DocumentRun> CopyStyledText(collections::List<DocumentContainerRun*>& styleRuns, const WString& text); extern Ptr<DocumentRun> CopyRunRecursively(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end, bool deepCopy); extern void CollectStyleName(DocumentParagraphRun* run, collections::List<WString>& 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<DocumentRun>& leftRun, Ptr<DocumentRun>& rightRun); extern void ClearUnnecessaryRun(DocumentParagraphRun* run, DocumentModel* model); extern void AddStyle(DocumentParagraphRun* run, RunRangeMap& runRanges, vint start, vint end, Ptr<DocumentStyleProperties> 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<DocumentStyleProperties> SummarizeStyle(DocumentParagraphRun* run, RunRangeMap& runRanges, DocumentModel* model, vint start, vint end); extern Nullable<WString> SummarizeStyleName(DocumentParagraphRun* run, RunRangeMap& runRanges, DocumentModel* model, vint start, vint end); extern void AggregateStyle(Ptr<DocumentStyleProperties>& dst, Ptr<DocumentStyleProperties> src); } } } #endif
[ "vczh@163.com" ]
vczh@163.com
b4731b196dbf9700dd99ba576380070e6758f9b4
79b6341ebe2ee3b88d1ff2d941c37855ba7058c1
/src/hiptest/bin/EventProcessor.cc
a50cc6570f173b782e5ca93202f162277e4a856d
[ "Apache-2.0" ]
permissive
PointKernel/pixeltrack-standalone
401fdfce7ea7c6b3b566de8fed0c7ebd2b2f0dfa
3aeaf7c89ea7d15fbe1adf885cb43b80d40c0c01
refs/heads/master
2023-02-28T04:01:21.038203
2021-01-21T02:42:51
2021-01-21T02:42:51
265,636,330
0
0
Apache-2.0
2020-05-20T17:18:41
2020-05-20T17:18:40
null
UTF-8
C++
false
false
1,570
cc
#include "Framework/EmptyWaitingTask.h" #include "Framework/ESPluginFactory.h" #include "Framework/WaitingTask.h" #include "Framework/WaitingTaskHolder.h" #include "EventProcessor.h" namespace edm { EventProcessor::EventProcessor(int maxEvents, int numberOfStreams, std::vector<std::string> const& path, std::vector<std::string> const& esproducers, std::filesystem::path const& datadir, bool validation) : source_(maxEvents, registry_, datadir, validation) { for (auto const& name : esproducers) { pluginManager_.load(name); auto esp = ESPluginFactory::create(name, datadir); esp->produce(eventSetup_); } //schedules_.reserve(numberOfStreams); for (int i = 0; i < numberOfStreams; ++i) { schedules_.emplace_back(registry_, pluginManager_, &source_, &eventSetup_, i, path); } } void EventProcessor::runToCompletion() { // The task that waits for all other work auto globalWaitTask = make_empty_waiting_task(); globalWaitTask->increment_ref_count(); for (auto& s : schedules_) { s.runToCompletionAsync(WaitingTaskHolder(globalWaitTask.get())); } globalWaitTask->wait_for_all(); if (globalWaitTask->exceptionPtr()) { std::rethrow_exception(*(globalWaitTask->exceptionPtr())); } } void EventProcessor::endJob() { // Only on the first stream... schedules_[0].endJob(); } } // namespace edm
[ "matti.kortelainen@cern.ch" ]
matti.kortelainen@cern.ch
3f5e67b2536ae21d85a33734cc9b6f771cfa9720
dd3c82f053db20ad6a8de06378c2e75f90554232
/shell/platform/windows/flutter_window_win32_unittests.cc
0340e2fc554601f74b112ecdf90582c59e4f6209
[ "BSD-3-Clause" ]
permissive
blasten/engine
04867d48a1a7c59849bece0e82c844c8559bd27a
eb94e4f595b62a2557cc88ec3bef14d42e020ac8
refs/heads/master
2022-07-12T12:07:33.846463
2021-09-23T17:33:35
2021-09-23T17:33:35
235,491,084
0
6
BSD-3-Clause
2020-01-22T03:27:25
2020-01-22T03:27:24
null
UTF-8
C++
false
false
25,284
cc
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/common/json_message_codec.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/keyboard_key_channel_handler.h" #include "flutter/shell/platform/windows/keyboard_key_handler.h" #include "flutter/shell/platform/windows/testing/engine_modifier.h" #include "flutter/shell/platform/windows/testing/flutter_window_win32_test.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h" #include "flutter/shell/platform/windows/testing/test_keyboard.h" #include "flutter/shell/platform/windows/text_input_plugin.h" #include "flutter/shell/platform/windows/text_input_plugin_delegate.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <rapidjson/document.h> using testing::_; using testing::Invoke; using testing::Return; namespace flutter { namespace testing { namespace { static constexpr int32_t kDefaultPointerDeviceId = 0; // A key event handler that can be spied on while it forwards calls to the real // key event handler. class SpyKeyboardKeyHandler : public KeyboardHandlerBase { public: SpyKeyboardKeyHandler(flutter::BinaryMessenger* messenger, KeyboardKeyHandler::EventDispatcher redispatch_event) { real_implementation_ = std::make_unique<KeyboardKeyHandler>(redispatch_event); real_implementation_->AddDelegate( std::make_unique<KeyboardKeyChannelHandler>(messenger)); ON_CALL(*this, KeyboardHook(_, _, _, _, _, _, _)) .WillByDefault(Invoke(real_implementation_.get(), &KeyboardKeyHandler::KeyboardHook)); ON_CALL(*this, TextHook(_, _)) .WillByDefault( Invoke(real_implementation_.get(), &KeyboardKeyHandler::TextHook)); } MOCK_METHOD7(KeyboardHook, bool(FlutterWindowsView* window, int key, int scancode, int action, char32_t character, bool extended, bool was_down)); MOCK_METHOD2(TextHook, void(FlutterWindowsView* window, const std::u16string& text)); MOCK_METHOD0(ComposeBeginHook, void()); MOCK_METHOD0(ComposeCommitHook, void()); MOCK_METHOD0(ComposeEndHook, void()); MOCK_METHOD2(ComposeChangeHook, void(const std::u16string& text, int cursor_pos)); private: std::unique_ptr<KeyboardKeyHandler> real_implementation_; }; // A text input plugin that can be spied on while it forwards calls to the real // text input plugin. class SpyTextInputPlugin : public KeyboardHandlerBase, public TextInputPluginDelegate { public: SpyTextInputPlugin(flutter::BinaryMessenger* messenger) { real_implementation_ = std::make_unique<TextInputPlugin>(messenger, this); ON_CALL(*this, KeyboardHook(_, _, _, _, _, _, _)) .WillByDefault( Invoke(real_implementation_.get(), &TextInputPlugin::KeyboardHook)); ON_CALL(*this, TextHook(_, _)) .WillByDefault( Invoke(real_implementation_.get(), &TextInputPlugin::TextHook)); } MOCK_METHOD7(KeyboardHook, bool(FlutterWindowsView* window, int key, int scancode, int action, char32_t character, bool extended, bool was_down)); MOCK_METHOD2(TextHook, void(FlutterWindowsView* window, const std::u16string& text)); MOCK_METHOD0(ComposeBeginHook, void()); MOCK_METHOD0(ComposeCommitHook, void()); MOCK_METHOD0(ComposeEndHook, void()); MOCK_METHOD2(ComposeChangeHook, void(const std::u16string& text, int cursor_pos)); virtual void OnCursorRectUpdated(const Rect& rect) {} private: std::unique_ptr<TextInputPlugin> real_implementation_; }; class MockFlutterWindowWin32 : public FlutterWindowWin32, public MockMessageQueue { public: MockFlutterWindowWin32() : FlutterWindowWin32(800, 600) { ON_CALL(*this, GetDpiScale()) .WillByDefault(Return(this->FlutterWindowWin32::GetDpiScale())); } virtual ~MockFlutterWindowWin32() {} // Prevent copying. MockFlutterWindowWin32(MockFlutterWindowWin32 const&) = delete; MockFlutterWindowWin32& operator=(MockFlutterWindowWin32 const&) = delete; // Wrapper for GetCurrentDPI() which is a protected method. UINT GetDpi() { return GetCurrentDPI(); } // Simulates a WindowProc message from the OS. LRESULT InjectWindowMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) { return Win32SendMessage(NULL, message, wparam, lparam); } void InjectMessages(int count, Win32Message message1, ...) { Win32Message messages[count]; messages[0] = message1; va_list args; va_start(args, message1); for (int i = 1; i < count; i += 1) { messages[i] = va_arg(args, Win32Message); } va_end(args); InjectMessageList(count, messages); } MOCK_METHOD1(OnDpiScale, void(unsigned int)); MOCK_METHOD2(OnResize, void(unsigned int, unsigned int)); MOCK_METHOD4(OnPointerMove, void(double, double, FlutterPointerDeviceKind, int32_t)); MOCK_METHOD5(OnPointerDown, void(double, double, FlutterPointerDeviceKind, int32_t, UINT)); MOCK_METHOD5(OnPointerUp, void(double, double, FlutterPointerDeviceKind, int32_t, UINT)); MOCK_METHOD2(OnPointerLeave, void(FlutterPointerDeviceKind, int32_t)); MOCK_METHOD0(OnSetCursor, void()); MOCK_METHOD4(OnScroll, void(double, double, FlutterPointerDeviceKind, int32_t)); MOCK_METHOD0(GetDpiScale, float()); MOCK_METHOD0(IsVisible, bool()); MOCK_METHOD1(UpdateCursorRect, void(const Rect&)); protected: virtual BOOL Win32PeekMessage(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) override { return MockMessageQueue::Win32PeekMessage(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg); } LRESULT Win32DefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) override { return kWmResultDefault; } private: LRESULT Win32SendMessage(HWND hWnd, UINT const message, WPARAM const wparam, LPARAM const lparam) override { return HandleMessage(message, wparam, lparam); } }; class MockWindowBindingHandlerDelegate : public WindowBindingHandlerDelegate { public: MockWindowBindingHandlerDelegate() {} // Prevent copying. MockWindowBindingHandlerDelegate(MockWindowBindingHandlerDelegate const&) = delete; MockWindowBindingHandlerDelegate& operator=( MockWindowBindingHandlerDelegate const&) = delete; MOCK_METHOD2(OnWindowSizeChanged, void(size_t, size_t)); MOCK_METHOD4(OnPointerMove, void(double, double, FlutterPointerDeviceKind, int32_t)); MOCK_METHOD5(OnPointerDown, void(double, double, FlutterPointerDeviceKind, int32_t, FlutterPointerMouseButtons)); MOCK_METHOD5(OnPointerUp, void(double, double, FlutterPointerDeviceKind, int32_t, FlutterPointerMouseButtons)); MOCK_METHOD2(OnPointerLeave, void(FlutterPointerDeviceKind, int32_t)); MOCK_METHOD1(OnText, void(const std::u16string&)); MOCK_METHOD6(OnKey, bool(int, int, int, char32_t, bool, bool)); MOCK_METHOD0(OnComposeBegin, void()); MOCK_METHOD0(OnComposeCommit, void()); MOCK_METHOD0(OnComposeEnd, void()); MOCK_METHOD2(OnComposeChange, void(const std::u16string&, int)); MOCK_METHOD7(OnScroll, void(double, double, double, double, int, FlutterPointerDeviceKind, int32_t)); }; // A FlutterWindowsView that overrides the RegisterKeyboardHandlers function // to register the keyboard hook handlers that can be spied upon. class TestFlutterWindowsView : public FlutterWindowsView { public: TestFlutterWindowsView(std::unique_ptr<WindowBindingHandler> window_binding, WPARAM virtual_key, bool is_printable = true) : FlutterWindowsView(std::move(window_binding)), virtual_key_(virtual_key), is_printable_(is_printable) {} SpyKeyboardKeyHandler* key_event_handler; SpyTextInputPlugin* text_input_plugin; void InjectPendingEvents(MockFlutterWindowWin32* win32window) { win32window->InjectMessageList(pending_responds_.size(), pending_responds_.data()); pending_responds_.clear(); } protected: void RegisterKeyboardHandlers( flutter::BinaryMessenger* messenger, flutter::KeyboardKeyHandler::EventDispatcher dispatch_event, flutter::KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state) override { auto spy_key_event_handler = std::make_unique<SpyKeyboardKeyHandler>( messenger, [this](UINT cInputs, LPINPUT pInputs, int cbSize) -> UINT { return this->SendInput(cInputs, pInputs, cbSize); }); auto spy_text_input_plugin = std::make_unique<SpyTextInputPlugin>(messenger); key_event_handler = spy_key_event_handler.get(); text_input_plugin = spy_text_input_plugin.get(); AddKeyboardHandler(std::move(spy_key_event_handler)); AddKeyboardHandler(std::move(spy_text_input_plugin)); } private: UINT SendInput(UINT cInputs, LPINPUT pInputs, int cbSize) { // Simulate the event loop by just sending the event sent to // "SendInput" directly to the window. const KEYBDINPUT kbdinput = pInputs->ki; const UINT message = (kbdinput.dwFlags & KEYEVENTF_KEYUP) ? WM_KEYUP : WM_KEYDOWN; const bool is_key_up = kbdinput.dwFlags & KEYEVENTF_KEYUP; const LPARAM lparam = CreateKeyEventLparam( kbdinput.wScan, kbdinput.dwFlags & KEYEVENTF_EXTENDEDKEY, is_key_up); // Windows would normally fill in the virtual key code for us, so we // simulate it for the test with the key we know is in the test. The // KBDINPUT we're passed doesn't have it filled in (on purpose, so that // Windows will fill it in). // // TODO(dkwingsmt): Don't check the message results for redispatched // messages for now, because making them work takes non-trivial rework // to our current structure. https://github.com/flutter/flutter/issues/87843 // If this is resolved, change them to kWmResultDefault. pending_responds_.push_back( Win32Message{message, virtual_key_, lparam, kWmResultDontCheck}); if (is_printable_ && (kbdinput.dwFlags & KEYEVENTF_KEYUP) == 0) { pending_responds_.push_back( Win32Message{WM_CHAR, virtual_key_, lparam, kWmResultDontCheck}); } return 1; } std::vector<Win32Message> pending_responds_; WPARAM virtual_key_; bool is_printable_; }; // The static value to return as the "handled" value from the framework for key // events. Individual tests set this to change the framework response that the // test engine simulates. static bool test_response = false; // Returns an engine instance configured with dummy project path values, and // overridden methods for sending platform messages, so that the engine can // respond as if the framework were connected. std::unique_ptr<FlutterWindowsEngine> GetTestEngine() { FlutterDesktopEngineProperties properties = {}; properties.assets_path = L"C:\\foo\\flutter_assets"; properties.icu_data_path = L"C:\\foo\\icudtl.dat"; properties.aot_library_path = L"C:\\foo\\aot.so"; FlutterProjectBundle project(properties); auto engine = std::make_unique<FlutterWindowsEngine>(project); EngineModifier modifier(engine.get()); MockEmbedderApiForKeyboard( modifier, [] { return test_response; }, [](const FlutterKeyEvent* event) { return false; }); return engine; } } // namespace TEST(FlutterWindowWin32Test, CreateDestroy) { FlutterWindowWin32Test window(800, 600); ASSERT_TRUE(TRUE); } // Tests key event propagation of non-printable, non-modifier key down events. TEST(FlutterWindowWin32Test, NonPrintableKeyDownPropagation) { ::testing::InSequence in_sequence; constexpr WPARAM virtual_key = VK_LEFT; constexpr WPARAM scan_code = 10; constexpr char32_t character = 0; MockFlutterWindowWin32 win32window; auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); TestFlutterWindowsView flutter_windows_view( std::move(window_binding_handler), virtual_key, false /* is_printable */); win32window.SetView(&flutter_windows_view); LPARAM lparam = CreateKeyEventLparam(scan_code, false, false); // Test an event not handled by the framework { test_response = false; flutter_windows_view.SetEngine(std::move(GetTestEngine())); EXPECT_CALL(*flutter_windows_view.key_event_handler, KeyboardHook(_, virtual_key, scan_code, WM_KEYDOWN, character, false /* extended */, _)) .Times(2) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.text_input_plugin, KeyboardHook(_, _, _, _, _, _, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.key_event_handler, TextHook(_, _)) .Times(0); EXPECT_CALL(*flutter_windows_view.text_input_plugin, TextHook(_, _)) .Times(0); win32window.InjectMessages(1, Win32Message{WM_KEYDOWN, virtual_key, lparam}); flutter_windows_view.InjectPendingEvents(&win32window); } // Test an event handled by the framework { test_response = true; EXPECT_CALL(*flutter_windows_view.key_event_handler, KeyboardHook(_, virtual_key, scan_code, WM_KEYDOWN, character, false /* extended */, false /* PrevState */)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.text_input_plugin, KeyboardHook(_, _, _, _, _, _, _)) .Times(0); win32window.InjectMessages(1, Win32Message{WM_KEYDOWN, virtual_key, lparam}); flutter_windows_view.InjectPendingEvents(&win32window); } } // Tests key event propagation of printable character key down events. These // differ from non-printable characters in that they follow a different code // path in the WndProc (HandleMessage), producing a follow-on WM_CHAR event. TEST(FlutterWindowWin32Test, CharKeyDownPropagation) { // ::testing::InSequence in_sequence; constexpr WPARAM virtual_key = 65; // The "A" key, which produces a character constexpr WPARAM scan_code = 30; constexpr char32_t character = 65; MockFlutterWindowWin32 win32window; auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); TestFlutterWindowsView flutter_windows_view( std::move(window_binding_handler), virtual_key, true /* is_printable */); win32window.SetView(&flutter_windows_view); LPARAM lparam = CreateKeyEventLparam(scan_code, false, false); flutter_windows_view.SetEngine(std::move(GetTestEngine())); // Test an event not handled by the framework { test_response = false; EXPECT_CALL(*flutter_windows_view.key_event_handler, KeyboardHook(_, virtual_key, scan_code, WM_KEYDOWN, character, false, false)) .Times(2) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.text_input_plugin, KeyboardHook(_, _, _, _, _, _, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.key_event_handler, TextHook(_, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.text_input_plugin, TextHook(_, _)) .Times(1) .RetiresOnSaturation(); win32window.InjectMessages(2, Win32Message{WM_KEYDOWN, virtual_key, lparam}, Win32Message{WM_CHAR, virtual_key, lparam}); flutter_windows_view.InjectPendingEvents(&win32window); } // Test an event handled by the framework { test_response = true; EXPECT_CALL(*flutter_windows_view.key_event_handler, KeyboardHook(_, virtual_key, scan_code, WM_KEYDOWN, character, false, false)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.text_input_plugin, KeyboardHook(_, _, _, _, _, _, _)) .Times(0); EXPECT_CALL(*flutter_windows_view.key_event_handler, TextHook(_, _)) .Times(0); EXPECT_CALL(*flutter_windows_view.text_input_plugin, TextHook(_, _)) .Times(0); win32window.InjectMessages(2, Win32Message{WM_KEYDOWN, virtual_key, lparam}, Win32Message{WM_CHAR, virtual_key, lparam}); flutter_windows_view.InjectPendingEvents(&win32window); } } // Tests key event propagation of modifier key down events. This is different // from non-printable events in that they call MapVirtualKey, resulting in a // slightly different code path. TEST(FlutterWindowWin32Test, ModifierKeyDownPropagation) { constexpr WPARAM virtual_key = VK_LSHIFT; constexpr WPARAM scan_code = 0x2a; constexpr char32_t character = 0; MockFlutterWindowWin32 win32window; auto window_binding_handler = std::make_unique<::testing::NiceMock<MockWindowBindingHandler>>(); TestFlutterWindowsView flutter_windows_view( std::move(window_binding_handler), virtual_key, false /* is_printable */); win32window.SetView(&flutter_windows_view); LPARAM lparam = CreateKeyEventLparam(scan_code, false, false); // Test an event not handled by the framework { test_response = false; flutter_windows_view.SetEngine(std::move(GetTestEngine())); EXPECT_CALL(*flutter_windows_view.key_event_handler, KeyboardHook(_, virtual_key, scan_code, WM_KEYDOWN, character, false /* extended */, false)) .Times(2) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.text_input_plugin, KeyboardHook(_, _, _, _, _, _, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.key_event_handler, TextHook(_, _)) .Times(0); EXPECT_CALL(*flutter_windows_view.text_input_plugin, TextHook(_, _)) .Times(0); EXPECT_EQ(win32window.InjectWindowMessage(WM_KEYDOWN, virtual_key, lparam), 0); flutter_windows_view.InjectPendingEvents(&win32window); } // Test an event handled by the framework { test_response = true; EXPECT_CALL(*flutter_windows_view.key_event_handler, KeyboardHook(_, virtual_key, scan_code, WM_KEYDOWN, character, false /* extended */, false)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*flutter_windows_view.text_input_plugin, KeyboardHook(_, _, _, _, _, _, _)) .Times(0); EXPECT_EQ(win32window.InjectWindowMessage(WM_KEYDOWN, virtual_key, lparam), 0); flutter_windows_view.InjectPendingEvents(&win32window); } } // Tests that composing rect updates are transformed from Flutter logical // coordinates to device coordinates and passed to the text input manager // when the DPI scale is 100% (96 DPI). TEST(FlutterWindowWin32Test, OnCursorRectUpdatedRegularDPI) { MockFlutterWindowWin32 win32window; ON_CALL(win32window, GetDpiScale()).WillByDefault(Return(1.0)); EXPECT_CALL(win32window, GetDpiScale()).Times(1); Rect cursor_rect(Point(10, 20), Size(30, 40)); EXPECT_CALL(win32window, UpdateCursorRect(cursor_rect)).Times(1); win32window.OnCursorRectUpdated(cursor_rect); } // Tests that composing rect updates are transformed from Flutter logical // coordinates to device coordinates and passed to the text input manager // when the DPI scale is 150% (144 DPI). TEST(FlutterWindowWin32Test, OnCursorRectUpdatedHighDPI) { MockFlutterWindowWin32 win32window; ON_CALL(win32window, GetDpiScale()).WillByDefault(Return(1.5)); EXPECT_CALL(win32window, GetDpiScale()).Times(1); Rect expected_cursor_rect(Point(15, 30), Size(45, 60)); EXPECT_CALL(win32window, UpdateCursorRect(expected_cursor_rect)).Times(1); Rect cursor_rect(Point(10, 20), Size(30, 40)); win32window.OnCursorRectUpdated(cursor_rect); } TEST(FlutterWindowWin32Test, OnPointerStarSendsDeviceType) { FlutterWindowWin32 win32window(100, 100); MockWindowBindingHandlerDelegate delegate; win32window.SetView(&delegate); // Move EXPECT_CALL(delegate, OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId)) .Times(1); EXPECT_CALL(delegate, OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId)) .Times(1); EXPECT_CALL(delegate, OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId)) .Times(1); // Down EXPECT_CALL( delegate, OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); EXPECT_CALL( delegate, OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); EXPECT_CALL( delegate, OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); // Up EXPECT_CALL(delegate, OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); EXPECT_CALL(delegate, OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); EXPECT_CALL(delegate, OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, kFlutterPointerButtonMousePrimary)) .Times(1); // Leave EXPECT_CALL(delegate, OnPointerLeave(kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId)) .Times(1); EXPECT_CALL(delegate, OnPointerLeave(kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId)) .Times(1); EXPECT_CALL(delegate, OnPointerLeave(kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId)) .Times(1); win32window.OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId); win32window.OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerLeave(kFlutterPointerDeviceKindMouse, kDefaultPointerDeviceId); // Touch win32window.OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId); win32window.OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerLeave(kFlutterPointerDeviceKindTouch, kDefaultPointerDeviceId); // Pen win32window.OnPointerMove(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId); win32window.OnPointerDown(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerUp(10.0, 10.0, kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId, WM_LBUTTONDOWN); win32window.OnPointerLeave(kFlutterPointerDeviceKindStylus, kDefaultPointerDeviceId); } } // namespace testing } // namespace flutter
[ "noreply@github.com" ]
blasten.noreply@github.com
62f35c1f86527b1947afbc15531b6b13c5be0293
df662d129a1702cfe51e66561f25d4e8edf78892
/source/headers/Chunk.hpp
7038cb07a6ddeebb0518b650fd3431d8756ee3d2
[]
no_license
nopenoway0/kcd_skin_modifier
c26d28fbcca9b0a3caab66faec0886412f0e762c
d7660f2cf95a401ceb9682c7df60701936a02167
refs/heads/master
2020-03-22T17:00:58.021426
2018-07-14T01:48:53
2018-07-14T01:48:53
140,366,899
1
0
null
2018-07-14T01:48:55
2018-07-10T02:35:11
C++
UTF-8
C++
false
false
678
hpp
#ifndef CHUNK #define CHUNK #include <iostream> #include "Bytable.hpp" using std::ifstream; template <class T> class Chunk : public Bytable{ protected: T* chunk_header; public: Chunk(T& chunk_header){ this->chunk_header = new T(chunk_header); } Chunk(T* chunk_header){ this->chunk_header = chunk_header; } virtual void load(ifstream& f){ std::cerr << "unimplemented load"; throw "unimplemented load"; } T getHeader(){ return *chunk_header; } char* asBytes(int& s) override{ s = 0; std::cerr << "unimplemented body as bytes" << std::endl; return nullptr; }; ~Chunk(){ //delete chunk_header; } }; #endif
[ "benjamin.gottheil@sjsu.edu" ]
benjamin.gottheil@sjsu.edu
fb803596238f06615f06ae8bfcc173910d224856
235f63ddcbc839485510617eebcc56f173dc0da6
/RECURSION/factorialTrailingZeros.cpp
0a13fa5a55bef261a5b161e20ff241da76be83a6
[]
no_license
SunithaDeviP/RECURSION
4fc2af2379627bd54c7e607a586073573e925bf4
aa633f5ee6485600bcfbffdb9f68214ee882563c
refs/heads/master
2020-06-16T19:10:58.034956
2019-07-07T16:45:31
2019-07-07T16:45:31
195,675,056
3
0
null
null
null
null
UTF-8
C++
false
false
236
cpp
#include<stdio.h> int trailingZeros(int n) { if(n<5) return 0; return n/5 + trailingZeros(n/5); } int main() { int fact = 5; // printf("FACTORILA OF 5 = %d",fact; printf("NO. OF TRAILING %d",trailingZeros(fact)); }
[ "noreply@github.com" ]
SunithaDeviP.noreply@github.com
baaacb4fd808caaf67c481fa3281d6692f5ab9dd
950d94513b3166ae4f99c1f6fba7e66ebf0f889a
/UVA/Graph/852 - Deciding victory in Go.cpp
8c1dc2ae761eabb0b3f99a88d9294aaf99e87b41
[]
no_license
Alarxon/Competitive-Programming
2a1f570d6ad3733b77caec1f5c72e3646acaee9f
9419be132fdcf85f9eeeab314f15c4c0e63e9d39
refs/heads/master
2021-01-01T18:10:30.412195
2017-07-25T11:15:45
2017-07-25T11:15:45
98,268,890
0
0
null
null
null
null
UTF-8
C++
false
false
2,193
cpp
//Number 27 #include <bits/stdc++.h> using namespace std; int dr[] = {1,0,-1, 0}; int dc[] = {0,1, 0,-1}; char grafo[9][9]; int negro; int blanco; int floodfill(int r, int c, char c1, char c2) { if (r < 0 || r >= 9 || c < 0 || c >= 9){ return 0; } if (grafo[r][c] == 'X'){ negro++; return 0; } if(grafo[r][c] == 'O'){ blanco++; return 0; } if(grafo[r][c] == '#'){ return 0; } int ans = 1; grafo[r][c] = c2; for (int d = 0; d < 4; d++){ ans += floodfill(r + dr[d], c + dc[d], c1, c2); } return ans; } int floodfillColores(int r, int c, char c1, char c2) { if (r < 0 || r >= 9 || c < 0 || c >= 9){ return 0; } if (grafo[r][c] != c1){ return 0; } int ans = 1; grafo[r][c] = c2; for (int d = 0; d < 4; d++){ ans += floodfillColores(r + dr[d], c + dc[d], c1, c2); } return ans; } int main() { int casos; cin >> casos; for(int i=0; i<casos; i++){ for(int j=0; j<9; j++){ for(int k=0; k<9; k++){ cin >> grafo[j][k]; } } int Blancos=0; int Negros=0; for(int j=0; j<9; j++){ for(int k=0; k<9; k++){ if(grafo[j][k] == '.'){ blanco = 0; negro = 0; int resultado = floodfill(j,k, '.', '#'); if(blanco > 0 && negro == 0){ Blancos = Blancos + resultado; } if(negro > 0 && blanco == 0){ Negros = Negros + resultado; } } } } for(int j=0; j<9; j++){ for(int k=0; k<9; k++){ if(grafo[j][k] == 'X'){ int resultado = floodfillColores(j, k, 'X', '#'); Negros = Negros + resultado; } if(grafo[j][k] == 'O'){ int resultado = floodfillColores(j, k, 'O', '#'); Blancos = Blancos + resultado; } } } cout << "Black " << Negros << " White " << Blancos << "\n"; } return 0; }
[ "noreply@github.com" ]
Alarxon.noreply@github.com
cff4d5b831f88771d1b9b08c0b8839946ac7746d
9db09a23d050d687dd87eef23384530dab9182ca
/main.cpp
d025fce412852e2dea239bc77e24304fa189a4cf
[]
no_license
MaxRayskiy/processor
6fefc34f17c89fbcb24615bfbd0958359b8203e4
348cde1b9400e538936b8bd5f22daf91d8934fd6
refs/heads/master
2022-12-18T19:16:00.357205
2020-09-03T15:10:53
2020-09-03T15:10:53
225,448,343
0
0
null
null
null
null
UTF-8
C++
false
false
307
cpp
#include <iostream> #include "compiler.hpp" #include "executor.hpp" int main() { Compiler compiler; compiler.SetSource("..//asm/factorial"); compiler.SetExecutable(); compiler.Compile(); compiler.WriteBinary(); Executor executor; executor.ReadBinary(); executor.Execute(); return 0; }
[ "max.rayskiy@gmail.com" ]
max.rayskiy@gmail.com
02dc5295e9950f8dcc6fd3d31664e8b0825d96bf
71bd065fb12ab2d07d4371f1903b45411b91735d
/controller/src/vnsw/agent/oper/test/test_aap6.cc
e16f7e0bbc4f26a3c5ac9f6f3213c5c9d9582234
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
syedaliawaissabir/BGPaaS
dffc3d07eddec91be3d70d8d226b2192511b61ff
71931e462944e39d31ca16167f273ab9fa84145a
refs/heads/master
2020-06-30T23:38:29.650304
2017-07-31T11:13:46
2017-07-31T11:13:46
74,343,705
0
1
null
2016-12-02T14:15:51
2016-11-21T08:46:43
C++
UTF-8
C++
false
false
25,198
cc
/* * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. */ #include "base/os.h" #include "testing/gunit.h" #include <base/logging.h> #include <io/event_manager.h> #include <tbb/task.h> #include <base/task.h> #include <cmn/agent_cmn.h> #include "cfg/cfg_init.h" #include "oper/operdb_init.h" #include "controller/controller_init.h" #include "pkt/pkt_init.h" #include "services/services_init.h" #include "vrouter/ksync/ksync_init.h" #include "oper/interface_common.h" #include "oper/nexthop.h" #include "route/route.h" #include "oper/vrf.h" #include "oper/mpls.h" #include "oper/vm.h" #include "oper/vn.h" #include "oper/path_preference.h" #include "filter/acl.h" #include "test_cmn_util.h" #include "vr_types.h" #include <controller/controller_export.h> #include <ksync/ksync_sock_user.h> #include <boost/assign/list_of.hpp> using namespace boost::assign; MacAddress zero_mac; void RouterIdDepInit(Agent *agent) { } struct PortInfo input[] = { {"intf1", 1, "1.1.1.1", "00:00:00:01:01:01", 1, 1, "fd10::2"}, }; IpamInfo ipam_info[] = { {"1.1.1.0", 24, "1.1.1.10"}, {"fd10::", 96, "fd10::1"}, }; class TestAap6 : public ::testing::Test { public: TestAap6() { peer_ = CreateBgpPeer(Ip4Address(1), "BGP Peer 1"); } ~TestAap6() { DeleteBgpPeer(peer_); } uint32_t Ip2PrefixLen(IpAddress addr) { uint32_t plen = 0; if (addr.is_v4()) { plen = 32; } else if (addr.is_v6()) { plen = 128; } return plen; } void AddAap(std::string intf_name, int intf_id, std::vector<IpAddress> aap_list) { std::ostringstream buf; buf << "<virtual-machine-interface-allowed-address-pairs>"; std::vector<IpAddress>::iterator it = aap_list.begin(); while (it != aap_list.end()) { uint32_t plen = Ip2PrefixLen(*it); buf << "<allowed-address-pair>"; buf << "<ip>"; buf << "<ip-prefix>" << it->to_string()<<"</ip-prefix>"; buf << "<ip-prefix-len>"<< plen << "</ip-prefix-len>"; buf << "</ip>"; buf << "<mac><mac-address>" << "00:00:00:00:00:00" << "</mac-address></mac>"; buf << "<flag>" << "act-stby" << "</flag>"; buf << "</allowed-address-pair>"; it++; } buf << "</virtual-machine-interface-allowed-address-pairs>"; char cbuf[10000]; strcpy(cbuf, buf.str().c_str()); AddNode("virtual-machine-interface", intf_name.c_str(), intf_id, cbuf); client->WaitForIdle(); } void AddAap(std::string intf_name, int intf_id, IpAddress ip, const std::string &mac) { std::ostringstream buf; uint32_t plen = Ip2PrefixLen(ip); buf << "<virtual-machine-interface-allowed-address-pairs>"; buf << "<allowed-address-pair>"; buf << "<ip>"; buf << "<ip-prefix>" << ip.to_string() <<"</ip-prefix>"; buf << "<ip-prefix-len>"<< plen << "</ip-prefix-len>"; buf << "</ip>"; buf << "<mac>" << mac << "</mac>"; buf << "<flag>" << "act-stby" << "</flag>"; buf << "</allowed-address-pair>"; buf << "</virtual-machine-interface-allowed-address-pairs>"; char cbuf[10000]; strcpy(cbuf, buf.str().c_str()); AddNode("virtual-machine-interface", intf_name.c_str(), intf_id, cbuf); client->WaitForIdle(); } void AddEcmpAap(std::string intf_name, int intf_id, IpAddress ip) { std::ostringstream buf; uint32_t plen = Ip2PrefixLen(ip); buf << "<virtual-machine-interface-allowed-address-pairs>"; buf << "<allowed-address-pair>"; buf << "<ip>"; buf << "<ip-prefix>" << ip.to_string() <<"</ip-prefix>"; buf << "<ip-prefix-len>"<< plen << "</ip-prefix-len>"; buf << "</ip>"; buf << "<mac><mac-address>" << "00:00:00:00:00:00" << "</mac-address></mac>"; buf << "<address-mode>" << "active-active" << "</address-mode>"; buf << "</allowed-address-pair>"; buf << "</virtual-machine-interface-allowed-address-pairs>"; char cbuf[10000]; strcpy(cbuf, buf.str().c_str()); AddNode("virtual-machine-interface", intf_name.c_str(), intf_id, cbuf); client->WaitForIdle(); } virtual void SetUp() { CreateVmportEnv(input, 1); client->WaitForIdle(); AddIPAM("vn1", ipam_info, 2); client->WaitForIdle(); EXPECT_TRUE(VmPortActive(1)); } virtual void TearDown() { DeleteVmportEnv(input, 1, 1, 0, NULL, NULL, true, true); client->WaitForIdle(); DelIPAM("vn1"); client->WaitForIdle(); EXPECT_FALSE(VmPortFindRetDel(1)); EXPECT_FALSE(VrfFind("vrf1", true)); client->WaitForIdle(); } protected: Peer *peer_; }; //Add and delete allowed address pair route TEST_F(TestAap6, AddDel_1) { Ip6Address ip = Ip6Address::from_string("fd10::10"); std::vector<IpAddress> v; v.push_back(ip); AddAap("intf1", 1, v); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); v.clear(); AddAap("intf1", 1, v); EXPECT_FALSE(RouteFindV6("vrf1", ip, 128)); } TEST_F(TestAap6, AddDel_2) { Ip6Address ip = Ip6Address::from_string("fd10::10"); std::vector<IpAddress> v; v.push_back(ip); AddAap("intf1", 1, v); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); DelLink("virtual-machine-interface-routing-instance", "intf1", "routing-instance", "vrf1"); client->WaitForIdle(); EXPECT_FALSE(RouteFindV6("vrf1", ip, 128)); AddLink("virtual-machine-interface-routing-instance", "intf1", "routing-instance", "vrf1"); client->WaitForIdle(); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); } TEST_F(TestAap6, Update) { Ip6Address ip1 = Ip6Address::from_string("fd10::10"); Ip6Address ip2 = Ip6Address::from_string("fd11::10"); std::vector<IpAddress> v; v.push_back(ip1); AddAap("intf1", 1, v); EXPECT_TRUE(RouteFindV6("vrf1", ip1, 128)); v.push_back(ip2); AddAap("intf1", 1, v); EXPECT_TRUE(RouteFindV6("vrf1", ip1, 128)); EXPECT_TRUE(RouteFindV6("vrf1", ip2, 128)); v.clear(); AddAap("intf1", 1, v); EXPECT_FALSE(RouteFindV6("vrf1", ip1, 128)); EXPECT_FALSE(RouteFindV6("vrf1", ip2, 128)); } //Check if subnet gateway for allowed address pair route gets set properly TEST_F(TestAap6, SubnetGw) { Ip6Address ip1 = Ip6Address::from_string("fd10::10"); std::vector<IpAddress> v; v.push_back(ip1); AddAap("intf1", 1, v); EXPECT_TRUE(RouteFindV6("vrf1", ip1, 128)); IpamInfo ipam_info[] = { {"fd10::", 120, "fd10::200", true}, }; AddIPAM("vn1", ipam_info, 1, NULL, "vdns1"); client->WaitForIdle(); Ip6Address subnet_service_ip = Ip6Address::from_string("fd10::200"); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", ip1, 128); EXPECT_TRUE(rt->GetActivePath()->subnet_service_ip() == subnet_service_ip); DelIPAM("vn1", "vdns1"); client->WaitForIdle(); v.clear(); AddAap("intf1", 1, v); EXPECT_FALSE(RouteFindV6("vrf1", ip1, 128)); } //When both IP and mac are given in config, verify that routes get added to //both V6 table and EVPN table. TEST_F(TestAap6, EvpnRoute) { Ip6Address ip = Ip6Address::from_string("fd10::10"); MacAddress mac("0a:0b:0c:0d:0e:0f"); VmInterface *vm_intf = static_cast<VmInterface *>(VmPortGet(1)); AddAap("intf1", 1, ip, mac.ToString()); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); EXPECT_TRUE(EvpnRouteGet("vrf1", mac, ip, 0)); EXPECT_TRUE(vm_intf->allowed_address_pair_list().list_.size() == 1); AddAap("intf1", 1, Ip6Address(), zero_mac.ToString()); EXPECT_FALSE(RouteFindV6("vrf1", ip, 128)); EXPECT_FALSE(EvpnRouteGet("vrf1", mac, ip, 0)); EXPECT_TRUE(vm_intf->allowed_address_pair_list().list_.size() == 0); } //Just add a local path, verify that sequence no gets initialized to 0 TEST_F(TestAap6, StateMachine_1) { Ip6Address ip = Ip6Address::from_string("fd10::10"); std::vector<IpAddress> v; v.push_back(ip); AddAap("intf1", 1, v); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", ip, 128); const AgentPath *path = rt->GetActivePath(); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); //cleanup v.clear(); AddAap("intf1", 1, v); EXPECT_FALSE(RouteFindV6("vrf1", ip, 128)); } //Add a remote path with same preference and verify that local path //moves to wait for traffic state TEST_F(TestAap6, StateMachine_2) { Ip6Address ip = Ip6Address::from_string("fd10::10"); std::vector<IpAddress> v; v.push_back(ip); AddAap("intf1", 1, v); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); //On addition of AAP config, verify that the initial state of the path for //VMI peer is set to the following //--Preference as LOW, sequence as 0 and wait_for_traffic as TRUE. VmInterface *vm_intf = VmInterfaceGet(1); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", ip, 128); const AgentPath *path = rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); //Enqueue traffic seen Agent::GetInstance()->oper_db()->route_preference_module()-> EnqueueTrafficSeen(ip, 128, vm_intf->id(), vm_intf->vrf()->vrf_id(), vm_intf->vm_mac()); client->WaitForIdle(); //After seeing traffic, verify that path for VMI peer is updated as follows //--Preference as HIGH, sequence as 1 and wait_for_traffic as FALSE. EXPECT_TRUE(path->path_preference().sequence() == 1); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); //cleanup v.clear(); AddAap("intf1", 1, v); EXPECT_FALSE(RouteFindV6("vrf1", ip, 128)); } TEST_F(TestAap6, StateMachine_3) { Ip6Address ip = Ip6Address::from_string("fd10::10"); MacAddress mac("0a:0b:0c:0d:0e:0f"); AddAap("intf1", 1, ip, mac.ToString()); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); EXPECT_TRUE(EvpnRouteGet("vrf1", mac, ip, 0)); //Add a remote path with same preference and higher sequence number Ip4Address server_ip = Ip4Address::from_string("10.1.1.3"); PathPreference path_preference(1, PathPreference::LOW, false, false); TunnelType::TypeBmap bmap = (1 << TunnelType::MPLS_GRE); Inet6TunnelRouteAdd(peer_, "vrf1", ip, 128, server_ip, bmap, 16, "vn1", SecurityGroupList(), path_preference); client->WaitForIdle(); VmInterface *vm_intf = VmInterfaceGet(1); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", ip, 128); EvpnRouteEntry *evpn_rt = EvpnRouteGet("vrf1", mac, ip, 0); //Verify that paths for unicast and evpn routes for VMI peer are set to //default values const AgentPath *path = rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); path = evpn_rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); //Enqueue traffic Agent::GetInstance()->oper_db()->route_preference_module()-> EnqueueTrafficSeen(ip, 128, vm_intf->id(), vm_intf->vrf()->vrf_id(), mac); client->WaitForIdle(); //Verify that paths for unicast and evpn routes for VMI peer are updated //after traffic is seen. path = rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 2); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); path = evpn_rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 1); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); //cleanup AddAap("intf1", 1, Ip6Address(), zero_mac.ToString()); //Remove the remote route added. InetUnicastAgentRouteTable *rt_table = Agent::GetInstance()->vrf_table()->GetInet6UnicastRouteTable("vrf1"); rt_table->DeleteReq(peer_, "vrf1", ip, 128, new ControllerVmRoute(static_cast<BgpPeer *>(peer_))); client->WaitForIdle(); WAIT_FOR(1000, 1, (RouteFindV6("vrf1", ip, 128) == false)); EXPECT_FALSE(EvpnRouteGet("vrf1", mac, ip, 0)); } //Verify that dependent static route gets high preference, when traffic is seen //on interface native IP. (UT for path_preference module. Not an AAP UT) TEST_F(TestAap6, StateMachine_4) { Ip6Address ip = Ip6Address::from_string("fd10::2"); //Add a static route struct TestIp6Prefix static_route[] = { { Ip6Address::from_string("fd11::2"), 120} }; AddInterfaceRouteTableV6("static_route", 1, static_route, 1); AddLink("virtual-machine-interface", "intf1", "interface-route-table", "static_route"); client->WaitForIdle(); //Verify static IP route and its path preference attributes VmInterface *vm_intf = VmInterfaceGet(1); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", static_route[0].addr_, static_route[0].plen_); EXPECT_TRUE(rt != NULL); const AgentPath *path = rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); //Enqueue traffic on native IP Agent::GetInstance()->oper_db()->route_preference_module()-> EnqueueTrafficSeen(ip, 128, vm_intf->id(), vm_intf->vrf()->vrf_id(), vm_intf->vm_mac()); client->WaitForIdle(); //Verify that static IP route's path_preference attributes are updated on //seeing traffic on interface's native IP EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); //Cleanup DelLink("virtual-machine-interface", "intf1", "interface-route-table", "static_route"); client->WaitForIdle(); rt = RouteGetV6("vrf1", static_route[0].addr_, static_route[0].plen_); EXPECT_TRUE(rt == NULL); } //Upon transition of instance IP address from active-backup to active-active, //Verify that path preference becomes high (This does not have any AAP config) TEST_F(TestAap6, StateMachine_5) { Ip6Address ip = Ip6Address::from_string("fd10::2"); VmInterface *vm_intf = VmInterfaceGet(1); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", ip, 128); const AgentPath *path = rt->FindPath(vm_intf->peer()); //Verify path attributes for native-IP EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); AddActiveActiveInstanceIp("instance1", 1, "fd10::2"); client->WaitForIdle(); //After instance-ip is configured for "active-active" mode, verify that //path preference attributes are updated (ecmp = true, pref = HIGH, //wait_for_traffic=false) EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == true); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); //Enqueue traffic seen Agent::GetInstance()->oper_db()->route_preference_module()-> EnqueueTrafficSeen(ip, 128, vm_intf->id(), vm_intf->vrf()->vrf_id(), vm_intf->vm_mac()); client->WaitForIdle(); //Verify that there no changes in path attributes, because wait_for_traffic //is false. EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == true); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); } //Upon transition of instance IP address from active-backup to active-active, //verify that path preference of dependent static routes, becomes high TEST_F(TestAap6, StateMachine_6) { //Add a static route struct TestIp6Prefix static_route[] = { { Ip6Address::from_string("fd11::2"), 120} }; AddInterfaceRouteTableV6("static_route", 1, static_route, 1); AddLink("virtual-machine-interface", "intf1", "interface-route-table", "static_route"); client->WaitForIdle(); //Verify static IP route and its path preference attributes VmInterface *vm_intf = VmInterfaceGet(1); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", static_route[0].addr_, static_route[0].plen_); EXPECT_TRUE(rt != NULL); const AgentPath *path = rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); AddActiveActiveInstanceIp("instance1", 1, "fd10::2"); client->WaitForIdle(); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == true); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); AddInstanceIp("instance1", 1, "fd10::2"); client->WaitForIdle(); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); //Cleanup DelLink("virtual-machine-interface", "intf1", "interface-route-table", "static_route"); client->WaitForIdle(); rt = RouteGetV6("vrf1", static_route[0].addr_, static_route[0].plen_); EXPECT_TRUE(rt == NULL); } //Verify that static preference is populated TEST_F(TestAap6, StateMachine_10) { Ip6Address ip = Ip6Address::from_string("fd10::2"); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", ip, 128); const AgentPath *path = rt->GetActivePath(); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); EXPECT_TRUE(path->path_preference().static_preference() == false); AddStaticPreference("intf1", 1, 200); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); EXPECT_TRUE(path->path_preference().static_preference() == true); //Delete static interface property AddNode("virtual-machine-interface", "intf1", 1, ""); client->WaitForIdle(); EXPECT_TRUE(path->path_preference().static_preference() == false); } //Verify that preference value change is reflected with //static preference change TEST_F(TestAap6, StaticMachine_11) { AddStaticPreference("intf1", 1, 100); Ip6Address ip = Ip6Address::from_string("fd10::2"); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", ip, 128); const AgentPath *path = rt->GetActivePath(); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); EXPECT_TRUE(path->path_preference().static_preference() == true); AddStaticPreference("intf1", 1, 200); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); EXPECT_TRUE(path->path_preference().static_preference() == true); AddStaticPreference("intf1", 1, 100); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); //Delete static interface property AddNode("virtual-machine-interface", "intf1", 1, ""); client->WaitForIdle(); EXPECT_TRUE(path->path_preference().static_preference() == false); } //Verify that static preference is not populated //when preference value is set to 0 TEST_F(TestAap6, StateMachine_12) { AddStaticPreference("intf1", 1, 0); Ip6Address ip = Ip6Address::from_string("fd10::2"); EXPECT_TRUE(RouteFindV6("vrf1", ip, 128)); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", ip, 128); const AgentPath *path = rt->GetActivePath(); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::LOW); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == true); EXPECT_TRUE(path->path_preference().static_preference() == false); } //When traffic is seen on native IP ensure that preference is updated even for //AAP IP (when address mode is active-active) TEST_F(TestAap6, StateMachine_16) { //Add AAP-IP with active-active mode Ip6Address aap_ip = Ip6Address::from_string("fd10::10"); AddEcmpAap("intf1", 1, aap_ip); EXPECT_TRUE(RouteFindV6("vrf1", aap_ip, 128)); //Verify that ecmp is set to true on AAP IP route's path, when active-active //mode is configured. VmInterface *vm_intf = VmInterfaceGet(1); InetUnicastRouteEntry *rt = RouteGetV6("vrf1", aap_ip, 128); const AgentPath *path = rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == true); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); //Enqueue traffic seen for native IP Ip6Address ip = Ip6Address::from_string("fd10::2"); Agent::GetInstance()->oper_db()->route_preference_module()-> EnqueueTrafficSeen(ip, 128, vm_intf->id(), vm_intf->vrf()->vrf_id(), vm_intf->vm_mac()); client->WaitForIdle(); //Verify preference for AAP IP path is increased and wait_for_traffic is //set to false EXPECT_TRUE(path->path_preference().sequence() == 0); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == true); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); //Verify that preference and wait_for_traffic fields for native IP are also //updated rt = RouteGetV6("vrf1", ip, 128); path = rt->FindPath(vm_intf->peer()); EXPECT_TRUE(path->path_preference().sequence() == 1); EXPECT_TRUE(path->path_preference().preference() == PathPreference::HIGH); EXPECT_TRUE(path->path_preference().ecmp() == false); EXPECT_TRUE(path->path_preference().wait_for_traffic() == false); //cleanup AddAap("intf1", 1, Ip6Address(), zero_mac.ToString()); WAIT_FOR(1000, 1, (RouteFindV6("vrf1", aap_ip, 128) == false)); } int main(int argc, char *argv[]) { GETUSERARGS(); client = TestInit(init_file, ksync_init); int ret = RUN_ALL_TESTS(); TestShutdown(); return ret; }
[ "awaisalisabir@yahoo.com" ]
awaisalisabir@yahoo.com
6c1016bade29f3c8898bf9b6fc5475386170bf59
c088753861e41f309285436f7658a8e1f27e3e94
/AirfoilThickness/thin/case/system/fvSchemes
355629bd7cd855f155aef93a9ca22d9449370e7e
[]
no_license
RobinHC/upcoming
9d4b22bfaa8ad2fab2f624d99b63f943ec30ee23
bb5faf9f4953e1a72ac9d653fd8c49b5ff155b99
refs/heads/master
2021-06-01T19:31:51.600480
2016-06-10T23:11:18
2016-06-10T23:11:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,659
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 3.0.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; object fvSchemes; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ddtSchemes { // default Euler; // PISO default steadyState; // SIMPLE } gradSchemes { default Gauss linear; grad(p) Gauss linear; grad(U) Gauss linear; } divSchemes { default none; // // PISO // div(phi,U) Gauss upwind; // div(phi,k) Gauss upwind; // div(phi,omega) Gauss upwind; // // PISO // SIMPLE div(phi,U) bounded Gauss upwind; div(phi,k) bounded Gauss upwind; div(phi,omega) bounded Gauss upwind; // SIMPLE div((nuEff*dev2(T(grad(U))))) Gauss linear; } laplacianSchemes { default Gauss linear limited corrected 0.5; } interpolationSchemes { default linear; } snGradSchemes { default corrected; } wallDist { method meshWave; } // ************************************************************************* //
[ "rlee32@gatech.edu" ]
rlee32@gatech.edu
84bccd13782d43a8afaacb0b5656915767ae837c
c6e8b9c0a225a682dcfee6ba3df36bd189fb7b24
/Лабораторная№10(13)/Лабораторная№10(13)/Лабораторная№10(13).cpp
6937741019f1323d11b6fae0e0e7e9a8e840f4d2
[]
no_license
eliadra/Laba13
81f63395e8a40d0310d4d5a01b4afec6b5f7d87e
b8266135c7a0e8fe63f16f8dc730ace38a7991d4
refs/heads/master
2021-01-10T12:34:40.295321
2015-12-15T09:55:21
2015-12-15T09:55:21
48,034,177
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
13,953
cpp
// Лабораторная№10(13).cpp: определяет точку входа для приложения. //стр 209 #include "stdafx.h" #include "Лабораторная№10(13).h" #define MAX_LOADSTRING 100 // Глобальные переменные: HINSTANCE hInst; // текущий экземпляр TCHAR szTitle[MAX_LOADSTRING]; // Текст строки заголовка TCHAR szWindowClass[MAX_LOADSTRING]; // имя класса главного окна static int winCount = 0; HWND begin_hWnd; HWND mass_hWnd[7]; // Отправить объявления функций, включенных в этот модуль кода: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); //сохраняет обработку экземпляра и создает главное окно. LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); /*вывызвется оконная ф-я LRESULT-Знаковый результат обработки сообщения. Функция WindowProc - определяемая программой функция, которая обрабатывает сообщения, отправленные в окно. */ INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); //Функция About будет вызываться системой для обработки сообщений, посылаемых окну диалога. int APIENTRY _tWinMain (_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: разместите код здесь. MSG msg; //содержит информацию о сообщении из очереди сообщений потока. HACCEL hAccelTable; //Дескриптор таблицы ускорителей // Инициализация глобальных строк LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); /*загружает ресурс строки из исполняемого файла, копирует строку в буфер и добавляет в конец символ завершающего нуля.*/ LoadString(hInstance, IDC_MY1013, szWindowClass, MAX_LOADSTRING); /*Дескриптор экземпляра модуля, исполняемый файл которого содержит в себе ресурс строки. Указывает целочисленный идентификатор строки, которая будет загружена. Указатель на буфер, который примет строку. Определяет размер буфера */ MyRegisterClass(hInstance); //регистрация оконного класса // Выполнить инициализацию приложения: if (!InitInstance (hInstance, nCmdShow)) //осуществляет инициализацию приложения и формирует дескриптор приложения hInstance { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MY1013)); /*загружает заданную таблицу клавиш-ускорителей Дескриптор модуля, исполняемый файл которого содержит загружаемую таблицу клавиш-ускорителей. Указатель на символьную строку с нулем в конце, которая содержит имя загружаемой таблицы клавиш-ускорителей.*/ /*простейший цикл обработки сообщения*/ while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); //переводит сообщения виртуальных клавиш в символьные сообщения DispatchMessage(&msg); //используется, чтобы доставить сообщение, извлеченное функцией GetMessage } } return (int) msg.wParam; } /* ФУНКЦИЯ: MyRegisterClass() НАЗНАЧЕНИЕ: регистрирует класс окна. КОММЕНТАРИИ: Эта функция и ее использование необходимы только в случае, если нужно, чтобы данный код был совместим с системами Win32, не имеющими функции RegisterClassEx' которая была добавлена в Windows 95. Вызов этой функции важен для того, чтобы приложение получило "качественные" мелкие значки и установило связь с ними.*/ ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; //содержит информацию о классе окна wcex.cbSize = sizeof(WNDCLASSEX); //Задает стиль окна. wcex.style = CS_HREDRAW | CS_VREDRAW; /*CS_HREDRAW Перерисовывает все окно, если перемещение или регулировка размера изменяют ширину или высоту рабочей области.*/ wcex.lpfnWndProc = WndProc; //Определяет имя оконной процедуры. wcex.cbClsExtra = 0; //Дополнительные данные для класса. wcex.cbWndExtra = 0; wcex.hInstance = hInstance; /*Заголовок приложения, работающего с данным окном. Иконка для окна приложения.*/ wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MY1013));/*загружает указанный ресурс значка из исполняемого файла, связанного с экземпляром приложения. Дескриптор экземпляра модуля, содержащий исполняемый файл, значок которого будет загружен. Указатель на строку с завершающим нулем, cодержащую имя ресурса значка, который будет загружен. Макрос MAKEINTRESOURCE преобразует целочисленное значение в тип ресурса, совместимого с функциями управления ресурсом*/ wcex.hCursor = LoadCursor(NULL, IDC_ARROW); //Устанавливает тип курсора в окне приложения. wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); //Задет кисть для закраски окна. HBR-Дескриптор кисти wcex.lpszMenuName = MAKEINTRESOURCE(IDC_MY1013); //Задает меню для окна приложения. wcex.lpszClassName = szWindowClass; //Указатель на оконный класс. wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } /*ФУНКЦИЯ: InitInstance(HINSTANCE, int) НАЗНАЧЕНИЕ: сохраняет обработку экземпляра и создает главное окно. КОММЕНТАРИИ: В данной функции дескриптор экземпляра сохраняется в глобальной переменной, а также создается и выводится на экран главное окно программы.*/ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { //Дескриптор окна. hInst = hInstance; // Сохранить дескриптор экземпляра в глобальной переменной // создает перекрывающее, выскакивающее или дочернее окно. HWND hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); begin_hWnd = hWnd; if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow);//устанавливает состояние показа определяемого окна, дескриптор окна, состояние показа окна UpdateWindow(hWnd);//обновляет клиентскую область указанного окна, return TRUE; } /*ФУНКЦИЯ: WndProc(HWND, UINT, WPARAM, LPARAM) НАЗНАЧЕНИЕ: обрабатывает сообщения в главном окне. WM_COMMAND - обработка меню приложения WM_PAINT -Закрасить главное окно WM_DESTROY - ввести сообщение о выходе и вернуться. */ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps;//содержит информации для приложения HDC hdc;//Дескриптор контекста устройства switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Разобрать выбор в меню: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);//создает модальное диалоговое окно из ресурса шаблона блока диалога. break; /* Дескриптор модуля, исполняемый файл которого содержит шаблон диалогового окна. Определяет шаблон диалогового окна Дескриптор окна, которое владеет диалоговым окном. Указатель на процедуру диалогового окна */ case IDM_EXIT: if (IDOK == MessageBox(hWnd, _T("Хотите закрыть программу?"), _T("Закрыть"), MB_OKCANCEL | MB_ICONQUESTION | MB_DEFBUTTON2)) SendMessage(hWnd, WM_DESTROY, NULL, NULL); DestroyWindow(hWnd);// разрушает заданное окно, дескриптор для разрушения окна break; default: return DefWindowProc(hWnd, message, wParam, lParam);//обеспечивает обработку по умолчанию любого сообщения окна, которые приложение не обрабатывае } break; case WM_LBUTTONDOWN: SetWindowText(hWnd, _T ("Главное окно")); break; case WM_PAINT://Уведомляет окно о том, что тpебуется пеpеpисовать всю или часть его области пользователя. hdc = BeginPaint(hWnd, &ps); // TODO: добавьте любой код отрисовки... EndPaint(hWnd, &ps); break; case WM_RBUTTONDOWN: { //for (winCount = 0;winCount < 3;winCount++) { if (winCount >= 7) { MessageBox(hWnd, L"Нельзя создать более 7 окон", L"", MB_OKCANCEL | MB_ICONQUESTION); break; } WNDCLASS w; memset(&w, 0, sizeof(WNDCLASS)); w.lpfnWndProc = WndProc; w.hInstance = hInst; w.hbrBackground = (HBRUSH)(COLOR_WINDOW); w.lpszClassName = L"ChildWClass"; w.hCursor = LoadCursor(NULL, IDC_IBEAM); RegisterClass(&w); HWND child; child = CreateWindowEx(1, L"ChildWClass", (LPCTSTR)NULL, WS_OVERLAPPEDWINDOW | WS_SYSMENU | WS_OVERLAPPEDWINDOW | WS_CAPTION | WS_HSCROLL | WS_BORDER | WS_VISIBLE, winCount * 20 + 200, winCount * 20 + 200, 400, 500, hWnd, (HMENU)(int)(0), hInst, NULL); ++winCount; SetWindowText(child, _T("Дочернее окно")); ShowWindow(child, SW_NORMAL); // } } break; case WM_CLOSE: //спрашивает о выходе из программы if (hWnd == begin_hWnd) { if (IDOK == MessageBox(hWnd, _T("Хотите закрыть программу?"), _T("Закрыть"), MB_OKCANCEL | MB_ICONQUESTION | MB_DEFBUTTON2)) SendMessage(hWnd, WM_DESTROY, NULL, NULL); } else DestroyWindow(hWnd); winCount--; break; case WM_DESTROY: if (hWnd == begin_hWnd) PostQuitMessage(0); else break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Обработчик сообщений для окна "О программе". INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) /*Функция About будет вызываться системой для обработки сообщений, посылаемых окну диалога. HWND Windows-описатель окна диалога; UINT — код сообщения; WPARAM, LPARAM — два параметра, сопровождающих сообщение. Целый знаковый тип для точности указателя.*/ { UNREFERENCED_PARAMETER(lParam); //Помогает избежать предупреждений компилятора о наличии параметров, на которые нет ссылок (неиспользуемых параметров) switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam));/*уничтожает модальное диалоговое окно, Описатель диалогового окна, Значение, возвращаемое приложению из функции, создающей диалоговое окно*/ return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
[ "eliadra@yandex.ru" ]
eliadra@yandex.ru
dcfb0778057cb5e4cf738acc70e43ca9093cb674
c8cb0d4ed0c14e6698400f3ee4d48ccb0d9e4c61
/openglBased/passenger.h
895ce6145d624633cef0d7c475d2376bd3a5ce1b
[]
no_license
sam8401/OORL-MSc-Thesis
f803d374026e6d48ed4d5d60b0fd912176630df2
c72948840fda1108cfdafac78931ef4a748bd92c
refs/heads/master
2021-01-12T08:42:04.967330
2016-12-16T16:23:06
2016-12-16T16:23:06
76,667,793
0
0
null
null
null
null
UTF-8
C++
false
false
173
h
#include "core.h" class passenger { public: // make these private later int index ; // -1 if the passenger is in taxi bool in_taxi ; passenger(int ); } ;
[ "ece.suman@gmail.com" ]
ece.suman@gmail.com
ffdc4edb065596dbfd0fc32cc365368a6f2ff895
fdffd3089821fab81479bffad75a7bc290155046
/2021-04-09/7.cpp
7c6b60dcaae2dc691e7341c5b3964d04f7eb8fed
[]
no_license
TXWSLYF/learn-c-primer
3e5cbbd51c34003d998677ec3efda381c0329534
3f5338f693a259a7c6e469534ee614d31dcb24f9
refs/heads/main
2023-04-20T07:12:06.162453
2021-05-12T08:28:01
2021-05-12T08:28:01
355,917,908
0
0
null
null
null
null
UTF-8
C++
false
false
283
cpp
#include <iostream> int main() { std::string str("some string"); for (decltype(str.size()) index = 0; index != str.size() && !std::isspace(str[index]); ++index) { str[index] = std::toupper(str[index]); } std::cout << str << std::endl; return 0; }
[ "1060319328@qq.com" ]
1060319328@qq.com
c17f7492e0f07ea748fd6296a74a1d2462914584
67fc9e51437e351579fe9d2d349040c25936472a
/wrappers/8.1.1/vtkImageAppendWrap.cc
cdfbf50ffb65c320b01aec503332ac3af02796e6
[]
permissive
axkibe/node-vtk
51b3207c7a7d3b59a4dd46a51e754984c3302dec
900ad7b5500f672519da5aa24c99aa5a96466ef3
refs/heads/master
2023-03-05T07:45:45.577220
2020-03-30T09:31:07
2020-03-30T09:31:07
48,490,707
6
0
BSD-3-Clause
2022-12-07T20:41:45
2015-12-23T12:58:43
C++
UTF-8
C++
false
false
11,995
cc
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkThreadedImageAlgorithmWrap.h" #include "vtkImageAppendWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkAlgorithmOutputWrap.h" #include "vtkDataObjectWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkImageAppendWrap::ptpl; VtkImageAppendWrap::VtkImageAppendWrap() { } VtkImageAppendWrap::VtkImageAppendWrap(vtkSmartPointer<vtkImageAppend> _native) { native = _native; } VtkImageAppendWrap::~VtkImageAppendWrap() { } void VtkImageAppendWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkImageAppend").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("ImageAppend").ToLocalChecked(), ConstructorGetter); } void VtkImageAppendWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkImageAppendWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkThreadedImageAlgorithmWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkThreadedImageAlgorithmWrap::ptpl)); tpl->SetClassName(Nan::New("VtkImageAppendWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetAppendAxis", GetAppendAxis); Nan::SetPrototypeMethod(tpl, "getAppendAxis", GetAppendAxis); Nan::SetPrototypeMethod(tpl, "GetInput", GetInput); Nan::SetPrototypeMethod(tpl, "getInput", GetInput); Nan::SetPrototypeMethod(tpl, "GetNumberOfInputs", GetNumberOfInputs); Nan::SetPrototypeMethod(tpl, "getNumberOfInputs", GetNumberOfInputs); Nan::SetPrototypeMethod(tpl, "GetPreserveExtents", GetPreserveExtents); Nan::SetPrototypeMethod(tpl, "getPreserveExtents", GetPreserveExtents); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "PreserveExtentsOff", PreserveExtentsOff); Nan::SetPrototypeMethod(tpl, "preserveExtentsOff", PreserveExtentsOff); Nan::SetPrototypeMethod(tpl, "PreserveExtentsOn", PreserveExtentsOn); Nan::SetPrototypeMethod(tpl, "preserveExtentsOn", PreserveExtentsOn); Nan::SetPrototypeMethod(tpl, "ReplaceNthInputConnection", ReplaceNthInputConnection); Nan::SetPrototypeMethod(tpl, "replaceNthInputConnection", ReplaceNthInputConnection); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetAppendAxis", SetAppendAxis); Nan::SetPrototypeMethod(tpl, "setAppendAxis", SetAppendAxis); Nan::SetPrototypeMethod(tpl, "SetInputData", SetInputData); Nan::SetPrototypeMethod(tpl, "setInputData", SetInputData); Nan::SetPrototypeMethod(tpl, "SetPreserveExtents", SetPreserveExtents); Nan::SetPrototypeMethod(tpl, "setPreserveExtents", SetPreserveExtents); #ifdef VTK_NODE_PLUS_VTKIMAGEAPPENDWRAP_INITPTPL VTK_NODE_PLUS_VTKIMAGEAPPENDWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkImageAppendWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkImageAppend> native = vtkSmartPointer<vtkImageAppend>::New(); VtkImageAppendWrap* obj = new VtkImageAppendWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkImageAppendWrap::GetAppendAxis(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetAppendAxis(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageAppendWrap::GetInput(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { vtkDataObject * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetInput( info[0]->Int32Value() ); VtkDataObjectWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDataObjectWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDataObjectWrap *w = new VtkDataObjectWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } vtkDataObject * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetInput(); VtkDataObjectWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDataObjectWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDataObjectWrap *w = new VtkDataObjectWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkImageAppendWrap::GetNumberOfInputs(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfInputs(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageAppendWrap::GetPreserveExtents(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetPreserveExtents(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageAppendWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); vtkImageAppend * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkImageAppendWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageAppendWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageAppendWrap *w = new VtkImageAppendWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkImageAppendWrap::PreserveExtentsOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->PreserveExtentsOff(); } void VtkImageAppendWrap::PreserveExtentsOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->PreserveExtentsOn(); } void VtkImageAppendWrap::ReplaceNthInputConnection(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkAlgorithmOutputWrap::ptpl))->HasInstance(info[1])) { VtkAlgorithmOutputWrap *a1 = ObjectWrap::Unwrap<VtkAlgorithmOutputWrap>(info[1]->ToObject()); if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->ReplaceNthInputConnection( info[0]->Int32Value(), (vtkAlgorithmOutput *) a1->native.GetPointer() ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkImageAppendWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkImageAppend * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkImageAppendWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageAppendWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageAppendWrap *w = new VtkImageAppendWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageAppendWrap::SetAppendAxis(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetAppendAxis( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageAppendWrap::SetInputData(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkDataObjectWrap::ptpl))->HasInstance(info[0])) { VtkDataObjectWrap *a0 = ObjectWrap::Unwrap<VtkDataObjectWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetInputData( (vtkDataObject *) a0->native.GetPointer() ); return; } else if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkDataObjectWrap::ptpl))->HasInstance(info[1])) { VtkDataObjectWrap *a1 = ObjectWrap::Unwrap<VtkDataObjectWrap>(info[1]->ToObject()); if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SetInputData( info[0]->Int32Value(), (vtkDataObject *) a1->native.GetPointer() ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkImageAppendWrap::SetPreserveExtents(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageAppendWrap *wrapper = ObjectWrap::Unwrap<VtkImageAppendWrap>(info.Holder()); vtkImageAppend *native = (vtkImageAppend *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPreserveExtents( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); }
[ "axkibe@gmail.com" ]
axkibe@gmail.com
db4e845d154da87d9ba114e5a50603090526a368
ad4db370c042b371132c21f6f9795613c50ee270
/Unary.cpp
1c606ea404b6b3ce1bdbbc3899b04e3b4cb65b63
[]
no_license
Vedant488/E-Lab-Object-Oriented-Programming
b284a836f5700c3d5cec978aa7c7a7406642c387
b1a3b43b10d6da8659872434ae062f3fe0d091de
refs/heads/master
2020-07-02T04:37:17.894912
2019-08-03T18:46:00
2019-08-03T18:46:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
456
cpp
#include<iostream> using namespace std; class data { public: double x, y; double a,b; void setdata() { cin>>x>>y; cin>>a>>b; } void display1() { cout<<x<<" "<<y; } void display2() { cout<<a<<" "<<b; } data operator*() { x=-x; y=-y; a=-a; b=-b; } }; int main() { data ob1; ob1.setdata(); *ob1; ob1.display1(); cout<<"\n"; ob1.display2(); return 0; }
[ "chilloutwithanas@gmail.com" ]
chilloutwithanas@gmail.com
9d02d98eb95146529d22c8b3b8c7240e6138150c
14aa16910ddaad71dc309064d1761d1f0d200542
/src/util/error.h
d93309551b98c5a222802cc8ef124bd2a4f36ca5
[ "MIT" ]
permissive
GhostsOfHiroshima/bitcoin
7028832120b04b1ba504d02c0f9635637f32c712
7ba7a6e82ff8bf42187f148feff95c15f1b5afa6
refs/heads/master
2020-06-06T07:01:51.153556
2019-06-30T19:40:07
2019-06-30T19:40:07
192,669,933
1
1
MIT
2019-06-30T19:40:08
2019-06-19T06:12:40
C++
UTF-8
C++
false
false
1,134
h
// Copyright (c) 2010-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTIL_ERROR_H #define BITCOIN_UTIL_ERROR_H /** * util/error.h is a common place for definitions of simple error types and * string functions. Types and functions defined here should not require any * outside dependencies. * * Error types defined here can be used in different parts of the bitcoin * codebase, to avoid the need to write boilerplate code catching and * translating errors passed across wallet/node/rpc/gui code boundaries. */ #include <string> enum class TransactionError { OK, //!< No error MISSING_INPUTS, ALREADY_IN_CHAIN, P2P_DISABLED, MEMPOOL_REJECTED, MEMPOOL_ERROR, INVALID_PSBT, PSBT_MISMATCH, SIGHASH_MISMATCH, }; std::string TransactionErrorString(const TransactionError error); std::string AmountHighWarn(const std::string& optname); std::string AmountErrMsg(const char* const optname, const std::string& strValue); #endif // BITCOIN_UTIL_ERROR_H
[ "john@johnnewbery.com" ]
john@johnnewbery.com
5295694238f467c1df195b29302e2d68bb41b345
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_838_collectd-5.6.3.cpp
76d3923d8fb7dbce7312fadd2b683ff1657e1f32
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
727
cpp
static int bind_config_add_view_zone(cb_view_t *view, /* {{{ */ oconfig_item_t *ci) { char **tmp; if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) { WARNING("bind plugin: The `Zone' option needs " "exactly one string argument."); return (-1); } tmp = realloc(view->zones, sizeof(char *) * (view->zones_num + 1)); if (tmp == NULL) { ERROR("bind plugin: realloc failed."); return (-1); } view->zones = tmp; view->zones[view->zones_num] = strdup(ci->values[0].value.string); if (view->zones[view->zones_num] == NULL) { ERROR("bind plugin: strdup failed."); return (-1); } view->zones_num++; return (0); }
[ "993273596@qq.com" ]
993273596@qq.com
4180afcf5341548f83a58d1c52494403de14d9e6
4c823916d6e1b5e90a23e9c4f3ef76b1e33a70be
/OS/fatmat.cpp
2ddaa84d00ab5264d4fdc1c19cecc16a1e851612
[]
no_license
iofish/FishOS
9af18e75136e4c248af0ebccde56e74b6761c394
dda857ab0dd8ff44ef9b5d2b4f14880a9c90b10f
refs/heads/master
2021-05-16T02:38:40.877715
2016-11-03T01:45:18
2016-11-03T01:45:18
72,648,328
1
2
null
null
null
null
UTF-8
C++
false
false
9,436
cpp
//============================================================================ // Name : fatmat.cpp // Author : // Version : // Copyright : Your copyright notice // Description : fatmat in C, Ansi-style //============================================================================ #include <stdio.h> #include <stdlib.h> #include <fstream> #include <iostream> using namespace std; int Start_Sector = 2048; int Bytes_Sector = 512; int Hello_Sector = 5000; // 打印hello world的elf数据数据函数 int Hello2_Sector = 5500; int Hello3_Sector = 6000; int Hello4_Sector = 6500; // 打印hello world的elf数据数据函数 int Hello5_Sector = 7000; int Hello6_Sector = 7500; int Hello7_Sector = 8000; // 打印hello world的elf数据数据函数 int Hello8_Sector = 8500; int Hello9_Sector = 9000; int main(void) { const char * imgFileName = "fishos.img"; const char * fat32Bin = "fat32.bin"; const char * bootFile = "boot.bin"; const char * helloBin = "elf_file/hello.bin"; //hello world --> 5000 const char * hello2Bin = "elf_file/hello2.bin"; //hello , os kernel --> 5500 const char * hello3Bin = "elf_file/hello3.bin"; //hello ,kernel --> 6000 const char * hello4Bin = "elf_file/hello4.bin"; //hello world --> 6500 const char * hello5Bin = "elf_file/hello5.bin"; //hello , os kernel --> 7000 const char * hello6Bin = "elf_file/hello6.bin"; //hello ,kernel --> 7500 const char * hello7Bin = "elf_file/hello7.bin"; //hello world --> 8000 const char * hello8Bin = "elf_file/hello8.bin"; //hello , os kernel --> 8500 const char * hello9Bin = "elf_file/hello9.bin"; //hello ,kernel --> 9000 char tmp[5*Bytes_Sector]; char buffer[Bytes_Sector]; char hello_tmp[40*Bytes_Sector]; char hello2_tmp[15 * Bytes_Sector]; char hello3_tmp[15 * Bytes_Sector]; char hello4_tmp[15 * Bytes_Sector]; char hello5_tmp[15 * Bytes_Sector]; char hello6_tmp[15 * Bytes_Sector]; char hello7_tmp[15 * Bytes_Sector]; char hello8_tmp[15 * Bytes_Sector]; char hello9_tmp[15 * Bytes_Sector]; //char buffer[Bytes_Sector]; FILE *imgFile, *binFile, *bootBinFile, *helloFile, *hello2File, *hello3File, *hello4File, *hello5File, *hello6File, *hello7File, *hello8File, *hello9File; imgFile = fopen(imgFileName,"rb+"); binFile = fopen(fat32Bin,"rb"); bootBinFile = fopen(bootFile,"rb"); helloFile = fopen(helloBin, "rb"); hello2File = fopen(hello2Bin, "rb"); hello3File = fopen(hello3Bin, "rb"); hello4File = fopen(hello4Bin, "rb"); hello5File = fopen(hello5Bin, "rb"); hello6File = fopen(hello6Bin, "rb"); hello7File = fopen(hello7Bin, "rb"); hello8File = fopen(hello8Bin, "rb"); hello9File = fopen(hello9Bin, "rb"); if(!imgFile) { cout<<"open image file failed!"<<endl; } if(!binFile) { cout<<"open bin file failed!"<<endl; } if(!bootBinFile) { cout<<"open boot file failed!"<<endl; } if(!helloFile) { cout<<"open hello bin file failed!"<<endl; } if(!hello2File) { cout<<"open hello2 bin file failed!"<<endl; } if(!hello6File) { cout<<"open hello6 bin file failed!"<<endl; } cout<<"read "<<fat32Bin<<" file..."<<endl; fseek(binFile,0,0); fseek(bootBinFile,0,0); fseek(helloFile, 0, 0); fseek(hello2File, 0, 0); fseek(hello3File, 0, 0); fseek(hello4File, 0, 0); fseek(hello5File, 0, 0); fseek(hello6File, 0, 0); fseek(hello7File, 0, 0); fseek(hello8File, 0, 0); fseek(hello9File, 0, 0); if(!fread(tmp, 1, 5*Bytes_Sector, binFile)) { if(feof(binFile)) cout<<"End of file!"<<endl; else cout<<"Read error!"<<endl; } if(!fread(buffer, 1, Bytes_Sector, bootBinFile)) { if(feof(bootBinFile)) cout<<"End of file!"<<endl; else cout<<"Read error!"<<endl; } if(!fread(hello_tmp, 1, 40*Bytes_Sector, helloFile)) { if(feof(helloFile)) cout<<"End of file!"<<endl; else cout<<"Read error!"<<endl; } if(!fread(hello2_tmp, 1, 15*Bytes_Sector, hello2File)) { if(feof(hello2File)) cout<<"End of file!"<<endl; else cout<<"Read hello2.bin error!"<<endl; } if(!fread(hello3_tmp, 1, 15*Bytes_Sector, hello3File)) { if(feof(hello3File)) cout<<"End of file!"<<endl; else cout<<"Read hello3.bin error!"<<endl; } if(!fread(hello4_tmp, 1, 15*Bytes_Sector, hello4File)) { if(feof(hello4File)) cout<<"End of file!"<<endl; else cout<<"Read error!"<<endl; } if(!fread(hello5_tmp, 1, 15*Bytes_Sector, hello5File)) { if(feof(hello5File)) cout<<"End of file!"<<endl; else cout<<"Read hello5.bin error!"<<endl; } if(!fread(hello6_tmp, 1, 15*Bytes_Sector, hello6File)) { if(feof(hello6File)) cout<<"End of file!"<<endl; else cout<<"Read hello6.bin error!"<<endl; } if(!fread(hello7_tmp, 1, 40*Bytes_Sector, hello7File)) { if(feof(hello7File)) cout<<"End of file!"<<endl; else cout<<"Read error!"<<endl; } if(!fread(hello8_tmp, 1, 15*Bytes_Sector, hello8File)) { if(feof(hello8File)) cout<<"End of file!"<<endl; else cout<<"Read hello8.bin error!"<<endl; } if(!fread(hello9_tmp, 1, 15*Bytes_Sector, hello9File)) { if(feof(hello3File)) cout<<"End of file!"<<endl; else cout<<"Read hello9.bin error!"<<endl; } //镜像文件中写入boot.bin fseek(imgFile,0,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(buffer, 1, Bytes_Sector, imgFile)) { cout<<"write boot file failed!"<<endl; } cout<<"write boot file successed!"<<endl; //镜像文件中写入fat32.bin -> loader.bin fseek(imgFile,Start_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(tmp, 1, 5*Bytes_Sector, imgFile)) { cout<<"write fat32.bin file failed!"<<endl; } cout<<"write fat32.bin file successed!"<<endl; //镜像文件中写入hello.bin fseek(imgFile,Hello_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello.bin file failed!"<<endl; } cout<<"write hello.bin file successed!"<<endl; //镜像文件中写入hello2.bin fseek(imgFile,Hello2_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello2_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello2.bin file failed!"<<endl; } cout<<"write hello2.bin file successed!"<<endl; //镜像文件中写入hello3.bin fseek(imgFile,Hello3_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello3_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello3.bin file failed!"<<endl; } cout<<"write hello3.bin file successed!"<<endl; //镜像文件中写入hello4.bin fseek(imgFile,Hello4_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello4_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello.bin file failed!"<<endl; } cout<<"write hello4.bin file successed!"<<endl; //镜像文件中写入hello5.bin fseek(imgFile,Hello5_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello5_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello5.bin file failed!"<<endl; } cout<<"write hello5.bin file successed!"<<endl; //镜像文件中写入hello3.bin fseek(imgFile,Hello6_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello6_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello6.bin file failed!"<<endl; } cout<<"write hello6.bin file successed!"<<endl; //镜像文件中写入hello7.bin fseek(imgFile,Hello7_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello7_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello7.bin file failed!"<<endl; } cout<<"write hello7.bin file successed!"<<endl; //镜像文件中写入hello8.bin fseek(imgFile,Hello8_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello8_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello8.bin file failed!"<<endl; } cout<<"write hello8.bin file successed!"<<endl; //镜像文件中写入hello9.bin fseek(imgFile,Hello9_Sector*Bytes_Sector,0); cout<<"current location is: "<<ftell(imgFile)<<endl; if(!fwrite(hello9_tmp, 1, 15*Bytes_Sector, imgFile)) { cout<<"write hello9.bin file failed!"<<endl; } cout<<"write hello9.bin file successed!"<<endl; fclose(imgFile); fclose(bootBinFile); fclose(binFile); fclose(helloFile); fclose(hello2File); fclose(hello3File); fclose(hello4File); fclose(hello5File); fclose(hello6File); fclose(hello7File); fclose(hello8File); fclose(hello9File); return EXIT_SUCCESS; }
[ "wq19911110@gmail.com" ]
wq19911110@gmail.com
f1730dbb8d2e943eb695cb18cdf0c78ae2466566
5cbb6f03a7ee11223095d641329e53e5f2fd676f
/src/clustering/community_detection_cluster.h
bd0c512fb6c9bf136588b0bd88f0e76db682df19
[]
no_license
aabin/DAGSfM
300e5caf92d74b80b6579a1dbb917ac4304ef25c
158646b9b554c5c7a0abf37016f243d37b987078
refs/heads/master
2022-11-08T07:12:26.793358
2020-06-24T09:14:38
2020-06-24T09:14:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
439
h
#ifndef SRC_CLUSTERING_COMMUNITY_DETECTION_CLUSTER_H_ #define SRC_CLUSTERING_COMMUNITY_DETECTION_CLUSTER_H_ #include "clustering/cluster.h" namespace DAGSfM { class CommunityDetectionCluster : public Cluster { public: virtual std::unordered_map<int, int> ComputeCluster( const std::vector<std::pair<int, int>>& edges, const std::vector<int>& weights, const int num_partitions) override; }; } // namespace DAGSfM #endif
[ "1701213988@pku.edu.cn" ]
1701213988@pku.edu.cn
765a573994e01cd9f77dccb1d441ede7d9310101
71387741a6519e66ac81c2d7f233f9b58ca94231
/tests/arduino/ros_lib/ros_lib/rospy_tutorials/BadTwoInts.h
24a449fd800533ad4ab06395a5bf3d49c69b7e7c
[ "BSD-3-Clause" ]
permissive
GAVLab/ros-hab-dcs
98aa81e34d6381533a2669f0abe04704cd1ad4cd
ad859f06aa1f6fd43ade65ccad13f3519c42da79
refs/heads/main
2023-04-17T05:29:14.703000
2021-04-25T15:59:49
2021-04-25T15:59:49
313,475,597
1
0
BSD-3-Clause
2021-04-25T15:37:07
2020-11-17T01:40:43
Makefile
UTF-8
C++
false
false
4,593
h
#ifndef _ROS_SERVICE_BadTwoInts_h #define _ROS_SERVICE_BadTwoInts_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace rospy_tutorials { static const char BADTWOINTS[] = "rospy_tutorials/BadTwoInts"; class BadTwoIntsRequest : public ros::Msg { public: typedef int64_t _a_type; _a_type a; typedef int32_t _b_type; _b_type b; BadTwoIntsRequest(): a(0), b(0) { } virtual int serialize(unsigned char *outbuffer) const override { int offset = 0; union { int64_t real; uint64_t base; } u_a; u_a.real = this->a; *(outbuffer + offset + 0) = (u_a.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_a.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_a.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_a.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_a.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_a.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_a.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_a.base >> (8 * 7)) & 0xFF; offset += sizeof(this->a); union { int32_t real; uint32_t base; } u_b; u_b.real = this->b; *(outbuffer + offset + 0) = (u_b.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_b.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_b.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_b.base >> (8 * 3)) & 0xFF; offset += sizeof(this->b); return offset; } virtual int deserialize(unsigned char *inbuffer) override { int offset = 0; union { int64_t real; uint64_t base; } u_a; u_a.base = 0; u_a.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_a.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_a.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_a.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_a.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_a.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_a.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_a.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->a = u_a.real; offset += sizeof(this->a); union { int32_t real; uint32_t base; } u_b; u_b.base = 0; u_b.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_b.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_b.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_b.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->b = u_b.real; offset += sizeof(this->b); return offset; } virtual const char * getType() override { return BADTWOINTS; }; virtual const char * getMD5() override { return "29bb5c7dea8bf822f53e94b0ee5a3a56"; }; }; class BadTwoIntsResponse : public ros::Msg { public: typedef int32_t _sum_type; _sum_type sum; BadTwoIntsResponse(): sum(0) { } virtual int serialize(unsigned char *outbuffer) const override { int offset = 0; union { int32_t real; uint32_t base; } u_sum; u_sum.real = this->sum; *(outbuffer + offset + 0) = (u_sum.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_sum.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_sum.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_sum.base >> (8 * 3)) & 0xFF; offset += sizeof(this->sum); return offset; } virtual int deserialize(unsigned char *inbuffer) override { int offset = 0; union { int32_t real; uint32_t base; } u_sum; u_sum.base = 0; u_sum.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_sum.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_sum.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_sum.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->sum = u_sum.real; offset += sizeof(this->sum); return offset; } virtual const char * getType() override { return BADTWOINTS; }; virtual const char * getMD5() override { return "0ba699c25c9418c0366f3595c0c8e8ec"; }; }; class BadTwoInts { public: typedef BadTwoIntsRequest Request; typedef BadTwoIntsResponse Response; }; } #endif
[ "mattcastle38@gmail.com" ]
mattcastle38@gmail.com
069dc603a030cb979cd404b5f3d9512c672c2940
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Database/CoraCool/CoraCool/CoraCoolFolder.h
f54fe9d3697b66c72e3e28783c1491a17647b887
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
7,665
h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef CORACOOL_CORACOOLFOLDER_H #define CORACOOL_CORACOOLFOLDER_H // CoraCoolFolder.h - interface to a COOL folder with data stored in // a separate CORAL payload table // Richard Hawkings, started 10/2006 #include <vector> #include <string> #include "CoralBase/MessageStream.h" #include "CoralBase/AttributeList.h" #include "CoralBase/Attribute.h" #include "CoolKernel/ValidityKey.h" #include "CoolKernel/ChannelSelection.h" #include "CoolKernel/RecordSpecification.h" #include "CoolKernel/IField.h" #include "CoraCool/CoraCoolTypes.h" class CoraCoolSequence; namespace coral { class ISessionProxy; class ITable; class ITableDescription; class IColumn; class IQuery; class IBulkOperation; } class CoraCoolFolder { // allow the object iterator to access internals friend class CoraCoolObjectIter; public: // iterators for storing objects typedef std::vector<coral::AttributeList>::const_iterator const_iterator; // constructor - do not use this directly, use CoraCoolDatabase::getFolder CoraCoolFolder(const std::string& coolfolder, coral::ISessionProxy* proxy, cool::IDatabasePtr cooldb, CoraCoolDatabase* coradb, coral::MessageStream& log); // destructor ~CoraCoolFolder(); // properties of the folder std::string coralTableName() const; const std::string& coralFKey() const; const std::string& coralPKey() const; const cool::IRecordSpecification& fkSpecification() const; const cool::RecordSpecification payloadSpecification() const; coral::AttributeList emptyAttrList() const; // allow access to the underlying COOL folder cool::IFolderPtr coolFolder(); // storing data - all these can throw CoraCool and Cool exceptions // store a vector of coral::AtributeLists (identified by begin/end iterators) // and store the reference in COOL, with IOV (since/until), channel and tag // the primary and foreign key values of the AttributeLists will be ignored // as the keys will be allocated internally by the API // return the value of the FK in case it is required later int storeObject(const cool::ValidityKey& since, const cool::ValidityKey until, const_iterator begin, const_iterator end, const cool::ChannelId& channelId=0, const std::string tagName="", const bool userTagOnly=false); // setup storage buffer for bulk insertion via repeated storeObject calls void setupStorageBuffer(); // flush the storage buffer (execute bulk insertion of objects) // unlike in COOL, flush deactivates the buffer - use setupStorageBuffer // again after flush if you want to carry on void flushStorageBuffer(); // add a reference in COOL to an existing stored payload object identified // by its foreign key (as an Attribute - normally extracted from the // AttributeList), specifying the COOL IOV, channel and tag void referenceObject(const cool::ValidityKey& since, const cool::ValidityKey& until, const coral::Attribute& fkey, const cool::ChannelId& channelId=0, const std::string tagName="", const bool userTagOnly=false); // add a reference to COOL to an existing stored payload object // same as above, but taking the FK as a plain int void referenceObject(const cool::ValidityKey& since, const cool::ValidityKey& until, const int ifkey, const cool::ChannelId& channelId=0, const std::string tagName="", const bool userTagOnly=false); // add more payload AttributeLists to the CORAL payload table // the foreign key column is used to determine which existing COOL entries // will reference this data // the primary key column will be ignored and values allocated by the API void addPayload(const_iterator begin, const_iterator end); // accessing data - all these can throw CoraCool and Cool exceptions // find the one object valid at a given time/channel and tag CoraCoolObjectPtr findObject(const cool::ValidityKey& pointInTime, const cool::ChannelId& channelId=0, const std::string tagName=""); // return an iterator to a set of objects identified by a point in time // and a channel specification (and optionally a tag) CoraCoolObjectIterPtr browseObjects( const cool::ValidityKey& pointInTime, const cool::ChannelSelection& channels, const std::string& tagName=""); // return an interator to a set of objects identified by a range in // time and a channel specification (and optionally a tag) CoraCoolObjectIterPtr browseObjects( const cool::ValidityKey& since=cool::ValidityKeyMin, const cool::ValidityKey& until=cool::ValidityKeyMax, const cool::ChannelSelection& channels=cool::ChannelSelection(0), const std::string& tagName=""); // setup folder preFetch status (passed on to COOL) void setPrefetchAll(const bool prefetchAll); // Helper functions to set and return a FK/PK Attribute as an int // First oner eturns False if it fails // keys can be int, unsigned int, long long / unsigned long long bool setAttrKey(coral::Attribute& attr,const int keyval); bool setFieldKey(cool::IField& attr,const int keyval); bool setFieldAttr(cool::IField& attr,const coral::Attribute& keyval); int getAttrKey(const coral::Attribute& attr); private: // accessors for friend class CoraCoolObjectIter coral::ISessionProxy* proxy() const; coral::ITable* table() const; void setOutputSpec(coral::IQuery* query); bool decodeAttrSpec(); cool::StorageType::TypeId nameToCoolType(const std::string& coolName) const; void bulkInsert(const_iterator begin,const_iterator end, const int fkey,bool updatefk); std::string m_foldername; // name of the COOL folder std::string m_dbname; // name of the COOL database instance coral::ISessionProxy* m_proxy; // database session proxy cool::IDatabasePtr m_cooldb; // pointer to the COOL database CoraCoolDatabase* m_coradb; // pointer to the parent CoraCool database coral::MessageStream& m_log; std::string m_tablename; // name of the CORAL table for the payload std::string m_keycolcoral; // name of the foreign key in CORAL table std::string m_keycolcool; // name of the foreign key in COOL table std::string m_pkeycolcoral; // name of the primary key in CORAL table bool m_pkey; // table has separate primary key (not reusing foreign key) cool::IFolderPtr m_coolfolder; // pointer to the COOL folder coral::ITable* m_table; // pointer to the payload table const coral::ITableDescription* m_tabledesc; // and its description // vector of pairs of column name/type typedef std::vector<std::pair<std::string,std::string> > AttrVec; typedef AttrVec::const_iterator AttrItr; AttrVec m_attrvec; // variables for the bulk operations bool m_bulkactive; coral::AttributeList* m_payloadbuf; coral::IBulkOperation* m_bulki; CoraCoolSequence* m_seqpk; CoraCoolSequence* m_seqfk; int m_nextpk; int m_usedpk; int m_nextfk; int m_usedfk; }; inline std::string CoraCoolFolder::coralTableName() const { return m_tablename.substr(m_dbname.size()+1); } inline const std::string& CoraCoolFolder::coralFKey() const { return m_keycolcoral; } inline const std::string& CoraCoolFolder::coralPKey() const { return m_pkeycolcoral; } inline cool::IFolderPtr CoraCoolFolder::coolFolder() { return m_coolfolder; } inline coral::ISessionProxy* CoraCoolFolder::proxy() const {return m_proxy; } // inline coral::ITable* CoraCoolFolder::table() const { return m_table; } #endif // CORACOOL_CORACOOLFOLDER_H
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
f324de01864fdbe5cb688b262a9e56f12e214661
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir22441/dir22442/dir22443/dir22444/dir22869/dir23467/file23564.cpp
9601341b610662fd288c0325fc4dac0ff5d85150
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file23564 #error "macro file23564 must be defined" #endif static const char* file23564String = "file23564";
[ "tgeng@google.com" ]
tgeng@google.com
ae5c98fc4c9d6339516c0be34e383cf620aeb252
192e6c1f82048e319f40fdeec1c4ef1c971ecdfd
/QLRead.ino
f687ab1a29de0d1dbf48a61f3051f013a1ee559d
[]
no_license
dandelion-labs/QLAN
fc323036896e3dcd1fcd9ae3314cf63e10741d89
5d84ad7a362e945154d5b6e59cb329933b03a853
refs/heads/master
2020-05-19T05:43:40.557040
2019-05-16T10:53:22
2019-05-16T10:53:22
184,855,397
3
2
null
null
null
null
UTF-8
C++
false
false
3,493
ino
/* * Standard QL Network Read routines * * Read Data from QL * */ byte receiveFile(String fname){ byte error=0; short blockcount=0; //Clear input buffer for(byte count=0;count<255;count++) Buf[count]=0; //Main Read loop do{ error=readBlock(); //Save to SD card if((error==E_OK) || (error==E_EOF)){//Data is for this station if((Header[2]+Header[3])==0){//First block clientNETID=Header[1]; if((Header[4]==1) && (Buf[0]=='C')){//Block is last block and first byte is 'C' - might be a command if(checkCommand()) return E_CMD; //Was a command - exit routine. } //Open file if no error SET_LED_PIN; char filename[37]; fname.toCharArray(filename,37); SD.remove(filename); FD.handle=SD.open(fname,O_READ | O_WRITE | O_CREAT); if(!FD.handle){ Serial.println("File error"); return E_FNF; } } //Serial.print("Block: "); //Serial.println(blockcount); //blockcount++; FD.handle.write(Buf,Header[5]); } } while ((error==E_OK) || (error==E_CHK)); if(error==E_EOF) error=E_OK; //Report EOF as Success //Close File FD.handle.close(); //Read_Retries=5; CLR_LED_PIN; return error; } byte readBlock(){ byte chksum=0; short retries=0; while(waitScout()){ retries++; if(retries==Read_Retries) return E_TO;//Timeout } //Serial.print("Retries: "); //Serial.println(retries,DEC); //Read header for(byte count=0;count<7;count++){ Header[count]=readByte(); chksum+=Header[count]; } //Header Checksum Header[7]=readByte(); if(chksum!=Header[7]) return E_CHK; //Checksum error if(Header[0]!=NETID) return E_NTS; //Block not for this station. Also ignore broadcast (NETID 0) blocks sendACK(); //Read data chksum=0; for(byte count=0;count<Header[5];count++){ Buf[count]=readByte(); chksum+=Buf[count]; } //Data Checksum if(chksum!=Header[6]) return E_CHK; //Checksum error sendACK(); return Header[4];//E_OK(0) if more data, E_EOF(1) if EOF } byte readByte(){ byte outData=0; boolean inData=0; unsigned long timeout=micros(); pinTrigDown=false;//reset trig pin ignorePinTrig=false; while(!pinTrigDown){ if(micros()>timeout+200){ ignorePinTrig=true; return E_TO; //Timeout here will cause checksum error } }; ignorePinTrig=true; //debugPin(); noInterrupts(); delayMicroseconds(T_BIT); for(byte count=0;count<8;count++){ //SET_DEBUG_PIN; inData=READ_DATA_PIN; outData+=(inData<<count); //CLR_DEBUG_PIN; delayMicroseconds(T_BIT); } delayMicroseconds(20); interrupts(); return outData; } byte waitScout(){ //debugPin(); unsigned long timeout=micros(); pinTrigUp=false; //Enable pin interrupt to detect contention during wait phase ignorePinTrig=false; while(micros()<(timeout+T_IBLK)){};//3ms wait ignorePinTrig=true; if(pinTrigUp) return E_CON; //Contention detected pinTrigUp=false;//reset trig pin ignorePinTrig=false; while(!pinTrigUp){ if(micros()>timeout+10000){//Timeout ignorePinTrig=true; return E_TO; } }; ignorePinTrig=true; //debugPin(); delayMicroseconds(500); return E_OK; } void sendACK(){ //Set net active noInterrupts(); delayMicroseconds(T_ACT*2); CLR_DATA_PIN; delayMicroseconds(T_ACT); SET_DATA_PIN; writeByte(1); interrupts(); debugPin(); }
[ "jason.lucas7@ntlworld.com" ]
jason.lucas7@ntlworld.com
dbd0727af3737ee47eb5e8a533d9a8c4dadf5f86
6a5bcb74e116c16ca603a5124b11f1e4355b42a1
/SDK/PUBG_EngineSettings_classes.hpp
6c2708e72e2150f37a41c11adc4750ccba87fe44
[]
no_license
taxi2za/PUBG-FULL-SDK
7ce8d261fb7a34f3dc9690c28408c285e487771d
a91088bcc1747de95a1fbd3416aada189799fb17
refs/heads/master
2020-04-27T07:26:16.461620
2019-03-05T14:52:06
2019-03-05T14:52:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,480
hpp
#pragma once // PUBG FULL SDK - Generated By Respecter (5.3.4.10 [04/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_EngineSettings_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class EngineSettings.ConsoleSettings // 0x0048 (0x0078 - 0x0030) class UConsoleSettings : public UObject { public: int MaxScrollbackSize; // 0x0030(0x0004) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x0034(0x0004) MISSED OFFSET TArray<struct FAutoCompleteCommand> ManualAutoCompleteList; // 0x0038(0x0010) (Edit, ZeroConstructor, Config) TArray<class FString> AutoCompleteMapPaths; // 0x0048(0x0010) (Edit, ZeroConstructor, Config) float BackgroundOpacityPercentage; // 0x0058(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData) bool bOrderTopToBottom; // 0x005C(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) unsigned char UnknownData01[0x3]; // 0x005D(0x0003) MISSED OFFSET struct FColor InputColor; // 0x0060(0x0004) (Edit, Config, IsPlainOldData) struct FColor HistoryColor; // 0x0064(0x0004) (Edit, Config, IsPlainOldData) struct FColor AutoCompleteCommandColor; // 0x0068(0x0004) (Edit, Config, IsPlainOldData) struct FColor AutoCompleteCVarColor; // 0x006C(0x0004) (Edit, Config, IsPlainOldData) struct FColor AutoCompleteFadedColor; // 0x0070(0x0004) (Edit, Config, IsPlainOldData) unsigned char UnknownData02[0x4]; // 0x0074(0x0004) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class EngineSettings.ConsoleSettings"); return ptr; } }; // Class EngineSettings.GameMapsSettings // 0x00A8 (0x00D8 - 0x0030) class UGameMapsSettings : public UObject { public: struct FStringAssetReference EditorStartupMap; // 0x0030(0x0010) (Edit, Config) class FString LocalMapOptions; // 0x0040(0x0010) (Edit, ZeroConstructor, Config) struct FStringAssetReference TransitionMap; // 0x0050(0x0010) (Edit, Config) bool bUseSplitscreen; // 0x0060(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) TEnumAsByte<ETwoPlayerSplitScreenType> TwoPlayerSplitscreenLayout; // 0x0061(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) TEnumAsByte<EThreePlayerSplitScreenType> ThreePlayerSplitscreenLayout; // 0x0062(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) bool bOffsetPlayerGamepadIds; // 0x0063(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x0064(0x0004) MISSED OFFSET struct FStringClassReference GameInstanceClass; // 0x0068(0x0010) (Edit, Config, NoClear) struct FStringAssetReference GameDefaultMap; // 0x0078(0x0010) (Edit, Config) struct FStringAssetReference ServerDefaultMap; // 0x0088(0x0010) (Edit, Config) struct FStringClassReference GlobalDefaultGameMode; // 0x0098(0x0010) (Edit, Config, NoClear) struct FStringClassReference GlobalDefaultServerGameMode; // 0x00A8(0x0010) (Edit, Config) TArray<struct FGameModeName> GameModeMapPrefixes; // 0x00B8(0x0010) (Edit, ZeroConstructor, Config) TArray<struct FGameModeName> GameModeClassAliases; // 0x00C8(0x0010) (Edit, ZeroConstructor, Config) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class EngineSettings.GameMapsSettings"); return ptr; } }; // Class EngineSettings.GameNetworkManagerSettings // 0x0030 (0x0060 - 0x0030) class UGameNetworkManagerSettings : public UObject { public: int MinDynamicBandwidth; // 0x0030(0x0004) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData) int MaxDynamicBandwidth; // 0x0034(0x0004) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData) int TotalNetBandwidth; // 0x0038(0x0004) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData) int BadPingThreshold; // 0x003C(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData) unsigned char bIsStandbyCheckingEnabled : 1; // 0x0040(0x0001) (Edit, Config) unsigned char UnknownData00[0x3]; // 0x0041(0x0003) MISSED OFFSET float StandbyRxCheatTime; // 0x0044(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData) float StandbyTxCheatTime; // 0x0048(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData) float PercentMissingForRxStandby; // 0x004C(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData) float PercentMissingForTxStandby; // 0x0050(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData) float PercentForBadPing; // 0x0054(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData) float JoinInProgressStandbyWaitTime; // 0x0058(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData) unsigned char UnknownData01[0x4]; // 0x005C(0x0004) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class EngineSettings.GameNetworkManagerSettings"); return ptr; } }; // Class EngineSettings.GameSessionSettings // 0x0010 (0x0040 - 0x0030) class UGameSessionSettings : public UObject { public: int MaxSpectators; // 0x0030(0x0004) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData) int MaxPlayers; // 0x0034(0x0004) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData) unsigned char bRequiresPushToTalk : 1; // 0x0038(0x0001) (Edit, Config, GlobalConfig) unsigned char UnknownData00[0x7]; // 0x0039(0x0007) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class EngineSettings.GameSessionSettings"); return ptr; } }; // Class EngineSettings.GeneralEngineSettings // 0x0000 (0x0030 - 0x0030) class UGeneralEngineSettings : public UObject { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class EngineSettings.GeneralEngineSettings"); return ptr; } }; // Class EngineSettings.GeneralProjectSettings // 0x00E8 (0x0118 - 0x0030) class UGeneralProjectSettings : public UObject { public: class FString CompanyName; // 0x0030(0x0010) (Edit, ZeroConstructor, Config) class FString CompanyDistinguishedName; // 0x0040(0x0010) (Edit, ZeroConstructor, Config) class FString CopyrightNotice; // 0x0050(0x0010) (Edit, ZeroConstructor, Config) class FString Description; // 0x0060(0x0010) (Edit, ZeroConstructor, Config) class FString Homepage; // 0x0070(0x0010) (Edit, ZeroConstructor, Config) class FString LicensingTerms; // 0x0080(0x0010) (Edit, ZeroConstructor, Config) class FString PrivacyPolicy; // 0x0090(0x0010) (Edit, ZeroConstructor, Config) struct FGuid ProjectID; // 0x00A0(0x0010) (Edit, Config, IsPlainOldData) class FString ProjectName; // 0x00B0(0x0010) (Edit, ZeroConstructor, Config) class FString ProjectVersion; // 0x00C0(0x0010) (Edit, ZeroConstructor, Config) class FString SupportContact; // 0x00D0(0x0010) (Edit, ZeroConstructor, Config) struct FText ProjectDisplayedTitle; // 0x00E0(0x0018) (Edit, Config) struct FText ProjectDebugTitleInfo; // 0x00F8(0x0018) (Edit, Config) bool bShouldWindowPreserveAspectRatio; // 0x0110(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) bool bUseBorderlessWindow; // 0x0111(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) bool bStartInVR; // 0x0112(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) bool bAllowWindowResize; // 0x0113(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) bool bAllowClose; // 0x0114(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) bool bAllowMaximize; // 0x0115(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) bool bAllowMinimize; // 0x0116(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData) unsigned char UnknownData00[0x1]; // 0x0117(0x0001) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class EngineSettings.GeneralProjectSettings"); return ptr; } }; // Class EngineSettings.HudSettings // 0x0018 (0x0048 - 0x0030) class UHudSettings : public UObject { public: unsigned char bShowHUD : 1; // 0x0030(0x0001) (Edit, Config) unsigned char UnknownData00[0x7]; // 0x0031(0x0007) MISSED OFFSET TArray<struct FName> DebugDisplay; // 0x0038(0x0010) (Edit, ZeroConstructor, Config, GlobalConfig) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class EngineSettings.HudSettings"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "45327951+realrespecter@users.noreply.github.com" ]
45327951+realrespecter@users.noreply.github.com
ab9b9da012d6ca7cf9a4ab98e45cc8e84e444a8c
dd80a584130ef1a0333429ba76c1cee0eb40df73
/frameworks/wilhelm/src/android/BufferQueueSource.cpp
6cf04fbc5193acdbb5a884b41bbe3441a10d81cc
[ "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
6,355
cpp
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //#define USE_LOG SLAndroidLogLevel_Verbose #include "sles_allinclusive.h" #include "android/BufferQueueSource.h" #include <media/stagefright/foundation/ADebug.h> #include <sys/types.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> namespace android { const SLuint32 BufferQueueSource::kItemProcessed[NB_BUFFEREVENT_ITEM_FIELDS] = { SL_ANDROID_ITEMKEY_BUFFERQUEUEEVENT, // item key sizeof(SLuint32), // item size SL_ANDROIDBUFFERQUEUEEVENT_PROCESSED // item data }; BufferQueueSource::BufferQueueSource(IAndroidBufferQueue *androidBufferQueue) : mAndroidBufferQueueSource(androidBufferQueue), mStreamToBqOffset(0), mEosReached(false) { } BufferQueueSource::~BufferQueueSource() { SL_LOGD("BufferQueueSource::~BufferQueueSource"); } //-------------------------------------------------------------------------- status_t BufferQueueSource::initCheck() const { return mAndroidBufferQueueSource != NULL ? OK : NO_INIT; } ssize_t BufferQueueSource::readAt(off64_t offset, void *data, size_t size) { SL_LOGD("BufferQueueSource::readAt(offset=%lld, data=%p, size=%d)", offset, data, size); if (mEosReached) { // once EOS has been received from the buffer queue, you can't read anymore return 0; } ssize_t readSize; slAndroidBufferQueueCallback callback = NULL; void* pBufferContext, *pBufferData, *callbackPContext; uint32_t dataSize, dataUsed; interface_lock_exclusive(mAndroidBufferQueueSource); if (mAndroidBufferQueueSource->mState.count == 0) { readSize = 0; } else { assert(mAndroidBufferQueueSource->mFront != mAndroidBufferQueueSource->mRear); AdvancedBufferHeader *oldFront = mAndroidBufferQueueSource->mFront; AdvancedBufferHeader *newFront = &oldFront[1]; // where to read from char *pSrc = NULL; // can this read operation cause us to call the buffer queue callback // (either because there was a command with no data, or all the data has been consumed) bool queueCallbackCandidate = false; // consume events when starting to read data from a buffer for the first time if (oldFront->mDataSizeConsumed == 0) { if (oldFront->mItems.mAdtsCmdData.mAdtsCmdCode & ANDROID_ADTSEVENT_EOS) { mEosReached = true; // EOS has no associated data queueCallbackCandidate = true; } oldFront->mItems.mAdtsCmdData.mAdtsCmdCode = ANDROID_ADTSEVENT_NONE; } //assert(mStreamToBqOffset <= offset); CHECK_LE(mStreamToBqOffset, offset); if (offset + size <= mStreamToBqOffset + oldFront->mDataSize) { pSrc = ((char*)oldFront->mDataBuffer) + (offset - mStreamToBqOffset); if (offset - mStreamToBqOffset + size == oldFront->mDataSize) { // consumed buffer entirely oldFront->mDataSizeConsumed = oldFront->mDataSize; mStreamToBqOffset += oldFront->mDataSize; queueCallbackCandidate = true; // move queue to next buffer if (newFront == &mAndroidBufferQueueSource-> mBufferArray[mAndroidBufferQueueSource->mNumBuffers + 1]) { // reached the end, circle back newFront = mAndroidBufferQueueSource->mBufferArray; } mAndroidBufferQueueSource->mFront = newFront; // update the queue state mAndroidBufferQueueSource->mState.count--; mAndroidBufferQueueSource->mState.index++; SL_LOGV("BufferQueueSource moving to next buffer"); } } // consume data: copy to given destination if (NULL != pSrc) { memcpy(data, pSrc, size); readSize = size; } else { readSize = 0; } if (queueCallbackCandidate) { // data has been consumed, and the buffer queue state has been updated // we will notify the client if applicable if (mAndroidBufferQueueSource->mCallbackEventsMask & SL_ANDROIDBUFFERQUEUEEVENT_PROCESSED) { callback = mAndroidBufferQueueSource->mCallback; // save callback data while under lock callbackPContext = mAndroidBufferQueueSource->mContext; pBufferContext = (void *)oldFront->mBufferContext; pBufferData = (void *)oldFront->mDataBuffer; dataSize = oldFront->mDataSize; dataUsed = oldFront->mDataSizeConsumed; } } } interface_unlock_exclusive(mAndroidBufferQueueSource); // notify client if (NULL != callback) { SLresult result = (*callback)(&mAndroidBufferQueueSource->mItf, callbackPContext, pBufferContext, pBufferData, dataSize, dataUsed, // no messages during playback other than marking the buffer as processed (const SLAndroidBufferItem*)(&kItemProcessed) /* pItems */, NB_BUFFEREVENT_ITEM_FIELDS * sizeof(SLuint32) /* itemsLength */ ); if (SL_RESULT_SUCCESS != result) { // Reserved for future use SL_LOGW("Unsuccessful result %d returned from AndroidBufferQueueCallback", result); } } return readSize; } status_t BufferQueueSource::getSize(off64_t *size) { SL_LOGD("BufferQueueSource::getSize()"); // we're streaming, we don't know how much there is *size = 0; return ERROR_UNSUPPORTED; } } // namespace android
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
b8013afd4ea0ee447473cac8256c70dd20650e0b
f68310c833cdc39789e8e8419121d5573027b88e
/Pacman - end game/CavePacman/Wave.h
866c74dbf20028419c82377af7ce307b309a6536
[]
no_license
sadhi/pacman3d-ti
3307480ba3ba5621f32d1c4db8f46b0ef619fc54
bbf203ff4a0358b6ccb66fe756d85c574ff562be
refs/heads/master
2020-04-14T00:33:30.621371
2013-04-11T19:13:32
2013-04-11T19:13:32
32,311,709
0
0
null
null
null
null
UTF-8
C++
false
false
1,926
h
#pragma once #include <Windows.h> #include "Mmsystem.h" #pragma pack(1) typedef struct __WAVEDESCR { BYTE riff[4]; DWORD size; BYTE wave[4]; } _WAVEDESCR, *_LPWAVEDESCR; typedef struct __WAVEFORMAT { BYTE id[4]; DWORD size; SHORT format; SHORT channels; DWORD sampleRate; DWORD byteRate; SHORT blockAlign; SHORT bitsPerSample; } _WAVEFORMAT, *_LPWAVEFORMAT; #pragma pack() class CWave { public: CWave(void); virtual ~CWave(void); public: // Public methods BOOL Load(const char* filePath); BOOL Save(LPTSTR lpszFilePath); BOOL Play(); BOOL Stop(); BOOL Pause(); BOOL Mix(CWave& wave); BOOL IsValid() {return (m_lpData != NULL);} BOOL IsPlaying() {return (!m_bStopped && !m_bPaused);} BOOL IsStopped() {return m_bStopped;} BOOL IsPaused() {return m_bPaused;} LPBYTE GetData() {return m_lpData;} DWORD GetSize() {return m_dwSize;} SHORT GetChannels() {return m_Format.channels;} DWORD GetSampleRate() {return m_Format.sampleRate;} SHORT GetBitsPerSample() {return m_Format.bitsPerSample;} private: // Pribate methods BOOL Open(SHORT channels, DWORD sampleRate, SHORT bitsPerSample); BOOL Close(); BOOL static CALLBACK WaveOut_Proc(HWAVEOUT hwi, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2); private: // Private members _WAVEDESCR m_Descriptor; _WAVEFORMAT m_Format; LPBYTE m_lpData; DWORD m_dwSize; HWAVEOUT m_hWaveout; WAVEHDR m_WaveHeader; BOOL m_bStopped; BOOL m_bPaused; };
[ "MichaelKoole1992@gmail.com@b95af814-9297-101e-d73d-04743131d72c" ]
MichaelKoole1992@gmail.com@b95af814-9297-101e-d73d-04743131d72c
f7030b25a351f7219b9e4e558986be7b090e04bf
245724709dfc7ee5c1c2d4ce6ec55d523f78d60c
/src/Algorithms/davidsonharel.cpp
a028580cbae6dd8c2816ad61006fa3621a19b34f
[]
no_license
joemcdonnell50/Qt_NetvizGL2
47aeca8b3c808d96567e1986457b3014d45a891f
08c1929ed8735029ed40ea6ad99e4cf175d76780
refs/heads/master
2021-05-13T13:23:56.045366
2018-04-18T16:33:46
2018-04-18T16:33:46
116,705,618
0
0
null
2018-01-08T17:14:39
2018-01-08T17:14:39
null
UTF-8
C++
false
false
2,968
cpp
#include <sys/time.h> #include <zconf.h> #include "../../inc/Algorithms/DavidsonHarel.h" DavidsonHarel::DavidsonHarel(Graph *g) : Algorithm(g) { W = 40; L = 30; area = W * L; t = graph->numVertices; k = sqrt(area / (double)t); m_temperature = 1000; m_shrinkingFactor = 0.8; m_diskRadius = 100.0; adj = new list<int>[graph->numVertices]; m_numberOfIterations = 30 * t; initialPlacement(); } void DavidsonHarel::apply() { //calculate the repulsive forces for every node Vertex *v; Vertex *u; for (int i = 0; i < graph->numVertices; ++i) { v = graph->vertices[i]; v->forceX = 0; v->forceY = 0; for (int j = 0; j < graph->numVertices; ++j) { if (i == j) continue; u = graph->vertices[j]; double xDist = (v->posX - u->posX); double yDist = (v->posY - u->posY); double dist = sqrt((xDist * xDist) + (yDist * yDist)); if (dist < 0.00000000002) dist = 0.00000000002; double div = (dist + 1.0)*(dist + 1.0); double repulsion = 1.0 / div; // / v->forceX += xDist / dist * repulsion; v->forceY += yDist / dist * repulsion; } } // double lengthSum = 0.0; // m_multiplier = 2.0; // m_prefEdgeLength = 0.0; // for (int i = 0; i < graph->numVertices; ++i){ // } double prefEdgeLength = 100; for (int i = 0; i < graph->numEdges; ++i) { v = graph->edges[i]->base; u = graph->edges[i]->connect; double xDist = (v->posX - u->posX); double yDist = (v->posY - u->posY); double dist = sqrt((xDist * xDist) + (yDist * yDist)); //cout << dist << endl; if (dist < 0.00000000002) dist = 1.0; double attraction = dist - prefEdgeLength; //attraction *= attraction; v->forceX -= xDist / dist * attraction; v->forceY -= yDist / dist * attraction; u->forceX += xDist / dist * attraction; u->forceY += yDist / dist * attraction; } for (int i = 0; i < graph->numVertices; ++i) { v = graph->vertices[i]; v->posX += v->forceX * 0.0015; v->posY += v->forceY * 0.0015; } t *= .9; } void DavidsonHarel::initialPlacement() { //char *digit = new char[64]; struct timeval time; gettimeofday(&time, NULL); srand(Graph::hash3(time.tv_sec, time.tv_usec, getpid())); for (int j = 0; j < graph->numVertices; ++j) { //sprintf(digit, "%d", j); //graph->vertices[j]->setText(digit); graph->vertices[j]->posX = ((double) rand()) / RAND_MAX * (W) - W / 2; graph->vertices[j]->posY = ((double) rand()) / RAND_MAX * (L) - L / 2; graph->vertices[j]->posZ = 0; } }
[ "joemcdonnell50@gmail.com" ]
joemcdonnell50@gmail.com
0dbd03349cb3c1bc139925b9c1baf6d7389f96fb
7c16810533a72162f1d584e2735235e1148e2cfc
/base1.cpp
9a21819598cb22cdf2fa73f7664d13cdb82af8ec
[]
no_license
hgrahn/DV1581_testcode
958ddf70c0cec45a177e4542c0d3eda39591e9ca
5a74d1163b09d6126d9efcc55c9a64d04262d4ff
refs/heads/master
2020-03-31T16:23:34.547587
2019-03-12T14:40:21
2019-03-12T14:40:21
152,373,593
0
0
null
null
null
null
UTF-8
C++
false
false
2,133
cpp
#include <iostream> #include <string> class BaseClass { private: int a; protected: int b; std::string name; public: BaseClass() { a = 0; b = 0; name = "Default name"; std::cout << "BaseClass default constructor: " << "name = " << name << ", a = " << a << ", b = " << b << std::endl; } BaseClass(int inita, int initb, std::string initname) : a(inita), b(initb), name(initname) { std::cout << "BaseClass constructor: " << "name = " << name << ", a = " << a << ", b = " << b << std::endl; } int getA() const { return a; } void setA(const int newa) { a = newa; } virtual int getB() const { return b; } virtual void setB(const int newb) { b = newb; } virtual void print() const { std::cout << "print(): name = " << name << ", a = " << a << ", b = " << b << std::endl; } virtual ~BaseClass() = default; }; // inheritance can be public or private class DerivedClass : public BaseClass // inherits from BaseClass { private: const int factor = 2; int c; public: DerivedClass() : BaseClass() { c = 0; std::cout << "DerivedClass default constructor: c = " << c << std::endl; } DerivedClass(int inita, int initb, int initc, std::string initname) : BaseClass(inita, initb, initname), c(initc) { std::cout << "DerivedClass constructor: " << "name = " << initname << ", a = " << inita << ", b = " << initb << ", c = " << initc << std::endl; } int getB() const override { return factor * b; } void setB(const int newb) override { b = factor * newb; } void print() const override { BaseClass::print(); std::cout << "Derived print(): c= " << c << std::endl; } }; int main() { std::cout << std::endl; BaseClass bc1; BaseClass bc2(3, 5, "bc2"); bc1.print(); bc2.print(); std::cout << std::endl; DerivedClass dc1; DerivedClass dc2(5,7, 9, "dc2"); dc1.print(); dc2.print(); std::cout << std::endl; dc2.setA(10); dc2.setB(10); dc2.print(); dc2.setA(40); bc2.setB(50); bc2.print(); }
[ "Hakan.Grahn@bth.se" ]
Hakan.Grahn@bth.se
997acbbdae873e6e695f7e3b401503b52a717fb2
c08441e1ad5d33bc42ed6ee090a6231778960d34
/c++/C-Free/datastructures/linklist/single linklist/19_intersection_of_two_sorted_linklist2.cpp
924f65930c8e23a560c46acd1d3a23ca70b775ed
[]
no_license
Sahilbatra1211/c-
45e3129e4994629bc80cc2cddaf16f2e3f21fe4c
7b8eb89d2db4a6eaec04197f8776e7fadffa3275
refs/heads/master
2020-03-31T18:34:22.640547
2018-10-10T17:38:03
2018-10-10T17:38:03
152,463,752
0
0
null
null
null
null
UTF-8
C++
false
false
1,693
cpp
//intersection of two sorted linklist usning recurssion #include<iostream> using namespace std; struct node { node *next; int data; }; node *head=NULL; node *temp; void insert() { cout<<"enter the data"; int a; cin>>a; if(head==NULL) { temp=new node(); temp->next=NULL; temp->data=a; head=temp; } else { node *temp2=new node(); temp2->data=a; temp2->next=NULL; temp->next=temp2; temp=temp2; } } node *head2=NULL; node *temp3; void insert2() { cout<<"enter the data"; int a; cin>>a; if(head2==NULL) { temp3=new node(); temp3->next=NULL; temp3->data=a; head2=temp3; } else { node *temp2=new node(); temp2->data=a; temp2->next=NULL; temp3->next=temp2; temp3=temp2; } } ; struct Node *sortedIntersect(struct Node *a, struct Node *b) { /* base case */ if (a == NULL || b == NULL) return NULL; /* If both lists are non-empty */ /* advance the smaller list and call recursively */ if (a->data < b->data) return sortedIntersect(a->next, b); if (a->data > b->data) return sortedIntersect(a, b->next); // Below lines are executed only when a->data == b->data struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = a->data; /* advance both lists and call recursively */ temp->next = sortedIntersect(a->next, b->next); return temp; } void display() { node *temp2=head; while(temp2!=NULL) { cout<<temp2->data; temp2=temp2->next; } } int main() { insert(); insert(); insert(); insert2(); insert2(); insert2(); node *temp1=head; node *temp2=head2; intersectionoftwolinklist(temp1,temp2); display(); }
[ "sahil27ahuja1999@gmail.com" ]
sahil27ahuja1999@gmail.com
8bd0f0bb85386516567868552b49f5852d8db0ba
53b283457572f17440ac2bdfabd92b8488cff457
/ibitset.h
c1836eba0aea62d19479ff6d4e716c9ebe95a005
[ "MIT" ]
permissive
Jacon20/etl
8888c57a2b7584739f7b192a3f2c79b74c8413d4
dad6faa8f5676d66c4bc8b42e5a993a776eb7fad
refs/heads/master
2021-01-18T06:48:28.773874
2014-12-24T20:49:53
2014-12-24T20:49:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,924
h
///\file /****************************************************************************** The MIT License(MIT) Embedded Template Library. Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #ifndef __ETL_IBITSET__ #define __ETL_IBITSET__ namespace etl { //************************************************************************* /// The base class for etl::bitset ///\ingroup bitset //************************************************************************* class ibitset { public: //************************************************************************* /// Default constructor. //************************************************************************* ibitset() { } //************************************************************************* /// Destructor. //************************************************************************* virtual ~ibitset() { } //************************************************************************* /// Set the bit at the position. //************************************************************************* virtual ibitset& set(size_t position, bool value = true) = 0; //************************************************************************* /// Reset the bit at the position. //************************************************************************* virtual ibitset& reset(size_t position) = 0; //************************************************************************* /// Finds the first bit in the specified state. ///\param state The state to search for. ///\returns The position of the bit or SIZE if none were found. //************************************************************************* virtual size_t find_first(bool state) const = 0; }; } #endif
[ "github@wellbelove.co.uk" ]
github@wellbelove.co.uk
75ba1dd30ae27fc3f618605d7817ec4bbe7a9a7e
be0331e6613fbe4d303eaaeba53a470968b2e7b6
/基于多态的职工管理系统/emloyee.h
d7ee66da7485bb7317b21602a973aa2805ed62b7
[]
no_license
zhangkaibin0921/WorkerManger
a0a9ec96d46d1f08663c4e2d49207fdd9a8ffb0e
da1c481fd359fac1a5162225dca86a9d3adbffa7
refs/heads/master
2023-08-27T07:02:05.858639
2021-11-09T01:06:25
2021-11-09T01:06:25
407,356,219
0
0
null
null
null
null
UTF-8
C++
false
false
218
h
#pragma once #include "Worker.h" #include <iostream> using namespace std; class Employee :public Worker { public: Employee(int id, string name, int dId); virtual void showInfo(); virtual string getDeptName(); };
[ "3301043642@qq.com" ]
3301043642@qq.com
fabaee88c7a055d04351bc22efd1f4b4e84d1516
6d00b88d4ea8afe7a169813f79a640f91e87b691
/Physics/cFixedConstraint.cpp
32be96eea0359049028ee14fa13e29585f36df19
[]
no_license
amengol/Fanshawe_Game_Jam
cce3aa48ecf97fef6649ce170bd1f9f6c5510a53
9f045ac028646766aaf3609705cbce8ef798f7e9
refs/heads/master
2020-03-12T19:00:19.962194
2018-08-03T20:02:58
2018-08-03T20:02:58
130,774,966
3
0
null
null
null
null
UTF-8
C++
false
false
1,090
cpp
#include "stdafx.h" #include "cFixedConstraint.h" #include <btBulletDynamicsCommon.h> #include "cRigidBody.h" nPhysics::cFixedConstraint::cFixedConstraint(iRigidBody* rbA, iRigidBody* rbB, const glm::vec3& pivotInA, const glm::vec3 & pivotInB) { btRigidBody* bulletRB_A = (dynamic_cast<cRigidBody*>(rbA))->getBulletRigidBody(); btRigidBody* bulletRB_B = (dynamic_cast<cRigidBody*>(rbB))->getBulletRigidBody(); btVector3 btPivotInA; btPivotInA.setX(pivotInA.x); btPivotInA.setY(pivotInA.y); btPivotInA.setZ(pivotInA.z); btMatrix3x3 mat; mat.setIdentity(); btTransform t_frameInA = btTransform(mat, btPivotInA); btVector3 btPivotInB; btPivotInB.setX(pivotInB.x); btPivotInB.setY(pivotInB.y); btPivotInB.setZ(pivotInB.z); btTransform t_frameInB = btTransform(mat, btPivotInB); mBulletConstraint = new btFixedConstraint(*bulletRB_A, *bulletRB_B, t_frameInA, t_frameInB); }
[ "jorge.amengol@gmail.com" ]
jorge.amengol@gmail.com
803a89a0af179129b3eb4d716ac5bde7c91cc7a5
68c7d60bcbfd7b2b887d8dfd64bbec0bd710c9da
/16401.cpp
5ca68e2d1edbfa017a196d9cf8d438200b8b8e00
[]
no_license
1000ship/BOJ
42b6cc67b06412fb95f132849f6d5843f6feb351
491d479fbd57663f297a935f3505650bc840744e
refs/heads/master
2021-08-03T23:36:50.788794
2021-07-22T01:10:59
2021-07-22T01:10:59
212,285,659
1
0
null
null
null
null
UTF-8
C++
false
false
981
cpp
#include <stdio.h> #include <stdlib.h> #define llu unsigned long long int m, n; int compare ( const void* a, const void* b ) { if( *(llu*)a < *(llu*)b ) return true; return false; } int isOK ( llu arr[], int x ) { int eat = 0; for( int i = 0; i < n && eat < m; ++ i ) { llu tmp = arr[ i ] / x; if( tmp == 0 ) break; eat += tmp; } if( eat >= m ) return true; return false; } int main ( void ) { scanf( "%d %d", &m, &n ); llu arr[ n ]; for( int i = 0; i < n; ++ i ) scanf( "%llu", &arr[ i ] ); qsort( arr, n, sizeof( llu ), compare ); int left = 0; int right = arr[ 0 ]; int mid; while( right - left > 1 ) { mid = (left+right)/2; if( isOK( arr, mid ) ) left = mid; else right = mid; } if( isOK( arr, right ) ) printf( "%d", right ); else printf( "%d", left ); return 0; }
[ "cjstjdgur1234@gmail.com" ]
cjstjdgur1234@gmail.com
4bda0a0dd25b86a13a08ab0bdf6e042a8c1f2cae
85899b3d0c2bf13ba02d8d24091ed63aa4873ba9
/termOps.h
99036b43dd362174fb52247968986fa36701db5b
[]
no_license
sai-sukrutha/FileXplorer
c99b1aca7b4a8ecf4660fde752767ed85647eeda
91dbc55a6361903aa02474ebdcd8db023a5e9568
refs/heads/master
2020-03-27T11:34:48.074264
2018-09-03T15:00:53
2018-09-03T15:00:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
448
h
#include <stdio.h> #include <unistd.h> #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <termios.h> #include <sys/ioctl.h> #define BAUDRATE B38400 using namespace std; struct termios get_mode(int fd); void set_mode(struct termios tio,int fd); void change_mode(int want_key,int fd,struct termios old_tio); void alter_screen(); void exit_alter_screen(); struct winsize get_termsize(); void goto_last();
[ "sai.sukrutha@students.iiit.ac.in" ]
sai.sukrutha@students.iiit.ac.in
69b0b2efcdb7f62fee52ac77ef908b324f1ae90d
39617689dbf273942f818dd297a5a29dcbb24a29
/src/qt/pivx/lockunlock.cpp
5c29adaa79994b915d2880b0cedb65bbfd3e6be6
[ "MIT" ]
permissive
Zoras2/EZPAY
6052f787409a501efcc73f73be9cdbc0fa10dbe1
22acc048d81aa4eb8b593ced1c5db4fb7f2e6ce7
refs/heads/master
2022-12-28T11:25:19.034543
2020-10-08T20:05:18
2020-10-08T20:05:18
300,731,837
1
0
MIT
2020-10-02T20:43:19
2020-10-02T20:43:18
null
UTF-8
C++
false
false
2,868
cpp
// Copyright (c) 2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/lockunlock.h" #include "qt/pivx/forms/ui_lockunlock.h" LockUnlock::LockUnlock(QWidget *parent) : QWidget(parent), ui(new Ui::LockUnlock) { ui->setupUi(this); // Load css. this->setStyleSheet(parent->styleSheet()); ui->container->setProperty("cssClass", "top-sub-menu"); ui->pushButtonUnlocked->setProperty("cssClass", "btn-check-lock-sub-menu-unlocked"); ui->pushButtonUnlocked->setStyleSheet("padding-left: 34px;"); ui->pushButtonLocked->setProperty("cssClass", "btn-check-lock-sub-menu-locked"); ui->pushButtonLocked->setStyleSheet("padding-left: 34px;"); ui->pushButtonStaking->setProperty("cssClass", "btn-check-lock-sub-menu-staking"); ui->pushButtonStaking->setStyleSheet("padding-left: 34px;"); ui->pushButtonUnlocked->setText(tr("Unlock Wallet")); ui->pushButtonLocked->setText(tr("Lock Wallet")); ui->pushButtonStaking->setText(tr("Staking Only")); // Connect connect(ui->pushButtonUnlocked, &QPushButton::clicked, this, &LockUnlock::onUnlockClicked); connect(ui->pushButtonLocked, &QPushButton::clicked, this, &LockUnlock::onLockClicked); connect(ui->pushButtonStaking, &QPushButton::clicked, this, &LockUnlock::onStakingClicked); } LockUnlock::~LockUnlock() { delete ui; } void LockUnlock::updateStatus(WalletModel::EncryptionStatus status) { switch (status) { case WalletModel::EncryptionStatus::Unlocked: ui->pushButtonUnlocked->setChecked(true); ui->pushButtonLocked->setChecked(false); ui->pushButtonStaking->setChecked(false); break; case WalletModel::EncryptionStatus::UnlockedForStaking: ui->pushButtonUnlocked->setChecked(false); ui->pushButtonLocked->setChecked(false); ui->pushButtonStaking->setChecked(true); break; case WalletModel::EncryptionStatus::Locked: ui->pushButtonUnlocked->setChecked(false); ui->pushButtonLocked->setChecked(true); ui->pushButtonStaking->setChecked(false); break; default: break; } } void LockUnlock::onLockClicked() { lock = 0; Q_EMIT lockClicked(StateClicked::LOCK); } void LockUnlock::onUnlockClicked() { lock = 1; Q_EMIT lockClicked(StateClicked::UNLOCK); } void LockUnlock::onStakingClicked() { lock = 2; Q_EMIT lockClicked(StateClicked::UNLOCK_FOR_STAKING); } void LockUnlock::enterEvent(QEvent *) { isOnHover = true; Q_EMIT Mouse_Entered(); } void LockUnlock::leaveEvent(QEvent *) { isOnHover = false; Q_EMIT Mouse_Leave(); } bool LockUnlock::isHovered() { return isOnHover; }
[ "r3mapper@gmail.com" ]
r3mapper@gmail.com
570b243be16087e5c363c579d2d47ae08b2d7dcb
c8456a33da785379421be765c942218339665731
/PumpUIMockup/PumpUIMockup.ino
922c30e105c38be84f8b488d447dbe38091e3fbd
[]
no_license
PeterTeunissen/tinker-homie
f92653a0f7ba251c57cedfe03550361f52a9fe4c
b989cf6dfed9d0d6f88237d07e1114cb4bff972e
refs/heads/master
2021-07-22T20:40:08.481649
2021-07-01T01:50:45
2021-07-01T01:50:45
117,550,793
0
0
null
2018-02-26T02:54:22
2018-01-15T13:45:07
C++
UTF-8
C++
false
false
3,110
ino
#include <Wire.h> // Only needed for Arduino 1.6.5 and earlier #include "SSD1306.h" // alias for `#include "SSD1306Wire.h"` #include "images.h" #include <NTPClient.h> #include <WiFiUdp.h> #include "PCF8574.h" //OLED pins to ESP32 GPIOs via this connecthin: //OLED_SDA -- GPIO4 //OLED_SCL -- GPIO15 //OLED_RST -- GPIO16 //#ifdef SSD_DISPLAY SSD1306 display(0x3c,4,15); //#endif PCF8574 expander(4,15,0x38); #define DEMO_DURATION 3000 typedef void (*Demo)(void); int demoMode = 0; int counter = 1; volatile boolean serveIRQ = false; void expanderIRQ() { serveIRQ = true; } void setup() { pinMode(16,OUTPUT); digitalWrite(16, LOW); // set GPIO16 low to reset OLED delay(50); digitalWrite(16, HIGH); // while OLED is running, must set GPIO16 in high Serial.begin(115200); Serial.println(); Serial.println(); Serial.print("ARDUINO:"); Serial.println(ARDUINO); // Initialising the UI will init the display too. //#ifdef SSD_DISPLAY display.init(); //#endif display.flipScreenVertically(); display.setFont(ArialMT_Plain_10); pumpDemoS(); // Set I2C clock down to 100khz since the expander can't handle more! Wire.setClock(100000); pinMode(23,INPUT); attachInterrupt(digitalPinToInterrupt(23),expanderIRQ, FALLING); expander.begin(); } //#ifdef SSD_DISPLAY void pumpDemoS() { display.setFont(ArialMT_Plain_10); // display.setFont(ArialMT_Plain_16); display.setTextAlignment(TEXT_ALIGN_LEFT); display.drawString(0, 0, "RSSI"); display.drawString(32, 0, ": 12"); display.setTextAlignment(TEXT_ALIGN_RIGHT); display.drawString(128, 0, "14:01:23"); display.setTextAlignment(TEXT_ALIGN_LEFT); display.drawString(0, 12, "Tank"); display.drawString(32, 12, ": 88 % Full"); display.setTextAlignment(TEXT_ALIGN_LEFT); display.drawString(0, 24, "Pump"); display.drawString(32, 24, ": On"); display.drawString(66, 24, "Flow"); display.drawString(98, 24, ": 100"); display.drawString(0, 36, "ZoneA"); display.drawString(32, 36, ": 12 s"); display.drawString(66, 36, "ZoneC"); display.drawString(98, 36, ": 12 s"); display.drawString(0, 48, "ZoneB"); display.drawString(32, 48, ": Off"); display.drawString(66, 48, "ZoneD"); display.drawString(98, 48, ": Off"); display.display(); } //#endif //Demo demos[] = {drawFontFaceDemo, drawTextFlowDemo, drawTextAlignmentDemo, drawRectDemo, drawCircleDemo, drawProgressBarDemo, drawImageDemo, pumpDemo}; //Demo demos[] = {pumpDemoS}; //int demoLength = (sizeof(demos) / sizeof(Demo)); long timeSinceLastModeSwitch = 0; void loop() { // clear the display // display.clear(); // draw the current demo method // demos[demoMode](); //#ifdef SSD_DISPLAY display.setColor(BLACK); display.fillRect(70,0,128-70,10); display.setColor(WHITE); display.setTextAlignment(TEXT_ALIGN_RIGHT); display.drawString(128, 0, String(millis())); // write the buffer to the display display.display(); //#endif if (serveIRQ) { serveIRQ = false; int x = expander.read8(); Serial.print("Read "); Serial.println(x, HEX); } delay(10); }
[ "PeterTeunissen@verizon.net" ]
PeterTeunissen@verizon.net
62de2b0b2fd6728c97a693493209e22a30580966
e878bb5bc796256914bacb8b520fd6589aa29f3f
/src/Module/Modem/CPM/CPM_parameters.hpp
b302d06497fe4599bc9b23cfcdcd397c0619b9b0
[ "MIT" ]
permissive
hongyunnchen/aff3ct
7ee22617e3ca14bba77e6297992315dbae1d3cd4
4883036480d5706482dcfe93bf4fef651dc0f998
refs/heads/master
2021-01-01T04:01:49.239599
2017-07-10T13:38:28
2017-07-10T13:38:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,537
hpp
#ifndef CPM_PARAMETERS_HPP_ #define CPM_PARAMETERS_HPP_ #include <fstream> #include <string> #include <mipp.h> namespace aff3ct { namespace module { template <typename SIN = int, typename SOUT = int> class CPM_parameters { public : CPM_parameters(const int L, const int k, const int p, const int n_b_per_s, const int s_factor, const std::string& filters_type, const std::string& wave_shape) : L (L ), k (k ), p (p ), n_b_per_s (n_b_per_s ), s_factor (s_factor ), filters_type(filters_type ), wave_shape (wave_shape ), m_order ((int)1 << n_b_per_s ), n_bits_p ((int)std::ceil(std::log2((double)p))), tl (L ), // TODO: warning: from here parameters are working for Rimoldi decomposition only! n_wa ((int)(p * std::pow(m_order, L)) ), n_bits_wa ((int)std::ceil(std::log2(n_wa)) ), max_wa_id (((int)1 << n_bits_wa) ), n_st ((int)(p * std::pow(m_order, L-1)) ), n_bits_st ((int)std::ceil(std::log2(n_st)) ), max_st_id (((int)1 << n_bits_st) ), transition_to_binary (n_b_per_s * m_order, -1), binary_to_transition ( m_order, -1), allowed_states (n_st , -1), allowed_wave_forms (n_wa , -1), trellis_next_state (max_st_id * m_order, -1), trellis_related_wave_form (max_st_id * m_order, -1), anti_trellis_original_state (max_st_id * m_order, -1), anti_trellis_input_transition(max_st_id * m_order, -1) { } virtual ~CPM_parameters(){} int L; // CPM pulse width or CPm memory int k; // modulation index numerator int p; // modulation index denumerator int n_b_per_s; // number of bits per symbol int s_factor; // sampling factor const std::string filters_type; // Choose receiver filters bank: {TOTAL} const std::string wave_shape; // Choose wave shape : {GMSK, REC, RCOS} int m_order; // modulation order of the cpm int n_bits_p; // number of bits used to code p int tl; // tail length for the modulation int n_wa; // number of wave forms used by the CPM int n_bits_wa; // number of bits used to code n_wa int max_wa_id; // maximum possible index of a trellis state int n_st; // number of states in the trellis int n_bits_st; // number of bits used to code n_st int max_st_id; // maximum possible index of a trellis state mipp::vector<SIN> transition_to_binary; // gives the binary code for a transition. // For each transition there are n_b_per_s bits separately given // (separate memory cases), in msb to lsb order mipp::vector<SIN> binary_to_transition; // gives the transition related to the binary code mipp::vector<int> allowed_states; // possible used state indexes // (there are jumps in the indexes because of p) mipp::vector<SOUT> allowed_wave_forms; // possible used wave forms indexes // (there are jumps in the indexes because of p) mipp::vector<int> trellis_next_state; // from a given state and transition, gives the next state mipp::vector<SOUT> trellis_related_wave_form; // from a given state and transition, gives the related wave form mipp::vector<int> anti_trellis_original_state; // from a given state and transition index, // gives the original state from where comes the transition mipp::vector<SIN> anti_trellis_input_transition; // from a given state and transition index, // gives the related transition value }; } } #endif /* CPM_PARAMETERS_HPP_ */
[ "adrien.cassagne@inria.fr" ]
adrien.cassagne@inria.fr
2f05d536374ccad4f5d244945aea147dab0c000a
86b11b5e3e484f0acb02be508f3cbf96813581df
/Source/YBaseLib/ZLibHelpers.cpp
2ca3d792390e30d59e34c560440eefe690f73c56
[]
no_license
stenzek/YBaseLib
999b7de9e2e5e249e888ccc2fcc2350068e0162c
7004a8b562373915bb56ea73171c4f3b43fafdea
refs/heads/master
2022-03-10T18:59:49.245529
2019-11-27T15:52:49
2019-11-27T15:52:49
110,406,133
2
0
null
null
null
null
UTF-8
C++
false
false
11,504
cpp
#include "YBaseLib/ZLibHelpers.h" #include "YBaseLib/Memory.h" #ifdef HAVE_ZLIB // Ensure zlib gets pulled in #if Y_COMPILER_MSVC #pragma comment(lib, "zdll.lib") #endif namespace ZLibHelpers { #if 0 static ZCALLBACK void *__zlib_filefuncs_open64(void *pUserData, const void *filename, int mode) { return pUserData; } static ZCALLBACK uLong __zlib_filefuncs_read(void *pUserData, void *pStream, void *buf, uLong size) { return reinterpret_cast<ByteStream *>(pUserData)->Read(buf, size); } static ZCALLBACK uLong __zlib_filefuncs_write(void *pUserData, void *pStream, const void *buf, uLong size) { return reinterpret_cast<ByteStream *>(pUserData)->Write(buf, size); } static ZCALLBACK ZPOS64_T __zlib_filefuncs_tell64(void *pUserData, void *pStream) { return reinterpret_cast<ByteStream *>(pUserData)->GetPosition(); } static ZCALLBACK int __zlib_filefuncs_close(void *pUserData, void *pStream) { reinterpret_cast<ByteStream *>(pUserData)->Flush(); return 0; } static ZCALLBACK int __zlib_filefuncs_testerror(void *pUserData, void *pStream) { return (reinterpret_cast<ByteStream *>(pUserData)->InErrorState()) ? -1 : 0; } static ZCALLBACK long __zlib_filefuncs_seek64(void *pUserData, void *pStream, ZPOS64_T offset, int mode) { if (mode == ZLIB_FILEFUNC_SEEK_CUR) { return reinterpret_cast<ByteStream *>(pUserData)->SeekRelative(offset) ? 0 : -1; } else if (mode == ZLIB_FILEFUNC_SEEK_END) { return reinterpret_cast<ByteStream *>(pUserData)->SeekToEnd() ? 0 : -1; } else if (mode == ZLIB_FILEFUNC_SEEK_SET) { return reinterpret_cast<ByteStream *>(pUserData)->SeekAbsolute(offset) ? 0 : -1; } else { return -1; } } void FillZLibFileFuncsForExistingByteStream(zlib_filefunc64_def *pFileFuncs, ByteStream *pStream) { pFileFuncs->zopen64_file = __zlib_filefuncs_open64; pFileFuncs->zread_file = __zlib_filefuncs_read; pFileFuncs->zwrite_file = __zlib_filefuncs_write; pFileFuncs->ztell64_file = __zlib_filefuncs_tell64; pFileFuncs->zseek64_file = __zlib_filefuncs_seek64; pFileFuncs->zclose_file = __zlib_filefuncs_close; pFileFuncs->zerror_file = __zlib_filefuncs_testerror; pFileFuncs->opaque = reinterpret_cast<void *>(pStream); } bool LocateAndExtractFile(void *pUnzFile, const char *FileName, void **ppBufferPointer, uint32 *pBufferSize) { unzFile realUnzFile = reinterpret_cast<unzFile>(pUnzFile); if (unzLocateFile(realUnzFile, FileName, 2) != UNZ_OK) return false; unz_file_info64 fileInfo; if (unzGetCurrentFileInfo64(realUnzFile, &fileInfo, NULL, 0, NULL, 0, NULL, 0) != UNZ_OK) return false; if (fileInfo.uncompressed_size > 0xFFFFFFFFULL) return false; if (unzOpenCurrentFile(realUnzFile) != UNZ_OK) return false; uint32 fileSize = (uint32)fileInfo.uncompressed_size; byte *pBuffer = (byte *)malloc(fileSize); if ((uint32)unzReadCurrentFile(realUnzFile, pBuffer, fileSize) != fileSize) { free(pBuffer); unzCloseCurrentFile(realUnzFile); return false; } unzCloseCurrentFile(realUnzFile); *ppBufferPointer = pBuffer; *pBufferSize = fileSize; return true; } ByteStream *LocateAndExtractFileStream(void *pUnzFile, const char *FileName) { unzFile realUnzFile = reinterpret_cast<unzFile>(pUnzFile); if (unzLocateFile(realUnzFile, FileName, 2) != UNZ_OK) return NULL; unz_file_info64 fileInfo; if (unzGetCurrentFileInfo64(realUnzFile, &fileInfo, NULL, 0, NULL, 0, NULL, 0) != UNZ_OK) return NULL; if (fileInfo.uncompressed_size > 0xFFFFFFFFULL) return NULL; if (unzOpenCurrentFile(realUnzFile) != UNZ_OK) return NULL; uint32 fileSize = (uint32)fileInfo.uncompressed_size; ByteStream *pStream = ByteStream_CreateGrowableMemoryStream(NULL, fileSize); uint32 position = 0; while (position < fileSize) { static const uint32 CHUNKSIZE = 4096; byte chunkData[CHUNKSIZE]; uint32 readSize = Min(CHUNKSIZE, (fileSize - position)); if ((uint32)unzReadCurrentFile(realUnzFile, chunkData, readSize) != readSize) { pStream->Release(); unzCloseCurrentFile(realUnzFile); return NULL; } // no point in checking return code here, memory will always succeed pStream->Write(chunkData, readSize); position += readSize; } pStream->SeekAbsolute(0); unzCloseCurrentFile(realUnzFile); return pStream; } ByteStream *LocateAndExtractFileStreamProgress(void *pUnzFile, const char *FileName, ProgressCallbacks *pProgressCallbacks) { unzFile realUnzFile = reinterpret_cast<unzFile>(pUnzFile); if (unzLocateFile(realUnzFile, FileName, 2) != UNZ_OK) return NULL; unz_file_info64 fileInfo; if (unzGetCurrentFileInfo64(realUnzFile, &fileInfo, NULL, 0, NULL, 0, NULL, 0) != UNZ_OK) return NULL; if (fileInfo.uncompressed_size > 0xFFFFFFFFULL) return NULL; if (unzOpenCurrentFile(realUnzFile) != UNZ_OK) return NULL; uint32 fileSize = (uint32)fileInfo.uncompressed_size; pProgressCallbacks->SetProgressRange(fileSize); pProgressCallbacks->SetProgressValue(0); ByteStream *pStream = ByteStream_CreateGrowableMemoryStream(NULL, fileSize); uint32 position = 0; while (position < fileSize) { static const uint32 CHUNKSIZE = 4096; byte chunkData[CHUNKSIZE]; uint32 readSize = Min(CHUNKSIZE, (fileSize - position)); if ((uint32)unzReadCurrentFile(realUnzFile, chunkData, readSize) != readSize) { pStream->Release(); unzCloseCurrentFile(realUnzFile); return NULL; } // no point in checking return code here, memory will always succeed pStream->Write(chunkData, readSize); position += readSize; // update progress pProgressCallbacks->SetProgressValue(position); if (pProgressCallbacks->IsCancelled()) { pStream->Release(); unzCloseCurrentFile(realUnzFile); return NULL; } } pStream->SeekAbsolute(0); unzCloseCurrentFile(realUnzFile); pProgressCallbacks->SetProgressValue(position); return pStream; } bool WriteFileStreamToZip(void *pZipFile, const char *FileName, ByteStream *pStream) { zipFile pRealZipFile = reinterpret_cast<unzFile>(pZipFile); // open file in zip file zip_fileinfo zfi; Y_memzero(&zfi, sizeof(zfi)); if (zipOpenNewFileInZip64(pRealZipFile, FileName, &zfi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0) != ZIP_OK) return false; // actually write (compress) it uint32 streamSize = (uint32)pStream->GetSize(); uint32 streamPosition = 0; pStream->SeekAbsolute(0); while (streamPosition < streamSize) { static const uint32 CHUNKSIZE = 4096; byte chunkData[CHUNKSIZE]; uint32 readSize = Min(CHUNKSIZE, (streamSize - streamPosition)); if (pStream->Read(chunkData, readSize) != readSize || zipWriteInFileInZip(pRealZipFile, chunkData, readSize) != ZIP_OK) { zipCloseFileInZip(pRealZipFile); return false; } streamPosition += readSize; } // close file zipCloseFileInZip(pRealZipFile); return true; } bool WriteFileStreamToZipProgress(void *pZipFile, const char *FileName, ByteStream *pStream, ProgressCallbacks *pProgressCallbacks) { zipFile pRealZipFile = reinterpret_cast<unzFile>(pZipFile); // open file in zip file zip_fileinfo zfi; Y_memzero(&zfi, sizeof(zfi)); if (zipOpenNewFileInZip64(pRealZipFile, FileName, &zfi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0) != ZIP_OK) return false; // actually write (compress) it uint32 streamSize = (uint32)pStream->GetSize(); uint32 streamPosition = 0; pStream->SeekAbsolute(0); pProgressCallbacks->SetProgressRange(streamSize); pProgressCallbacks->SetProgressValue(0); while (streamPosition < streamSize) { static const uint32 CHUNKSIZE = 4096; byte chunkData[CHUNKSIZE]; uint32 readSize = Min(CHUNKSIZE, (streamSize - streamPosition)); if (pStream->Read(chunkData, readSize) != readSize || zipWriteInFileInZip(pRealZipFile, chunkData, readSize) != ZIP_OK) { zipCloseFileInZip(pRealZipFile); return false; } streamPosition += readSize; // update progress pProgressCallbacks->SetProgressValue(streamPosition); if (pProgressCallbacks->IsCancelled()) { zipCloseFileInZip(pRealZipFile); return false; } } // close file zipCloseFileInZip(pRealZipFile); pProgressCallbacks->SetProgressValue(streamPosition); return true; } #endif uint32 GetDeflatedBufferUpperBounds(uint32 cbSourceBuffer, const int compressionLevel /*= Z_DEFAULT_COMPRESSION*/) { z_stream zStream; Y_memzero(&zStream, sizeof(zStream)); if (deflateInit(&zStream, compressionLevel) != Z_OK) return cbSourceBuffer * 4; uint32 nBytes = deflateBound(&zStream, cbSourceBuffer); deflateEnd(&zStream); return nBytes; } bool WriteDeflatedDataToBuffer(void* pDestinationBuffer, uint32 cbDestinationBuffer, uint32* pCompressedSize, const void* pSourceBuffer, uint32 cbSourceBuffer, const int compressionLevel /*= Z_DEFAULT_COMPRESSION*/) { z_stream zStream; Y_memzero(&zStream, sizeof(zStream)); if (deflateInit(&zStream, compressionLevel) != Z_OK) return false; zStream.avail_in = cbSourceBuffer; zStream.next_in = (Bytef*)pSourceBuffer; zStream.avail_out = cbDestinationBuffer; zStream.next_out = (Bytef*)pDestinationBuffer; while (zStream.avail_in > 0) { int ret = deflate(&zStream, Z_FINISH); if (ret == Z_STREAM_END) { break; } else if (ret == Z_OK && zStream.avail_out > 0) { continue; } else { deflateEnd(&zStream); return false; } } if (pCompressedSize != NULL) *pCompressedSize = (uint32)zStream.total_out; deflateEnd(&zStream); return true; } // bool WriteDeflatedDataToStream(ByteStream *pDestinationStream, const void *pSourceBuffer, uint32 cbSourceBuffer, // const int compressionLevel /*= Z_DEFAULT_COMPRESSION*/) // { // // } bool ReadDeflatedDataFromBuffer(void* pDestinationBuffer, uint32 cbDestinationBuffer, uint32* pDecompressedSize, const void* pSourceBuffer, uint32 cbSourceBuffer) { z_stream zStream; Y_memzero(&zStream, sizeof(zStream)); if (inflateInit(&zStream) != Z_OK) return false; zStream.avail_in = cbSourceBuffer; zStream.next_in = (Bytef*)pSourceBuffer; zStream.avail_out = cbDestinationBuffer; zStream.next_out = (Bytef*)pDestinationBuffer; while (zStream.avail_in > 0) { int ret = inflate(&zStream, Z_FINISH); if (ret == Z_STREAM_END) { break; } else if (ret == Z_OK && zStream.avail_out > 0) { continue; } else { deflateEnd(&zStream); return false; } } if (pDecompressedSize != NULL) *pDecompressedSize = (uint32)zStream.total_out; deflateEnd(&zStream); return true; } // bool ReadDeflatedDataFromStream(void *pDestinationBuffer, uint32 cbDestinationBuffer, ByteStream *pSourceStream) // { // // } } // namespace ZipHelpers #endif // HAVE_ZLIB
[ "mclaughc@outlook.com" ]
mclaughc@outlook.com
bc9052e8300776c4b289db12129523be93cbc30b
66a953acee4e398d3fc9e6487a23cef26a0b8de7
/이길주/애니메이션 테스트중/SceneMgr.h
ab6bc01d8b85a9202f47bc6de5e34a0e832816c0
[]
no_license
lgj8502/maple
713ef38fa933fbc6d3ef3893dace353e47203b53
005e7dac28bcde7eaba3381dfd3715e940026308
refs/heads/master
2020-03-18T06:47:47.924592
2018-08-16T16:06:13
2018-08-16T16:06:13
134,415,758
0
0
null
null
null
null
UHC
C++
false
false
999
h
#pragma once #include <Windows.h> #include "TemplateSingleton.h" enum { SCENE_SERVER, SCENE_LOBBY, SCENE_INGAME, SCENE_END }; // 전방선언 class Scene; class SceneMgr : public TemplateSingleton<SceneMgr> { BASESET(SceneMgr); public: Scene *m_pScene = nullptr; ID2D1RenderTarget *m_pRT = nullptr; ID2D1SolidColorBrush *m_pBrush = nullptr; int m_Type = SCENE_END; bool m_IsChange = false; // 윈도우 정보용 HWND m_hWnd = nullptr; private: void SetScene(); public: ~SceneMgr(); void Update(float _DelayTime = 0.0f); void Render(); // 씬 변경 요청 void ChangeScene(int _Type); // HWND 저장 inline void SetHwnd(HWND _hWnd) { m_hWnd = _hWnd; } inline void SetRT_Brush(ID2D1RenderTarget *_pRT, ID2D1SolidColorBrush *_pBrush) { m_pRT = _pRT; m_pBrush = _pBrush; } LRESULT MyWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam); }; #define SCENE_MGR SceneMgr::GetInstance()
[ "35256124+lgj8502@users.noreply.github.com" ]
35256124+lgj8502@users.noreply.github.com