Compare commits
29 Commits
06e75924f1
...
v1.1.0
Author | SHA1 | Date | |
---|---|---|---|
f997990af6 | |||
7f373ed354 | |||
31a7cb5675 | |||
87fa30fe82 | |||
ecb06504bc | |||
805ffe70d6 | |||
052fa7f4d1 | |||
9e5bd370c4 | |||
94386c93aa | |||
b13bb445e4 | |||
81fe72c425 | |||
b912be082c | |||
9f47d0fe24 | |||
cc689ce8bb | |||
1ccea1290e | |||
ed549592dd | |||
1c2007928d | |||
a6c543c1b5 | |||
942e4ff8eb | |||
9a18233723 | |||
11b2185bb4 | |||
d27a66e770 | |||
4f1e2447d0 | |||
3075ec583d | |||
2e28dd4c48 | |||
a1699f13db | |||
65b81f5cfa | |||
1c5a85bbb2 | |||
1f04e23092 |
3
.gitattributes
vendored
3
.gitattributes
vendored
@ -1,2 +1,3 @@
|
||||
Doxyfile.in eol=lf
|
||||
*.bat eol=crlf
|
||||
*.bat eol=crlf
|
||||
*.sh eol=lf
|
@ -1,6 +1,6 @@
|
||||
cmake_minimum_required(VERSION 3.23)
|
||||
project(YYCC
|
||||
VERSION 1.0.0
|
||||
VERSION 1.1.0
|
||||
LANGUAGES CXX
|
||||
)
|
||||
|
||||
@ -8,19 +8,18 @@ project(YYCC
|
||||
option(YYCC_BUILD_TESTBENCH "Build testbench of YYCCommonplace." OFF)
|
||||
option(YYCC_BUILD_DOC "Build document of YYCCommonplace." OFF)
|
||||
|
||||
# Detect MSVC IDE environment.
|
||||
# If we in it, we should add configuration and build type in install path.
|
||||
if (CMAKE_GENERATOR MATCHES "Visual Studio")
|
||||
# Do Visual Studio specific
|
||||
set(YYCC_INSTALL_PATH_LIB lib/${CMAKE_VS_PLATFORM_NAME}/$<CONFIG>)
|
||||
set(YYCC_INSTALL_PATH_BIN bin/${CMAKE_VS_PLATFORM_NAME})
|
||||
else()
|
||||
# Other stuff
|
||||
set(YYCC_INSTALL_PATH_LIB lib)
|
||||
set(YYCC_INSTALL_PATH_BIN bin)
|
||||
endif()
|
||||
# Setup install path from CMake provided install path for convenient use.
|
||||
include(GNUInstallDirs)
|
||||
set(YYCC_INSTALL_INCLUDE_PATH ${CMAKE_INSTALL_INCLUDEDIR} CACHE PATH
|
||||
"Public header install path relative to CMAKE_INSTALL_PREFIX unless set to an absolute path.")
|
||||
set(YYCC_INSTALL_LIB_PATH ${CMAKE_INSTALL_LIBDIR} CACHE PATH
|
||||
"Library install path relative to CMAKE_INSTALL_PREFIX unless set to an absolute path.")
|
||||
set(YYCC_INSTALL_BIN_PATH ${CMAKE_INSTALL_BINDIR} CACHE PATH
|
||||
"Binary install path relative to CMAKE_INSTALL_PREFIX unless set to an absolute path.")
|
||||
set(YYCC_INSTALL_DOC_PATH ${CMAKE_INSTALL_DOCDIR} CACHE PATH
|
||||
"Non-arch doc install path relative to CMAKE_INSTALL_PREFIX unless set to an absolute path.")
|
||||
|
||||
# Import 2 build targets
|
||||
# Import 3 build targets
|
||||
add_subdirectory(src)
|
||||
if (YYCC_BUILD_TESTBENCH)
|
||||
add_subdirectory(testbench)
|
||||
@ -29,12 +28,12 @@ if (YYCC_BUILD_DOC)
|
||||
add_subdirectory(doc)
|
||||
endif ()
|
||||
|
||||
# Install project package infos
|
||||
# Package target
|
||||
# Install target and package
|
||||
# Install target
|
||||
install(EXPORT YYCCommonplaceTargets
|
||||
FILE YYCCommonplaceTargets.cmake
|
||||
NAMESPACE YYCC::
|
||||
DESTINATION lib/cmake/YYCCommonplace
|
||||
DESTINATION ${YYCC_INSTALL_LIB_PATH}/cmake/YYCCommonplace
|
||||
)
|
||||
# Package configuration file
|
||||
include(CMakePackageConfigHelpers)
|
||||
@ -46,14 +45,14 @@ write_basic_package_version_file(
|
||||
configure_package_config_file(
|
||||
${CMAKE_CURRENT_LIST_DIR}/cmake/YYCCommonplaceConfig.cmake.in
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/YYCCommonplaceConfig.cmake"
|
||||
INSTALL_DESTINATION lib/cmake/YYCCommonplace
|
||||
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/YYCCommonplace
|
||||
)
|
||||
# Copy to install destination
|
||||
# Copy package files to install destination
|
||||
install(
|
||||
FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/YYCCommonplaceConfig.cmake"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/YYCCommonplaceConfigVersion.cmake"
|
||||
DESTINATION
|
||||
lib/cmake/YYCCommonplace
|
||||
${CMAKE_INSTALL_LIBDIR}/cmake/YYCCommonplace
|
||||
)
|
||||
|
||||
|
21
LICENSE
Normal file
21
LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2024-2024 yyc12345
|
||||
|
||||
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.
|
15
README.md
15
README.md
@ -1,9 +1,16 @@
|
||||
# YYC Commonplace
|
||||
|
||||
During the development of a few projects, I gradually understand how Windows make the compromise with the code written by its old developers, and what is developer wanted in contemporary C++ standard library under Windows environment. So I create this static library for all of my C++ project, After this, I do not need to write these duplicated code in each project. I can use a clear and easy way to manage these codes. I can easily fix issues found in project using this library by updating a single project, rather than fixing these duplicated code in each project one by one because all of them share the same implementations.
|
||||
YYC Commonplace, or YYCCommonplace (abbr. YYCC) is a static library specifically resolving my requirements in C++ and Windows scope.
|
||||
|
||||
This project mainly is served for my personal use. But I would be honored if you would like to use this in your project. Almost of my projects, except some critical projects (they will copy this project implementations into their own project scope to eliminate non-common library dependency), will gradually adapt to this project and drop their own individual implementations.
|
||||
## Usage
|
||||
|
||||
This project includes Visual Studio project file and CMake support at the same time. So that at least I can use one of them freely.
|
||||
For more usage about this library, please build documentation of this project via Doxygen and read it.
|
||||
|
||||
**WIP. Do not use it now.**
|
||||
And I also highly recommend that you read documentation first before writing with this library.
|
||||
|
||||
## Build
|
||||
|
||||
This project require at least CMake 3.23 to build. We suggest that you only use stable version (tagged commit). The latest commit may still work in progress and not stable.
|
||||
|
||||
For Windows builing, you can browse GitHub action script to have a preview. It actually is a simple calling to script file.
|
||||
For other platforms building (e.g. Linux), you can following common builing way of CMake project.
|
||||
|
@ -1,2 +1,7 @@
|
||||
# Add the targets file
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/YYCCommonplaceTargets.cmake")
|
||||
|
||||
@PACKAGE_INIT@
|
||||
|
||||
# Include targets file
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/YYCCommonplaceTargets.cmake")
|
||||
|
||||
check_required_components(YYCCommonplace)
|
@ -4,3 +4,15 @@ configure_file(
|
||||
${CMAKE_CURRENT_BINARY_DIR}/Doxyfile
|
||||
@ONLY
|
||||
)
|
||||
|
||||
# Add custom target
|
||||
add_custom_target (YYCCDocumentation
|
||||
doxygen ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMENT "Generating documentation" VERBATIM
|
||||
)
|
||||
|
||||
# Install built documentation
|
||||
install (DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html
|
||||
DESTINATION ${YYCC_INSTALL_DOC_PATH}
|
||||
)
|
||||
|
@ -2356,7 +2356,7 @@ INCLUDE_FILE_PATTERNS =
|
||||
# recursively expanded use the := operator instead of the = operator.
|
||||
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
|
||||
|
||||
PREDEFINED =
|
||||
PREDEFINED = YYCC_DOXYGEN
|
||||
|
||||
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
|
||||
# tag can be used to specify a list of macro names that should be expanded. The
|
||||
|
33
doc/src/com_helper.dox
Normal file
33
doc/src/com_helper.dox
Normal file
@ -0,0 +1,33 @@
|
||||
/**
|
||||
|
||||
\page com_helper COM Helper
|
||||
|
||||
This namespace is Windows specific.
|
||||
It will be invisible on other platforms.
|
||||
|
||||
This namespace is used by internal functions as intended.
|
||||
They should not be used outside of this library.
|
||||
But if you compel to use them, it is also okey.
|
||||
|
||||
\section com_helper__memory_safe_ptr Memory Safe Pointer Types
|
||||
|
||||
This namespace also provided various memory-safe types for interacting with COM functions.
|
||||
Although Microsoft also has similar smart pointer called \c CComPtr.
|
||||
But this library is eager to hide all Microsoft-related functions calling.
|
||||
Using \c CComPtr is not corresponding with the philosophy of this library.
|
||||
So these standard library based smart pointer types were created.
|
||||
|
||||
\section com_helper__com_guard COM Guard
|
||||
|
||||
This namespace contain a COM Guard which make sure COM was initialized in current module when loading current module.
|
||||
It is essential because all calling to COM functions should be under the premise that COM has been initialized.
|
||||
This guard also will uninitialize COM when unloading this module.
|
||||
|
||||
There is only an exposed function called YYCC::COMHelper::IsInitialized for user calling.
|
||||
This function will check whether COM environment is initialized.
|
||||
If you want YYCC automatically initialize COM environment for you,
|
||||
you must call this function in your program at least one time.
|
||||
Otherwise COM Guard code may be unavailable,
|
||||
because compiler may think they are not essential code and drop them.
|
||||
|
||||
*/
|
@ -2,4 +2,119 @@
|
||||
|
||||
\page config_manager Universal Config Manager
|
||||
|
||||
Universal config manager give programmer an universal way to manage its program settings.
|
||||
There is an example about how to use universal config manager.
|
||||
In following content, we will describe it in detail.
|
||||
|
||||
\code
|
||||
class TestConfigManager {
|
||||
public:
|
||||
enum class TestEnum : int8_t {
|
||||
Test1, Test2, Test3
|
||||
};
|
||||
|
||||
TestConfigManager() :
|
||||
m_IntSetting(YYCC_U8("int-setting"), INT32_C(0)),
|
||||
m_StringSetting(YYCC_U8("string-setting"), YYCC_U8("")),
|
||||
m_FloatSetting(YYCC_U8("float-setting"), 0.0f, YYCC::ConfigManager::ConstraintPresets::GetNumberRangeConstraint<float>(-1.0f, 1.0f)),
|
||||
m_EnumSetting(YYCC_U8("enum-setting"), TestEnum::Test1),
|
||||
m_CoreManager(YYCC_U8("test.cfg"), UINT64_C(0), {
|
||||
&m_IntSetting, &m_StringSetting, &m_FloatSetting, &m_EnumSetting
|
||||
})
|
||||
{}
|
||||
~TestConfigManager() {}
|
||||
|
||||
YYCC::ConfigManager::NumberSetting<int32_t> m_IntSetting;
|
||||
YYCC::ConfigManager::StringSetting m_StringSetting;
|
||||
YYCC::ConfigManager::NumberSetting<float> m_FloatSetting;
|
||||
YYCC::ConfigManager::NumberSetting<TestEnum> m_EnumSetting;
|
||||
|
||||
YYCC::ConfigManager::CoreManager m_CoreManager;
|
||||
};
|
||||
|
||||
// init cfg manager
|
||||
TestConfigManager test;
|
||||
// load string
|
||||
test.m_CoreManager.Load()
|
||||
// get string value
|
||||
auto val = test.m_StringSetting.Get();
|
||||
\endcode
|
||||
|
||||
\section config_manager__setting Setting
|
||||
|
||||
Setting can be seen as the leaf of the config tree.
|
||||
Each setting describe a single configuration entry.
|
||||
|
||||
\subsection config_manager__setting__presets Setting Presets
|
||||
|
||||
We currently provide 2 setting preset classes which you can directly use.
|
||||
|
||||
\li YYCC::ConfigManager::NumberSetting: The setting storing a number inside.
|
||||
It is a template class. Support all arithmetic and enum types (integral, floating point, bool, enum).
|
||||
\li YYCC::ConfigManager::StringSetting: The setting storing a string inside.
|
||||
|
||||
When constructing these settings,
|
||||
you need to provide its unique name which will be used when saving to file or reading from file.
|
||||
Also you need to provide a default value for it.
|
||||
It will be used when fail to read file or initializing itself.
|
||||
Optionally, you can assign a constraint to it which we will introduce in following section.
|
||||
|
||||
\subsection config_manager__setting__custom Custom Setting
|
||||
|
||||
In most cases, the combination use of setting presets and constraints introduced in following is enough.
|
||||
However, if you still are urge to create your personal setting,
|
||||
please inherit YYCC::ConfigManager::AbstractSetting and implement essential class functions.
|
||||
For the class functions you need to implement,
|
||||
please refer to our setting presets, YYCC::ConfigManager::NumberSetting and YYCC::ConfigManager::StringSetting.
|
||||
|
||||
\section config_manager__constraint Constraint
|
||||
|
||||
Constraint can be applied to specific setting instance,
|
||||
and limit its value to specific values,
|
||||
such as minimum maximum value, specific string format and etc.
|
||||
|
||||
\subsection config_manager__constraint__presets Constraint Presets
|
||||
|
||||
YYCC::ConfigManager provide some constraint presets in YYCC::ConfigManager::Constraints namespace.
|
||||
All functions inside this namespace will return a YYCC::ConfigManager::Constraint instance,
|
||||
and you can directly assign it to the constructor of setting.
|
||||
Currently there is only one constraint preset:
|
||||
|
||||
\li YYCC::ConfigManager::Constraints::GetNumberRangeConstraint: Constrain the number value in minimum maximum value range (inclusive).
|
||||
|
||||
\subsection config_manager__constraint__custom Custom Constraint
|
||||
|
||||
For creating your personal constraint,
|
||||
you need to create YYCC::ConfigManager::Constraint instance manually.
|
||||
|
||||
First you need decide the template argument of YYCC::ConfigManager::Constraint.
|
||||
The type you assigned to template argument always is
|
||||
the same type which is accepted by the setting this constraint will be applied to.
|
||||
|
||||
Second, you need assign class member of YYCC::ConfigManager::Constraint.
|
||||
Currently there is only one class member.
|
||||
It is a function pointer called when correcting value.
|
||||
See our constraint presets for more infomation about how to write it.
|
||||
|
||||
\section config_manager__core_manager Core Manager
|
||||
|
||||
YYCC::ConfigManager::CoreManager manage a collection of settings.
|
||||
And have responsibility to reading and writing config file.
|
||||
|
||||
We highly suggest that you create a personal config manager class like example does.
|
||||
Then put essential settings and core manager inside it.
|
||||
Please note you must place core manager after all settings.
|
||||
Because the order of C++ initializing its class member is the order you declared them.
|
||||
The constructor of core manager need the pointer to all it managed settings,
|
||||
so it must be initialized after initializing all settings.
|
||||
|
||||
When initializing core manager, you need assign config file path first.
|
||||
Then you need specify a version number.
|
||||
Version number will be used when reading config file.
|
||||
If the version of config file is higher than your given number,
|
||||
core manager will assume you are trying to read a config file created by a higher version program.
|
||||
Core manager will reject reading and use default value for all settings.
|
||||
Otherwise, core manager will try to read config file and do proper migration if possible.
|
||||
The last argument is an initializer list which contain the \b pointer to all settings this manager managed.
|
||||
|
||||
*/
|
179
doc/src/console_helper.dox
Normal file
179
doc/src/console_helper.dox
Normal file
@ -0,0 +1,179 @@
|
||||
/**
|
||||
|
||||
\page console_helper Console Helper
|
||||
|
||||
This helper provide console related stuff.
|
||||
This helper includes 2 parts.
|
||||
First part is console color.
|
||||
It was constituted by a bunch of macros.
|
||||
The second part is universal console IO function because Windows is lacking in UTF8 console IO.
|
||||
All of these parts will be introduced in following content.
|
||||
|
||||
\section console_helper__color Console Color
|
||||
|
||||
YYCC::ConsoleHelper provide a bunch of macros which can allow you output colorful text in terminal.
|
||||
Supported color is limited in 16 colors,
|
||||
because these color is implemented by ASCII Escape Code: https://en.wikipedia.org/wiki/ANSI_escape_code .
|
||||
So if your terminal do not support this, such as default Windows terminal, or teletypewriter,
|
||||
you will see some unrecognised characters surrounding with your output.
|
||||
That's ASCII Escape Code.
|
||||
|
||||
\subsection console_helper__color__enable_win_color Enable Color in Windows Console
|
||||
|
||||
As we introduced in above,
|
||||
you may know Windows console does not support ASCII Escape Code color in default.
|
||||
However YYCC::ConsoleHelper::EnableColorfulConsole can fix this issue.
|
||||
|
||||
YYCC::ConsoleHelper::EnableColorfulConsole will forcely enable ASCII Escape Code support in Windows console if possible.
|
||||
Thus you can write colorful text in Windows console freely.
|
||||
We suggest you to call this function at the beginning of program.
|
||||
|
||||
Considering most Linux console supports ASCII Escape Code very well,
|
||||
this function does nothing in non-Windows platform.
|
||||
So it is not essential that brack this function calling with Windows-only \c \#if.
|
||||
|
||||
\subsection console_helper__color__common Common Usage
|
||||
|
||||
For common scenarios, you can use macro like this:
|
||||
|
||||
\code
|
||||
YYCC::ConsoleHelper::WriteLine(YYCC_U8(YYCC_COLOR_LIGHT_RED("Light Red Text")));
|
||||
YYCC::ConsoleHelper::WriteLine(YYCC_U8("I am " YYCC_COLOR_LIGHT_RED("Light Red")));
|
||||
\endcode
|
||||
|
||||
In first line, it will make <TT>"Light Red Text"</TT> to be shown in light red color.
|
||||
And for second line, it will make <TT>"Light Red"</TT> to be shown in light red color,
|
||||
but <TT>"I am "</TT> will keep default console font color.
|
||||
|
||||
You also may notice this macro is used with YYCC_U8 macro.
|
||||
Because YYCC::ConsoleHelper::WriteLine only accept UTF8 argument.
|
||||
So please note if you use console color macro with YYCC_U8,
|
||||
please make YYCC_U8 always is located the outside.
|
||||
Otherwise, YYCC_U8 will fail to make the whole become UTF8 stirng as we introduced in \ref library_encoding.
|
||||
Because console color macro is implemented by string literal concatenation internally.
|
||||
|
||||
YYCC_COLOR_LIGHT_RED is a member in YYCC_COLOR macro family.
|
||||
YYCC_COLOR macro family has 16 members for 16 different colors:
|
||||
|
||||
\li YYCC_COLOR_BLACK
|
||||
\li YYCC_COLOR_RED
|
||||
\li YYCC_COLOR_GREEN
|
||||
\li YYCC_COLOR_YELLOW
|
||||
\li YYCC_COLOR_BLUE
|
||||
\li YYCC_COLOR_MAGENTA
|
||||
\li YYCC_COLOR_CYAN
|
||||
\li YYCC_COLOR_WHITE
|
||||
\li YYCC_COLOR_LIGHT_BLACK
|
||||
\li YYCC_COLOR_LIGHT_RED
|
||||
\li YYCC_COLOR_LIGHT_GREEN
|
||||
\li YYCC_COLOR_LIGHT_YELLOW
|
||||
\li YYCC_COLOR_LIGHT_BLUE
|
||||
\li YYCC_COLOR_LIGHT_MAGENTA
|
||||
\li YYCC_COLOR_LIGHT_CYAN
|
||||
\li YYCC_COLOR_LIGHT_WHITE
|
||||
|
||||
\subsection console_helper__color__embedded Embedded Usgae
|
||||
|
||||
In some cases, you want change console at some time point and reset it in another time point.
|
||||
You can use color macros like following example:
|
||||
|
||||
\code
|
||||
YYCC::ConsoleHelper::WriteLine(YYCC_U8(YYCC_COLORHDR_LIGHT_BLUE));
|
||||
|
||||
// Write as much as you liked
|
||||
YYCC::ConsoleHelper::WriteLine(YYCC_U8("some string"));
|
||||
YYCC::ConsoleHelper::WriteLine(YYCC_U8("another string"));
|
||||
|
||||
YYCC::ConsoleHelper::WriteLine(YYCC_U8(YYCC_COLORTAIL));
|
||||
\endcode
|
||||
|
||||
At first line, we output YYCC_COLORHDR_LIGHT_BLUE which is in YYCC_COLORHDR macro family.
|
||||
It is colorful text ASCII Escape Code head.
|
||||
It will make all following output become light blue color,
|
||||
until the last line we output YYCC_COLORTAIL to reset console color to original color.
|
||||
|
||||
Same as YYCC_COLOR macro family,
|
||||
YYCC_COLORHDR macro family also has 16 members for 16 different colors:
|
||||
|
||||
\li YYCC_COLORHDR_BLACK
|
||||
\li YYCC_COLORHDR_RED
|
||||
\li YYCC_COLORHDR_GREEN
|
||||
\li YYCC_COLORHDR_YELLOW
|
||||
\li YYCC_COLORHDR_BLUE
|
||||
\li YYCC_COLORHDR_MAGENTA
|
||||
\li YYCC_COLORHDR_CYAN
|
||||
\li YYCC_COLORHDR_WHITE
|
||||
\li YYCC_COLORHDR_LIGHT_BLACK
|
||||
\li YYCC_COLORHDR_LIGHT_RED
|
||||
\li YYCC_COLORHDR_LIGHT_GREEN
|
||||
\li YYCC_COLORHDR_LIGHT_YELLOW
|
||||
\li YYCC_COLORHDR_LIGHT_BLUE
|
||||
\li YYCC_COLORHDR_LIGHT_MAGENTA
|
||||
\li YYCC_COLORHDR_LIGHT_CYAN
|
||||
\li YYCC_COLORHDR_LIGHT_WHITE
|
||||
|
||||
However YYCC_COLORTAIL is YYCC_COLORTAIL.
|
||||
There is no other variant for different colors.
|
||||
Because all tail of colorful ASCII Escape Code is same.
|
||||
|
||||
\section console_helper__universal_io Universal IO Function
|
||||
|
||||
\subsection console_helper__universal_io__why Why?
|
||||
|
||||
Windows console doesn't support UTF8 very well.
|
||||
The standard input output functions can not work properly with UTF8 on Windows.
|
||||
So we create this namespace and provide various console-related functions
|
||||
to patch Windows console and let it more like the console in other platforms.
|
||||
|
||||
The function provided in this function can be called in any platforms.
|
||||
In Windows, the implementation will use Windows native function,
|
||||
and in other platform, the implementation will redirect request to standard C function like \c std::fputs and etc.
|
||||
So the programmer do not need to be worried about which function should they use,
|
||||
and don't need to use macro to use different IO function in different platforms.
|
||||
It is just enough that fully use the functions provided in this namespace.
|
||||
|
||||
All IO functions this namespace provided are UTF8-based.
|
||||
It also means that input output string should always be UTF8 encoded.
|
||||
|
||||
\subsection console_helper__universal_io__input Input Functions
|
||||
|
||||
Please note that EOL will automatically converted into LF on Windows platform, not CRLF.
|
||||
This action actually is removing all CR chars in result string.
|
||||
This behavior affect nothing in most cases but it still is possible break something in some special case.
|
||||
|
||||
Due to implementation, if you decide to use this function,
|
||||
you should give up using any other function to read stdin stream,
|
||||
such as \c std::gets() and \c std::cin.
|
||||
Because this function may read chars which is more than needed.
|
||||
These extra chars will be stored in this function and can be used next calling.
|
||||
But these chars can not be visited by stdin again.
|
||||
This behavior may cause bug.
|
||||
So if you decide using this function, stick on it and do not change.
|
||||
|
||||
Due to implementation, this function do not support hot switch of stdin.
|
||||
It means that stdin can be redirected before first calling of this function,
|
||||
but it should not be redirected during program running.
|
||||
The reason is the same one introduced above.
|
||||
|
||||
\subsection console_helper__universal_io__output Output Functions
|
||||
|
||||
In current implementation, EOL will not be converted automatically to CRLF.
|
||||
This is different with other stream read functions provided in this namespace.
|
||||
|
||||
Comparing with other stream read functions provided in this namespace,
|
||||
stream write function support hot switch of stdout and stderr.
|
||||
Because they do not have internal buffer storing something.
|
||||
|
||||
In this namespace, there are various stream write function.
|
||||
There is a list telling you how to choose one from them for using:
|
||||
|
||||
\li Functions with leading "Err" will write data into stderr,
|
||||
otherwise they will write data into stdout.
|
||||
\li Functions with embedded "Format" are output functions with format feature
|
||||
like \c std::fprintf(), otherwise the functions with embedded "Write" will
|
||||
only write plain string like \c std::fputs().
|
||||
\li Functions with trailing "Line" will write extra EOL to break current line.
|
||||
This is commonly used, otherwise functions will only write the text provided by arguments,
|
||||
without adding something.
|
||||
|
||||
*/
|
@ -32,7 +32,7 @@ YYCC::DialogHelper::FileDialog::SetOwner will set owner of this dialog.
|
||||
It accepts a Microsoft defined \c HWND as argument which should be familiar with Windows programmer.
|
||||
If you pass \c NULL to it or skip calling this function, it indicate that there is no owner of this dialog.
|
||||
<I>
|
||||
I don't what whill happend if there is no owner for it.
|
||||
I don't what will happen if there is no owner for it.
|
||||
But it would be better to have an owner if possible.
|
||||
</I>
|
||||
|
||||
@ -73,6 +73,95 @@ The directory we meeting in the first launch is system defined.
|
||||
|
||||
\section dialog_helper__file_filters Configure File Filters
|
||||
|
||||
File filters is a drop down list represented in file dialog which allow user filter files by their extensions.
|
||||
It is beneficial to let user get the file which they want in a directory including massive different files.
|
||||
|
||||
<B>For file dialog picking a directory,</B> you can skip this step.
|
||||
Because the file dialog picking directory does not have file filter drop down box.
|
||||
Directory can not be filtered.
|
||||
|
||||
YYCC::DialogHelper::FileFilters takes responsibility for this feature:
|
||||
|
||||
\code
|
||||
auto& filters = params.ConfigreFileTypes();
|
||||
filters.Add(YYCC_U8("Microsoft Word (*.docx; *.doc)"), { YYCC_U8("*.docx"), YYCC_U8("*.doc") });
|
||||
filters.Add(YYCC_U8("Microsoft Excel (*.xlsx; *.xls)"), { YYCC_U8("*.xlsx"), YYCC_U8("*.xls") });
|
||||
filters.Add(YYCC_U8("Microsoft PowerPoint (*.pptx; *.ppt)"), { YYCC_U8("*.pptx"), YYCC_U8("*.ppt") });
|
||||
filters.Add(YYCC_U8("Text File (*.txt)"), { YYCC_U8("*.txt") });
|
||||
filters.Add(YYCC_U8("All Files (*.*)"), { YYCC_U8("*.*") });
|
||||
params.SetDefaultFileTypeIndex(0u);
|
||||
\endcode
|
||||
|
||||
\subsection dialog_helper__file_filters__setup File Filters
|
||||
|
||||
We don't need to initialize YYCC::DialogHelper::FileFilters by ourselves.
|
||||
Oppositely, we fetch it from YYCC::DialogHelper::FileDialog instance by calling YYCC::DialogHelper::FileDialog::ConfigreFileTypes.
|
||||
After fetching, we can call YYCC::DialogHelper::FileFilters::Add to add a filter pair for file filters.
|
||||
|
||||
The first argument is the display text which user will see in file filter drop down box.
|
||||
|
||||
The second argument is a \c std::initializer_list.
|
||||
Every items are Windows used wildcard string instructing which file should be shown in file dialog.
|
||||
It is okey to use multiple wildcard string in list.
|
||||
This is suit for those file types involving multiple file extensions, such as the old and new file types of Microsoft Office as we illustracted.
|
||||
Empty list not allowed
|
||||
|
||||
YYCC::DialogHelper::FileFilters::Add also will return a bool to indicate the success of this adding.
|
||||
|
||||
It should at least has one file filter in file dialog.
|
||||
I don't know the consequence if you don't provide any file filter.
|
||||
|
||||
\subsection dialog_helper__file_filters__default_filter Default File Type
|
||||
|
||||
YYCC::DialogHelper::FileDialog::SetDefaultFileTypeIndex will set the default selected file filter of this dialog.
|
||||
It accepts an index pointing to the file filter which you want to show in default for this file dialog.
|
||||
The index of file filters is the order where you call YYCC::DialogHelper::FileFilters::Add above.
|
||||
If you pass \c NULL to it or skip calling this function, the first one will be default.
|
||||
|
||||
\section dialog_helper__result Create Dialog and Get Result
|
||||
|
||||
Finally, we can call file dialog functions by we initialized YYCC::DialogHelper::FileDialog
|
||||
|
||||
\code
|
||||
YYCC::yycc_u8string single_selection;
|
||||
std::vector<YYCC::yycc_u8string> multiple_selection;
|
||||
|
||||
YYCC::DialogHelper::OpenFileDialog(params, single_selection);
|
||||
YYCC::DialogHelper::OpenMultipleFileDialog(params, multiple_selection);
|
||||
YYCC::DialogHelper::SaveFileDialog(params, single_selection);
|
||||
YYCC::DialogHelper::OpenFolderDialog(params, single_selection);
|
||||
\endcode
|
||||
|
||||
There are 4 file dialogs you can choose:
|
||||
|
||||
\li YYCC::DialogHelper::OpenFileDialog: Open single file
|
||||
\li YYCC::DialogHelper::OpenMultipleFileDialog: Open multiple files
|
||||
\li YYCC::DialogHelper::SaveFileDialog: Save single file
|
||||
\li YYCC::DialogHelper::OpenFolderDialog: Open single directory
|
||||
|
||||
\subsection dialog_helper__result__arguments Arguments
|
||||
|
||||
Among these 4 functions, the first argument always is the reference to YYCC::DialogHelper::FileDialog.
|
||||
Function will use it to decide what should be shown in this file dialog.
|
||||
|
||||
The second argument always is the reference to the container receiving the result.
|
||||
For single selection, the return type is \c yycc_u8string.
|
||||
For multiple selection, the return type is a list of strings: \c std::vector<yycc_u8string>.
|
||||
|
||||
\subsection dialog_helper__result__return_value Return Value
|
||||
|
||||
Please note among these 4 functions will return a bool as its return value to indicate the success of function.
|
||||
If they return false, it means that the execution of functions are failed or user click Cancel button.
|
||||
In this case, there is no guaranteen to the content of second argument (the real return value).
|
||||
|
||||
\section dialog_helper__notes Notes
|
||||
|
||||
You may notice there are various classes which we never introduce.
|
||||
Because they are intermediate classes and should not be used by programmer.
|
||||
For example:
|
||||
|
||||
\li YYCC::DialogHelper::WinFileDialog: The converted YYCC::DialogHelper::FileDialog passed to Windows.
|
||||
\li YYCC::DialogHelper::WinFileFilters: Same as YYCC::DialogHelper::WinFileDialog. It will be passed to Windows functions.
|
||||
\li etc...
|
||||
|
||||
*/
|
@ -4,8 +4,143 @@
|
||||
|
||||
YYCC::EncodingHelper namespace include all encoding related functions:
|
||||
|
||||
\li The convertion between native string and UTF8 string which has been introduced in chapter \ref library_encoding.
|
||||
\li The convertion between ordinary string and UTF8 string which has been introduced in chapter \ref library_encoding.
|
||||
\li Windows specific convertion between \c WCHAR, UTF8 string and string encoded by other encoding.
|
||||
\li The convertion among UTF8, UTF16 and UTF32.
|
||||
|
||||
\section encoding_helper__ordinary_utf8_conv Ordinary & UTF8 Convertion
|
||||
|
||||
These convertion functions have been introduced in previous page.
|
||||
See \ref library_encoding for more infomation.
|
||||
|
||||
YYCC supports following convertions:
|
||||
|
||||
\li YYCC::EncodingHelper::ToUTF8: Convert ordinary string to UTF8 string.
|
||||
\li YYCC::EncodingHelper::ToUTF8View: Same as ToUTF8, but return string view instead.
|
||||
\li YYCC::EncodingHelper::ToOrdinary: Convert UTF8 string to ordinary string.
|
||||
\li YYCC::EncodingHelper::ToOrdinaryView: Same as ToOrdinary, but return string view instead.
|
||||
|
||||
\section encoding_helper__win_conv Windows Specific Convertion
|
||||
|
||||
During Windows programming, the convertion between Microsoft specified \c wchar_t and \c char is an essential operation.
|
||||
Because Windows has 2 different function system, the functions ended with A and the functions ended with W.
|
||||
(Microsoft specified \c wchar_t is \c 2 bytes long. It's different with Linux defined common 4 bytes long).
|
||||
Thus YYCC provides these convertion functions in Windows to help programmer have better programming experience.
|
||||
|
||||
These functions are Windows specific, so they will be invisible in other platforms.
|
||||
Please use them carefully (make sure that you are using them only in Windows environment).
|
||||
|
||||
YYCC supports following convertions:
|
||||
|
||||
\li YYCC::EncodingHelper::WcharToChar: Convert \c wchar_t string to code page specified string.
|
||||
\li YYCC::EncodingHelper::CharToWchar: The reversed convertion of WcharToChar.
|
||||
\li YYCC::EncodingHelper::CharToChar: Convert string between 2 different code pages. It's a shortcut of calling CharToWchar and WcharToChar successively.
|
||||
\li YYCC::EncodingHelper::WcharToUTF8: Convert \c wchar_t string to UTF8 string.
|
||||
\li YYCC::EncodingHelper::UTF8ToWchar: The reversed convertion of WcharToUTF8.
|
||||
\li YYCC::EncodingHelper::CharToUTF8: Convert code page specified string to UTF8 string.
|
||||
\li YYCC::EncodingHelper::UTF8ToChar: The reversed convertion of CharToUTF8.
|
||||
|
||||
Code Page is a Windows concept.
|
||||
If you don't understand it, please view corresponding Microsoft documentation.
|
||||
|
||||
\section encoding_helper__utf_conv UTF8 UTF16 UTF32 Convertion
|
||||
|
||||
The convertion between UTF8, UTF16 and UTF32 is not common but essential.
|
||||
These convertions can be achieved by standard library functions and classes.
|
||||
(they are actually done by standard library functions in our implementation)
|
||||
But we provided functions are easy to use and have clear interface.
|
||||
|
||||
These functions are different with the functions introduced above.
|
||||
They can be used in any platform, not confined in Windows platforms.
|
||||
|
||||
YYCC supports following convertions:
|
||||
|
||||
\li YYCC::EncodingHelper::UTF8ToUTF16: Convert UTF8 string to UTF16 string.
|
||||
\li YYCC::EncodingHelper::UTF16ToUTF8: The reversed convertion of UTF8ToUTF16.
|
||||
\li YYCC::EncodingHelper::UTF8ToUTF32: Convert UTF8 string to UTF32 string.
|
||||
\li YYCC::EncodingHelper::UTF32ToUTF8: The reversed convertion of UTF8ToUTF32.
|
||||
|
||||
\section encoding_helper__overloads Function Overloads
|
||||
|
||||
Every encoding convertion functions (except the convertion between UTF8 and ordinary string) have 4 different overloads for different scenarios.
|
||||
Take YYCC::EncodingHelper::WcharToChar for example.
|
||||
There are following 4 overloads:
|
||||
|
||||
\code
|
||||
bool WcharToChar(const std::wstring_view& src, std::string& dst, UINT code_page);
|
||||
bool WcharToChar(const wchar_t* src, std::string& dst, UINT code_page);
|
||||
std::string WcharToChar(const std::wstring_view& src, UINT code_page);
|
||||
std::string WcharToChar(const wchar_t* src, UINT code_page);
|
||||
\endcode
|
||||
|
||||
\subsection encoding_helper__overloads_destination Destination String
|
||||
|
||||
According to the return value, these 4 overload can be divided into 2 types.
|
||||
The first type returns bool. The second type returns \c std::string instance.
|
||||
|
||||
For the first type, it always return bool to indicate whether the convertion is success.
|
||||
Due to this, the function must require an argument for holding the result string.
|
||||
So you can see the functions belonging to this type always require a reference to \c std::string in argument.
|
||||
|
||||
Oppositely, the second directly returns result by return value.
|
||||
It doesn't care the success of convertion and will return empty string if convertion failed.
|
||||
Programmer can more naturally use it because the retuen value itself is the result.
|
||||
There is no need to declare a variable before calling convertion function for holding result.
|
||||
|
||||
All in all, the first type overload should be used in strict scope.
|
||||
The success of convertion will massively affect the behavior of your following code.
|
||||
For example, the convertion code is delivered to some system function and it should not be empty and etc.
|
||||
The second type overload usually is used in lossen scenarios.
|
||||
For exmaple, this overload usually is used in console output because it usually doesn't matter.
|
||||
There is no risk even if the convertion failed (just output a blank string).
|
||||
|
||||
For the first type, please note that there is \b NO guarantee that the argument holding return value is not changed.
|
||||
Even the convertion is failed, the argument holding return value may still be changed by function itself.
|
||||
|
||||
In this case, the type of result is \c std::string because this is function required.
|
||||
In other functions, such as YYCC::EncodingHelper::WcharToUTF8, the type of result can be \c yycc_u8string or etc.
|
||||
So please note the type of result is decided by convertion function itself, not only \c std::string.
|
||||
|
||||
\subsection encoding_helper__overloads__source Source String
|
||||
|
||||
According to the way providing source string,
|
||||
these 4 overload also can be divided into 2 types.
|
||||
The first type take a reference to constant \c std::wstring_view.
|
||||
The second type take a pointer to constant wchar_t.
|
||||
|
||||
For first type, it will take the whole string for convertion, including \b embedded NUL terminal.
|
||||
Please note we use string view as argument.
|
||||
It is compatible with corresponding raw string pointer and string container.
|
||||
So it is safe to directly pass \c std::wstring for this function.
|
||||
|
||||
For second type, it will assume that you passed argument is a NUL terminated string and send it for convertion.
|
||||
|
||||
The result is clear.
|
||||
If you want to process string with \b embedded NUL terminal, please choose first type overload.
|
||||
Otherwise the second type overload is enough.
|
||||
|
||||
Same as destination string, the type of source is also decided by the convertion function itself.
|
||||
For exmaple, the type of source in YYCC::EncodingHelper::UTF8ToWchar is \c yycc_u8string_view and \c yycc_char8_t,
|
||||
not \c std::wstring and \c wchar_t.
|
||||
|
||||
\subsection encoding_helper__overloads__extra Extra Argument
|
||||
|
||||
There is an extra argument called \c code_page for YYCC::EncodingHelper::WcharToChar.
|
||||
It indicates the code page of destination string,
|
||||
because this function will convert \c wchar_t string to the string with specified code page encoding.
|
||||
|
||||
Some convertion functions have extra argument like this,
|
||||
because they need more infomations to decide what they need to do.
|
||||
Some convertion functions don't have extra argument.
|
||||
For exmaple, the convertion between \c wchar_t string and UTF8 string.
|
||||
Because both source string and destination string are concrete.
|
||||
There is no need to provide any more infomations.
|
||||
|
||||
\subsection encoding_helper__overloads__conclusion Conclusion
|
||||
|
||||
Mixing 2 types of source string and 2 types of destination string,
|
||||
we have 4 different overload as we illustrated before.
|
||||
Programmer can use them freely according to your requirements.
|
||||
And don't forget to provide extra argument if function required.
|
||||
|
||||
*/
|
87
doc/src/exception_helper.dox
Normal file
87
doc/src/exception_helper.dox
Normal file
@ -0,0 +1,87 @@
|
||||
/**
|
||||
|
||||
\page exception_helper Unhandled Exception Handler
|
||||
|
||||
Most Linux users are familiar with core dump.
|
||||
However core dump is a tough work on Windows especially most Windows users are naive for getting core dump.
|
||||
So it is essential to make an easy-to-visit core dump Feature for Windows program.
|
||||
YYCC provides this feature in YYCC::ExceptionHelper.
|
||||
|
||||
You may know Google also has a similar and universal project called Crashpad used by Google Chrome.
|
||||
That's right. But it is too heavy.
|
||||
I just want to implement a tiny but worked core dump feature on Windows.
|
||||
|
||||
This module is Windows specific.
|
||||
It will be invisible on other platforms.
|
||||
|
||||
\section exception_helper__usage Usage
|
||||
|
||||
\subsection exception_helper__usage__code Register Code
|
||||
|
||||
In most scenarios, programmer only need call YYCC::ExceptionHelper::Register() when program started or module loaded.
|
||||
And call YYCC::ExceptionHelper::Unregister when program exited or module unloaded.
|
||||
All details are hidden by these 2 feature.
|
||||
Programmer do not need worried about the implementation of unhandled exception handler.
|
||||
|
||||
\subsection exception_helper__usage__location Location
|
||||
|
||||
When unhandled exception occurs,
|
||||
unhandled exception handler will try to record error log and core dump in following path:
|
||||
|
||||
\li Error Log: <TT>\%LOCALAPPDATA\%\\CrashDumps\\<I>program.exe</I>.<I>pid</I>.log</TT>
|
||||
\li Core Dump: <TT>\%LOCALAPPDATA\%\\CrashDumps\\<I>program.exe</I>.<I>pid</I>.dmp</TT>
|
||||
|
||||
The italic characters <I>program.exe</I> and <I>pid</I> will be replaced by program name and process ID respectively at runtime.
|
||||
Directory <TT>\%LOCALAPPDATA\%\\CrashDumps</TT> also is Windows used crash dump directory.
|
||||
So you may see some other core dumps done by Windows in it.
|
||||
|
||||
\subsection exception_helper__usage__last_remedy Last Remedy
|
||||
|
||||
If unhandled exception handler occurs error, these stuff may not be generated correctly.
|
||||
The end user may not find them and send them to you.
|
||||
There is a last remedy for this scenario.
|
||||
|
||||
Unhandled exception handler will still output error log in \c stderr no matter whether error log or core dump is created.
|
||||
So end user always can fetch error log from console.
|
||||
You only need to instruct end user open command prompt, launch application, reproduce error and get the output error log in console.
|
||||
In this case, you can not get core dump. But you can get error log.
|
||||
It is not good for debugging but it is better than nothing.
|
||||
|
||||
Also please note the last remedy may still have a little bit possibility to occurs error and output nothing,
|
||||
especially the error occurs in back trace function.
|
||||
There is no guaranteen that unhandled exception handler must generate error log and core dump.
|
||||
|
||||
\section exception_helper__notes Notes
|
||||
|
||||
\subsection exception_helper__notes__thread_safe Thread Safe
|
||||
|
||||
All exposed functions in YYCC::ExceptionHelper are thread safe.
|
||||
The implementation uses \c std:mutex to ensure this.
|
||||
|
||||
\subsection exception_helper__notes__singleton Singleton Handler
|
||||
|
||||
YYCC::ExceptionHelper also have a mechanism that make sure the same unhandled exception handler implementation only appear once in the same process.
|
||||
For example, you have an executable program A.exe, and 2 dynamic libraries B.dll and C.dll.
|
||||
A.exe and B.dll use YYCC unhandled exception handler feature but C.dll not.
|
||||
A.exe will load B.dll and C.dll at runtime.
|
||||
Although both A.exe and B.dll call YYCC::ExceptionHelper::Register(),
|
||||
when unhandled exception occurs, there is only one error report output,
|
||||
which may be generated by A.exe or B.dll accoridng to their order of loading.
|
||||
|
||||
The core purpose of this is making sure the program will not output too many error report for the same unhandled exception,
|
||||
no matter how many modules calling YYCC::ExceptionHelper::Register() are loaded.
|
||||
Only one error report is enough.
|
||||
|
||||
More precisely, we use \c CreateMutexW to create an unique mutex in Windows global scope,
|
||||
to make sure YYCC::ExceptionHelper::Register() only run once in the same process.
|
||||
It is very like the implementation of singleton application.
|
||||
|
||||
\subsection exception_helper__notes__recursive_calling Recursive Calling
|
||||
|
||||
The implementation of unhandled exception handler may also will throw exception.
|
||||
This will cause infinite recursive calling.
|
||||
YYCC::ExceptionHelper has internal mechanism to prevent this bad case.
|
||||
If this really happened, the handler will quit silent and will not cause any issue.
|
||||
Programmer don't need to worry about this.
|
||||
|
||||
*/
|
73
doc/src/fs_path_patch.dox
Normal file
73
doc/src/fs_path_patch.dox
Normal file
@ -0,0 +1,73 @@
|
||||
/**
|
||||
|
||||
\page fs_path_patch std::filesystem::path Patch
|
||||
|
||||
As you know, the underlying char type of \c std::filesystem::path is \c wchar_t on Windows,
|
||||
and in other platforms, it is simple \c char.
|
||||
Due to this, if you try to create a \c std::filesystem::path instance by calling constructor with an UTF8 char sequence on Windows,
|
||||
the library implementation will assume your input is based on current Windows code page, not UTF8.
|
||||
And the final path stored in \c std::filesystem::path is not what you expcected.
|
||||
|
||||
This patch gives you a way to create \c std::filesystem::path
|
||||
and extract path string stored in \c std::filesystem::path with UTF8 encoding.
|
||||
This patch namespace always use UTF8 as its argument.
|
||||
You should use the functions provided by this namespace on any platforms
|
||||
instead of vanilla \c std::filesystem::path functions.
|
||||
However, if your C++ standard is higher than C++ 20,
|
||||
you can directly use UTF8 string pointer and string container in \c std::filesystem::path,
|
||||
because standard library has supported them.
|
||||
This patch only just want to provide an uniform programming experience.
|
||||
|
||||
This patch is served for Windows but also works on other plaftoms.
|
||||
If you are in Windows, this patch will perform extra operations to achieve goals,
|
||||
and in other platforms, they just redirect request to corresponding vanilla C++ functions.
|
||||
|
||||
\section fs_path_patch__from_utf8_path Create Path from UTF8 String
|
||||
|
||||
YYCC::FsPathPatch::FromUTF8Path provides this feature.
|
||||
It accepts an string pointer to UTF8 string and try to create \c std::filesystem::path from it.
|
||||
Function will throw exception if encoding convertion or constructor self failed.
|
||||
There are some example:
|
||||
|
||||
\code
|
||||
auto foobar_path = YYCC::FsPathPatch::FromUTF8Path(YYCC_U8("/foo/bar"));
|
||||
auto slashed_path = foobar_path / YYCC::FsPathPatch::FromUTF8Path(YYCC_U8("test"));
|
||||
auto replaced_ext = foobar_path.replace_extension(YYCC::FsPathPatch::FromUTF8Path(YYCC_U8(".txt")));
|
||||
\endcode
|
||||
|
||||
For first line in example, it is obvious that you can create a \c std::filesystem::path from this function.
|
||||
However, for the second and third line in example, what we want to tell you is
|
||||
that you should always use this function in other \c std::filesystem::path functions requiring path string.
|
||||
|
||||
\c std::filesystem::path is a very \e conservative class.
|
||||
Most of its functions only accept \c std::filesystem::path self as argument.
|
||||
For example, \c std::filesystem::path::replace_extension do not accept string as argument.
|
||||
It accepts a reference to \c std::filesystem::path as argument.
|
||||
(it still is possible that pass string pointer or string container to it because they can be converted to \c std::filesystem::path implicitly.)
|
||||
It's great. This is what we expected!
|
||||
We now can safely deliver the result generated by our function to these functions,
|
||||
and don't need to worry about the encoding of we provided string.
|
||||
Because all strings have been converted to \c std::filesystem::path by our function before passing them.
|
||||
|
||||
So, the second line will produce \c "/foo/bar/test"
|
||||
and the third line will produce \c "/foo/bar.txt" in any platforms.
|
||||
|
||||
You may notice std::filesystem::u8path.
|
||||
However it is depracted since C++ 20,
|
||||
because \c std::filesystem::path directly supports UTF8 by \c char8_t since C++ 20.
|
||||
Because C++ standard is volatile, we create this function to have an uniform programming experience.
|
||||
|
||||
\section fs_path_patch__to_utf8_path Extract UTF8 Path String from Path
|
||||
|
||||
YYCC::FsPathPatch::ToUTF8Path provides this feature.
|
||||
It basically is the reversed operation of YYCC::FsPathPatch::FromUTF8Path.
|
||||
It is usually used when you have done all path work in \c std::filesystem::path
|
||||
and want to get the result.
|
||||
There is an example:
|
||||
|
||||
\code
|
||||
auto foobar_path = YYCC::FsPathPatch::FromUTF8Path(YYCC_U8("/foo/bar"));
|
||||
auto result = YYCC::FsPathPatch::ToUTF8Path(foobar_path / YYCC::FsPathPatch::FromUTF8Path(YYCC_U8("test")));
|
||||
\endcode
|
||||
|
||||
*/
|
@ -29,12 +29,22 @@
|
||||
|
||||
\li \subpage intro
|
||||
|
||||
\li \subpage platform_checker
|
||||
|
||||
\li \subpage library_encoding
|
||||
|
||||
\li \subpage encoding_helper
|
||||
|
||||
\li \subpage string_helper
|
||||
|
||||
\li \subpage parser_helper
|
||||
|
||||
\li \subpage console_helper
|
||||
|
||||
\li \subpage io_helper
|
||||
|
||||
\li \subpage fs_path_patch
|
||||
|
||||
<B>Advanced Features</B>
|
||||
|
||||
\li \subpage config_manager
|
||||
@ -46,8 +56,14 @@
|
||||
|
||||
\li \subpage win_import
|
||||
|
||||
\li \subpage com_helper
|
||||
|
||||
\li \subpage dialog_helper
|
||||
|
||||
\li \subpage win_fct_helper
|
||||
|
||||
\li \subpage exception_helper
|
||||
|
||||
</TD>
|
||||
</TR>
|
||||
</TABLE>
|
||||
|
@ -2,14 +2,23 @@
|
||||
|
||||
\page intro Introduction to YYCCommonplace
|
||||
|
||||
YYCCommonplace, or YYC Commonplace (abbr. YYCC), is a static library providing various useful C++ functions when programming with standard library or Windows environment.
|
||||
YYCCommonplace, or YYC Commonplace (abbr. YYCC),
|
||||
is a static library providing various useful C++ functions
|
||||
when programming with standard library or Windows environment.
|
||||
|
||||
Actually YYCC provides the functions which I frequently used in my personal projects.
|
||||
Thus I do not need copy these functions from one project to another project.
|
||||
I can write them once and use them everywhere.
|
||||
It's also good for bug fix.
|
||||
If I found bug in these code, I only need to fix it in this project.
|
||||
Otherwise I need to fix them one by one in each project because they share the same code.
|
||||
During the development of a few projects,
|
||||
I gradually understand how Windows make the compromise with the code written by its old developers,
|
||||
and what is developer wanted in contemporary C++ standard library under Windows environment.
|
||||
So I create this static library for all of my C++ project.
|
||||
After this, I do not need to write these duplicated code in each project.
|
||||
I can use a clear and easy way to manage these codes.
|
||||
I can easily fix issues found in project using this library by updating a single project,
|
||||
rather than fixing these duplicated code in each project one by one
|
||||
because all of them share the same implementations.
|
||||
|
||||
This project mainly is served for my personal use.
|
||||
But I would be honored if you would like to use this in your project.
|
||||
Almost of my projects will gradually adapt to this project and drop their own individual implementations.
|
||||
|
||||
\section intro__why Why YYCCommonplace
|
||||
|
||||
@ -71,6 +80,83 @@ Before using this library, I suggest you read this manual fully to have a full o
|
||||
Otherwise you may make mistake during using this library.
|
||||
I suggest you read this manual from top to bottom in the left tree panel, one by one.
|
||||
|
||||
This library is a static library.
|
||||
YYCC library self provides some build scripts for convenient use which are located in \c script directory.
|
||||
Please note all of these script should be executed in the root of YYCC project, not the script directory
|
||||
(i.e. work directory is the root directory of YYCC).
|
||||
All scripts will try to do a simple check about this if you accidently execute them in a wrong place.
|
||||
|
||||
If you are not willing to use our build script, or our build script went wrong,
|
||||
you can create your personal build script by viewing our build script.
|
||||
|
||||
\subsection intro__usage__linux Linux
|
||||
|
||||
Building YYCC on Linux is easy to do by executing <TT>script/linux_build.sh</TT>.
|
||||
After script done, you will find installation result in directory <TT>bin/install</TT>.
|
||||
Then other CMake project can utilize it (non-CMake project also can utilize this).
|
||||
|
||||
\subsection intro__usage__win Windows
|
||||
|
||||
For building on Windows, there are 2 distribution types which YYCC can create.
|
||||
First is CMake distribution, this distribution is served for other CMake project using.
|
||||
Another one is MSVC distribution, this distribution is served for other MSVC project using.
|
||||
These have different directory layout which is specifically designed for corresponding build tools.
|
||||
See following section for more details.
|
||||
|
||||
\subsubsection intro__usage__win__cmake CMake Distribution
|
||||
|
||||
For creating CMake distribution, please execute script <TT>script/win_build.bat</TT>.
|
||||
After script done, you will find CMake distribution in directory <TT>bin/install</TT> with following structure.
|
||||
|
||||
\verbatim
|
||||
YYCC
|
||||
├─Win32_Debug: Win32 Debug package
|
||||
│ ├─include: Headers
|
||||
│ └─lib: Library for linking and CMake package file
|
||||
├─Win32_Release: Win32 Release package
|
||||
│ ├─bin: Executable testbench
|
||||
│ ├─include: Headers
|
||||
│ └─lib: Library for linking and CMake package file
|
||||
├─x64_Debug: x64 Debug package
|
||||
│ ├─include: Headers
|
||||
│ └─lib: Library for linking and CMake package file
|
||||
└─x64_Release: x64 Release package
|
||||
├─bin: Executable testbench
|
||||
├─include: Headers
|
||||
├─lib: Library for linking and CMake package file
|
||||
└─share: Documentation
|
||||
\endverbatim
|
||||
|
||||
Every different architecture and build type have a single and full directory.
|
||||
CMake project can use one of by adding their build type in \c find_package path.
|
||||
So that CMake will automatically utilize correct package when switching build type.
|
||||
|
||||
\subsubsection intro__usage__win__msvc MSVC Distribution
|
||||
|
||||
Before creating MSVC distribution, you should create CMake distribution first,
|
||||
because MSVC distribution depend on CMake distribution.
|
||||
|
||||
After creating CMake distribution, you can simply create MSVC distribution by executing <TT>script/win_msvc_build.bat</TT>.
|
||||
Then you will find your MSVC distribution in directory <TT>bin/msvc_install</TT> with following structure.
|
||||
|
||||
\verbatim
|
||||
YYCC
|
||||
├─bin
|
||||
│ ├─Win32: Win32 Release testbench
|
||||
│ └─x64: x64 Release testbench
|
||||
├─include: Headers
|
||||
├─lib
|
||||
│ ├─Win32
|
||||
│ │ ├─Debug: Win32 Debug library for linking
|
||||
│ │ └─Release: Win32 Release library for linking
|
||||
│ └─x64
|
||||
│ ├─Debug: x64 Debug library for linking
|
||||
│ └─Release: x64 Release library for linking
|
||||
└─share: Documentation
|
||||
\endverbatim
|
||||
|
||||
The different between MSVC distribution and CMake distribution is
|
||||
that MSVC distribution places all static library under one director \c lib.
|
||||
Thus in MSVC project user can simply spcify the install path of YYCC,
|
||||
and use MSVC macros in path to choose correct static library for linking
|
||||
|
||||
*/
|
||||
|
43
doc/src/io_helper.dox
Normal file
43
doc/src/io_helper.dox
Normal file
@ -0,0 +1,43 @@
|
||||
/**
|
||||
|
||||
\page io_helper IO Helper
|
||||
|
||||
YYCC::IOHelper currently only has one function and one macro.
|
||||
|
||||
\section io_helper__ptr_pri_padding Pointer Print Padding
|
||||
|
||||
When printing pointer on screen, programmer usually left-pad zero to make it looks good.
|
||||
However, the count of zero for padding is different in x86 and x64 architecture (8 for x86 and 16 for x64).
|
||||
Macro \c PRI_XPTR_LEFT_PADDING will help you to resolve this issue.
|
||||
|
||||
Macro \c PRI_XPTR_LEFT_PADDING will be defined to following value according to the target system architecture.
|
||||
|
||||
\li \c "08": On x86 system.
|
||||
\li \c "016": On x64 system.
|
||||
|
||||
There is an example for how to use it:
|
||||
|
||||
\code
|
||||
void* raw_ptr = blabla();
|
||||
std::printf(stdout, "Raw Pointer 0x%" PRI_XPTR_LEFT_PADDING PRIXPTR, raw_ptr);
|
||||
\endcode
|
||||
|
||||
Note \c PRIXPTR is defined by standard library for formatting pointer as hexadecimal style.
|
||||
|
||||
\section io_helper__utf8_fopen UTF8 fopen
|
||||
|
||||
In Windows, standard \c std::fopen can not handle UTF8 file name in common environment.
|
||||
So we create this function to give programmer an universal \c fopen in UTF8 style.
|
||||
|
||||
In Windows platform, this function will try to convert its argument to \c wchar_t
|
||||
and calling Microsoft specific \c _wfopen function to open file.
|
||||
If encoding convertion or \c _wfopen failed, this function will return \c nullptr like \c std::fopen does.
|
||||
In other platforms, it will simply redirect calling to \c std::fopen.
|
||||
|
||||
There is a simple example:
|
||||
|
||||
\code
|
||||
FILE* fs = YYCC::IOHelper::FOpen(YYCC_U8("/path/to/file"), YYCC_U8("rb"));
|
||||
\endcode
|
||||
|
||||
*/
|
@ -59,6 +59,23 @@ I notice standard library change UTF8 related functions frequently and its API a
|
||||
For example, standard library brings \c std::codecvt_utf8 in C++ 11, deprecate it in C++ 17 and even remove it in C++ 26.
|
||||
That's unacceptable! So I create my own UTF8 type to avoid the scenario that standard library remove \c char8_t in future.
|
||||
|
||||
\section library_encoding__concept Concepts
|
||||
|
||||
In following content, you may be face with 2 words: ordinary string and UTF8 string.
|
||||
|
||||
UTF8 string, as its name, is the string encoded with UTF8.
|
||||
The char type of it must is \c yycc_char8_t.
|
||||
(equivalent to \c char8_t after C++ 20.)
|
||||
|
||||
Ordinary string means the plain, native string.
|
||||
The result of C++ string literal without any prefix \c "foo bar" is a rdinary string.
|
||||
The char type of it is \c char.
|
||||
Its encoding depends on compiler and environment.
|
||||
(UTF8 in Linux, or system code page in Windows if UTF8 switch was not enabled in MSVC.)
|
||||
|
||||
For more infomation, please browse CppReference:
|
||||
https://en.cppreference.com/w/cpp/language/string_literal
|
||||
|
||||
\section library_encoding__utf8_literal UTF8 Literal
|
||||
|
||||
String literal is a C++ concept.
|
||||
@ -79,6 +96,24 @@ This macro will do this automatically.
|
||||
In detail, this macro do a \c reinterpret_cast to change the type of given argument to \c const \c yycc_char8_t* forcely.
|
||||
This ensure that declared UTF8 literal is compatible with YYCC UTF8 types.
|
||||
|
||||
\subsection library_encoding__utf8_literal__char Single Char
|
||||
|
||||
Same as UTF8 literal, YYCC allow you cast normal \c char into \c yycc_char8_t as following code:
|
||||
|
||||
\code
|
||||
YYCC_U8_CHAR('A')
|
||||
\endcode
|
||||
|
||||
YYCC_U8_CHAR is a macro.
|
||||
It just simply use \c static_cast to cast given value to \c yycc_char8_t.
|
||||
It doesn't mean that you can cast non-ASCII characters,
|
||||
because the space these characters occupied usually more than the maximum value of \c char.
|
||||
For example, following code is \b invalid:
|
||||
|
||||
\code
|
||||
YYCC_U8_CHAR('文') // INVALID!
|
||||
\endcode
|
||||
|
||||
\subsection library_encoding__utf8_literal__concatenation Literal Concatenation
|
||||
|
||||
YYCC_U8 macro also works for string literal concatenation:
|
||||
@ -123,35 +158,35 @@ char* mutable_utf8 = const_cast<char*>(absolutely_is_utf8); // This is not safe.
|
||||
yycc_char8_t* mutable_converted = YYCC::EncodingHelper::ToUTF8(mutable_utf8);
|
||||
\endcode
|
||||
|
||||
YYCC::EncodingHelper::ToUTF8 has 2 overloads which can handle const and mutable stirng pointer convertion respectively.
|
||||
YYCC::EncodingHelper::ToUTF8 has 2 overloads which can handle constant and mutable stirng pointer convertion respectively.
|
||||
|
||||
YYCC also has ability that convert YYCC UTF8 char type to native char type by YYCC::EncodingHelper::ToNative.
|
||||
YYCC also has ability that convert YYCC UTF8 char type to ordinary char type by YYCC::EncodingHelper::ToOrdinary.
|
||||
Here is an exmaple:
|
||||
|
||||
\code
|
||||
const yycc_char8_t* yycc_utf8 = YYCC_U8("I am UTF8 string.");
|
||||
const char* converted = YYCC::EncodingHelper::ToNative(yycc_utf8);
|
||||
const char* converted = YYCC::EncodingHelper::ToOrdinary(yycc_utf8);
|
||||
|
||||
yycc_char8_t* mutable_yycc_utf8 = const_cast<char*>(yycc_utf8); // Not safe. Also just for example.
|
||||
char* mutable_converted = YYCC::EncodingHelper::ToNative(mutable_yycc_utf8);
|
||||
char* mutable_converted = YYCC::EncodingHelper::ToOrdinary(mutable_yycc_utf8);
|
||||
\endcode
|
||||
|
||||
Same as YYCC::EncodingHelper::ToUTF8, YYCC::EncodingHelper::ToNative also has 2 overloads to handle const and mutable string pointer.
|
||||
Same as YYCC::EncodingHelper::ToUTF8, YYCC::EncodingHelper::ToOrdinary also has 2 overloads to handle constant and mutable string pointer.
|
||||
|
||||
\section library_encoding__utf8_container UTF8 String Container
|
||||
|
||||
String container usually means the standard library string container, such as \c std::string, \c std::wstring, \c std::u32string and etc.
|
||||
|
||||
In many personal project, programmer may use \c std::string everywhere because \c std::u8string may not be presented when writing peoject.
|
||||
How to do convertion between native string container and YYCC UTF8 string container?
|
||||
How to do convertion between ordinary string container and YYCC UTF8 string container?
|
||||
It is definitely illegal that directly do force convertion. Because they may have different class layout.
|
||||
Calm down and I will tell you how to do correct convertion.
|
||||
YYCC provides YYCC::EncodingHelper::ToUTF8 to convert native string container to YYCC UTF8 string container.
|
||||
YYCC provides YYCC::EncodingHelper::ToUTF8 to convert ordinary string container to YYCC UTF8 string container.
|
||||
There is an exmaple:
|
||||
|
||||
\code
|
||||
std::string native_string("I am UTF8");
|
||||
yycc_u8string yycc_string = YYCC::EncodingHelper::ToUTF8(native_string);
|
||||
std::string ordinary_string("I am UTF8");
|
||||
yycc_u8string yycc_string = YYCC::EncodingHelper::ToUTF8(ordinary_string);
|
||||
auto result = YYCC::EncodingHelper::UTF8ToUTF32(yycc_string);
|
||||
\endcode
|
||||
|
||||
@ -160,19 +195,19 @@ However, there is a implicit convertion from \c std::string to \c std::string_vi
|
||||
so you can directly pass a \c std::string instance to it.
|
||||
|
||||
String view will reduce unnecessary memory copy.
|
||||
If you just want to pass native string container to function, and this function accepts \c yycc_u8string_view as its argument,
|
||||
If you just want to pass ordinary string container to function, and this function accepts \c yycc_u8string_view as its argument,
|
||||
you can use alternative YYCC::EncodingHelper::ToUTF8View.
|
||||
|
||||
\code
|
||||
std::string native_string("I am UTF8");
|
||||
yycc_u8string_view yycc_string = YYCC::EncodingHelper::ToUTF8View(native_string);
|
||||
std::string ordinary_string("I am UTF8");
|
||||
yycc_u8string_view yycc_string = YYCC::EncodingHelper::ToUTF8View(ordinary_string);
|
||||
auto result = YYCC::EncodingHelper::UTF8ToUTF32(yycc_string);
|
||||
\endcode
|
||||
|
||||
Comparing with previous one, this example use less memory.
|
||||
The reduced memory is the content of \c yycc_string because string view is a view, not the copy of original string.
|
||||
|
||||
Same as UTF8 string pointer, we also have YYCC::EncodingHelper::ToNative and YYCC::EncodingHelper::ToNativeView do correspondant reverse convertion.
|
||||
Same as UTF8 string pointer, we also have YYCC::EncodingHelper::ToOrdinary and YYCC::EncodingHelper::ToOrdinaryView do correspondant reverse convertion.
|
||||
Try to do your own research and figure out how to use them.
|
||||
It's pretty easy.
|
||||
|
||||
|
80
doc/src/parser_helper.dox
Normal file
80
doc/src/parser_helper.dox
Normal file
@ -0,0 +1,80 @@
|
||||
/**
|
||||
|
||||
\page parser_helper Parser Helper
|
||||
|
||||
This helper is served for the convertion between number and string.
|
||||
|
||||
\section parser_helper_supported_types Supported Types
|
||||
|
||||
Functions located in this helper support the convertion between string and following types:
|
||||
|
||||
\li Integral types (except \c bool): \c int, \c uint32_t, \c char and etc.
|
||||
\li Floating point types: \c float, \c double and etc.
|
||||
\li \c bool
|
||||
|
||||
Please note in C++, \c bool is integral type but we list it individually because parser will treat it specially.
|
||||
For \c bool type, parser will try doing convertion between it and \c "true" \c "false" string.
|
||||
(\b case-sensitive. It means that \c true will only be converted to \c "true" and \c "TRUE" can not be recognised.)
|
||||
|
||||
\section parser_helper__try_parse Try Parse
|
||||
|
||||
YYCC::ParserHelper::TryParse will try to parse string into caller specified type.
|
||||
All of them accept an UTF8 string view at first argument,
|
||||
require that you provide a container receiving converted result in the second argument,
|
||||
and return a bool value to indicate whether the convertion is successful.
|
||||
There are some examples:
|
||||
|
||||
\code
|
||||
uint32_t val;
|
||||
YYCC::ParserHelper::TryParse<uint32_t>(YYCC_U8("123"), val);
|
||||
YYCC::ParserHelper::TryParse<uint32_t>(YYCC_U8("7fff"), val, 16);
|
||||
\endcode
|
||||
|
||||
For integral type, this function allows caller to specify extra argument providing the base of given number string.
|
||||
|
||||
\section parser_helper__parse Parse
|
||||
|
||||
YYCC::ParserHelper::Parse is similar to YYCC::ParserHelper::TryParse.
|
||||
But it will not return bool value to indicate success and doesn't have the argument receiving result.
|
||||
It only accepts an UTF8 string view as the only one argument, and return result directly.
|
||||
If the convertion failed, the return value is \b undefined (but usually is the default value of given type).
|
||||
There is an example:
|
||||
|
||||
\code
|
||||
uint32_t val = YYCC::ParserHelper::Parse<uint32_t>(YYCC_U8("123"));
|
||||
\endcode
|
||||
|
||||
Please note, for integral types, there is no base argument in YYCC::ParserHelper::Parse.
|
||||
Please use YYCC::ParserHelper::TryParse instead.
|
||||
|
||||
Using this function is dangerous if the validation of your input is important.
|
||||
In this case, please use YYCC::ParserHelper::TryParse instead.
|
||||
|
||||
\section parser_helper__to_string To String
|
||||
|
||||
YYCC::ParserHelper::ToString basically is the reversed operation of YYCC::ParserHelper::Parse.
|
||||
It gets the string representation of given type.
|
||||
The only argument of these functions is the type which need to be converted to its string representation.
|
||||
And they will return yycc_u8string as result.
|
||||
There is an example:
|
||||
|
||||
\code
|
||||
auto result = YYCC::ParserHelper::ToString<uint32_t>(UINT32_C(114));
|
||||
\endcode
|
||||
|
||||
\section parser_helper__notes Notes
|
||||
|
||||
All functions within this helper are implementated by standard library functions.
|
||||
These functions just make a good wrapper for complex standard library functions.
|
||||
And give you a experience like C\# parser functions.
|
||||
|
||||
Basically, all functions located in this helper have possibility to throw exception.
|
||||
But this possibility are more close to the possibility that \c new statement throw \c std::bad_alloc.
|
||||
So in most cases you can assume these functions will not throw any exception.
|
||||
|
||||
All functions are template functions.
|
||||
The argument of template is the type these functions need to be processed.
|
||||
Although C++ have \e smart template type deduction,
|
||||
it would be better to specify template argument manually to explicitly specify your desired type.
|
||||
|
||||
*/
|
35
doc/src/platform_checker.dox
Normal file
35
doc/src/platform_checker.dox
Normal file
@ -0,0 +1,35 @@
|
||||
/**
|
||||
|
||||
\page platform_checker Platform Checker
|
||||
|
||||
In many cross platform applications,
|
||||
programmer usually write code adapted to different platforms in one source file
|
||||
and enable them respectively by macros representing the target platform.
|
||||
As a cross platform library,
|
||||
YYCC also has this feature and you can utilize it if you don't have other ways to so the same things.
|
||||
|
||||
\section platform_checker__values Values
|
||||
|
||||
YYCC always define a macro called \c YYCC_OS to indicate the system of target platform.
|
||||
In implementation, it will check following list from top to bottom to set matched value for it.
|
||||
|
||||
\li \c YYCC_OS_WINDOWS: Windows environment. It is done by checking whether environment define \c _WIN32 macro.
|
||||
\li \c YYCC_OS_LINUX: In current implementation, this means target platform is \b NOT Windows.
|
||||
|
||||
\section platform_checker__usage Usage
|
||||
|
||||
Now you know any possible value of \c YYCC_OS.
|
||||
The next step is how to use it to enable specified code in specific target platform.
|
||||
We take Windows platform for example.
|
||||
Assume \c blabla() function is Windows specific.
|
||||
We have following example code:
|
||||
|
||||
\code
|
||||
#if YYCC_OS == YYCC_OS_WINDOWS
|
||||
blabla();
|
||||
#endif
|
||||
\endcode
|
||||
|
||||
It's enough and simple that use \c \#if to bracket the Windows specified code.
|
||||
|
||||
*/
|
@ -2,8 +2,104 @@
|
||||
|
||||
\page string_helper String Helper
|
||||
|
||||
\section string_helper__printf Printf VPrintf
|
||||
|
||||
\section string_helper_lower_upper Lower Upper
|
||||
YYCC::StringHelper provides 4 functions for formatting string.
|
||||
These functions are mainly provided to programmer who can not use C++ 20 \c std::format feature.
|
||||
|
||||
\code
|
||||
bool Printf(yycc_u8string&, const yycc_char8_t*, ...);
|
||||
bool VPrintf(yycc_u8string&, const yycc_char8_t*, va_list argptr);
|
||||
yycc_u8string Printf(const yycc_char8_t*, ...);
|
||||
yycc_u8string VPrintf(const yycc_char8_t*, va_list argptr);
|
||||
\endcode
|
||||
|
||||
YYCC::StringHelper::Printf and YYCC::StringHelper::VPrintf is similar to \c std::sprintf and \c std::vsprintf.
|
||||
YYCC::StringHelper::Printf accepts UTF8 format string and variadic arguments specifying data to print.
|
||||
This is commonly used by programmer.
|
||||
However, YYCC::StringHelper::VPrintf also do the same work but its second argument is \c va_list,
|
||||
the representation of variadic arguments.
|
||||
It is mostly used by other function which has variadic arguments.
|
||||
|
||||
The only difference between these function and standard library functions is
|
||||
that you don't need to worry about whether the space of given buffer is enough,
|
||||
because these functions help you to calculate this internally.
|
||||
|
||||
There is the same design like we introduced in \ref encoding_helper.
|
||||
There are 2 overloads for YYCC::StringHelper::Printf and YYCC::StringHelper::VPrintf respectively.
|
||||
First overload return bool value and require a string container as argument for storing result.
|
||||
The second overload return result string directly.
|
||||
As you expected, first overload will return false if fail to format string (this is barely happened).
|
||||
and second overload will return empty string when formatter failed.
|
||||
|
||||
\section string_helper__replace Replace
|
||||
|
||||
YYCC::StringHelper provide 2 functions for programmer do string replacement:
|
||||
|
||||
\code
|
||||
void Replace(yycc_u8string&, const yycc_char8_t*, const yycc_char8_t*);
|
||||
yycc_u8string Replace(const yycc_char8_t*, const yycc_char8_t*, const yycc_char8_t*);
|
||||
\endcode
|
||||
|
||||
The first overload will do replacement in given string container directly.
|
||||
The second overload will produce a copy of original string and do replacement on the copied string.
|
||||
|
||||
YYCC::StringHelper::Replace has special treatments for following scenarios:
|
||||
|
||||
\li If given string is empty or nullptr, the return value will be empty.
|
||||
\li If the character sequence to be replaced is nullptr or empty string, no replacement will happen.
|
||||
\li If the character sequence will be replaced into string is nullptr or empty, it will simply delete found character sequence from given string.
|
||||
|
||||
\section string_helper__join Join
|
||||
|
||||
YYCC::StringHelper provide an universal way for joining string and various specialized join functions.
|
||||
|
||||
\subsection string_helper__join__universal Universal Join Function
|
||||
|
||||
Because C++ list types are various.
|
||||
There is no unique and convenient way to create an universal join function.
|
||||
So we create YYCC::StringHelper::JoinDataProvider to describe join context.
|
||||
|
||||
Before using universal join function,
|
||||
you should setup YYCC::StringHelper::JoinDataProvider first, the context of join function.
|
||||
It actually is an \c std::function object which can be easily fetched by C++ lambda syntax.
|
||||
This function pointer accept a reference to \c yycc_u8string_view,
|
||||
programmer should set it to the string to be joined when at each calling.
|
||||
And this function pointer return a bool value to indicate the end of join.
|
||||
You can simply return \c false to terminate join process.
|
||||
The argument you assigned to argument will not be taken into join process when you return false.
|
||||
|
||||
Then, you can pass the created YYCC::StringHelper::JoinDataProvider object to YYCC::StringHelper::Join function.
|
||||
And specify decilmer at the same time.
|
||||
Then you can get the final joined string.
|
||||
There is an example:
|
||||
|
||||
\code
|
||||
std::vector<yycc_u8string> data {
|
||||
YYCC_U8(""), YYCC_U8("1"), YYCC_U8("2"), YYCC_U8("")
|
||||
};
|
||||
auto iter = data.cbegin();
|
||||
auto stop = data.cend();
|
||||
auto joined_string = YYCC::StringHelper::Join(
|
||||
[&iter, &stop](yycc_u8string_view& view) -> bool {
|
||||
if (iter == stop) return false;
|
||||
view = *iter;
|
||||
++iter;
|
||||
return true;
|
||||
},
|
||||
decilmer
|
||||
);
|
||||
\endcode
|
||||
|
||||
\subsection string_helper__join__specialized Specialized Join Function
|
||||
|
||||
Despite universal join function,
|
||||
YYCC::StringHelper also provide some specialized join functions for commonly used types.
|
||||
Current we support following join function:
|
||||
|
||||
\li \c std::vector<yycc_u8string>: With an extra option which allow join it with reversed order.
|
||||
|
||||
\section string_helper__lower_upper Lower Upper
|
||||
|
||||
String helper provides Python-like string lower and upper function.
|
||||
Both lower and upper function have 2 overloads:
|
||||
@ -18,7 +114,7 @@ Second overload accepts a mutable string container as argument and will make all
|
||||
You can choose on of them for your flavor and requirements.
|
||||
Upper also has similar 2 overloads.
|
||||
|
||||
\section string_helper_split Split
|
||||
\section string_helper__split Split
|
||||
|
||||
String helper provides Python-like string split function.
|
||||
It has 2 types for you:
|
||||
@ -28,16 +124,16 @@ std::vector<yycc_u8string> Split(const yycc_u8string_view&, const yycc_char8_t*)
|
||||
std::vector<yycc_u8string_view> SplitView(const yycc_u8string_view&, const yycc_char8_t*);
|
||||
\endcode
|
||||
|
||||
All these overloads take a string view as the first argument for the string need to be split.
|
||||
All these overloads take a string view as the first argument representing the string need to be split.
|
||||
The second argument is a raw string pointer representing the decilmer for splitting.
|
||||
The only difference between these 2 split function are overt according to their names.
|
||||
The first split function will return a list of copied string as its split result.
|
||||
The second split function will return a list of string view as its split result,
|
||||
and it will keep valid as long as the life time of your given string view argument.
|
||||
It also means that the last type will cost less memory if you don't need the copy of original string.
|
||||
It also means that the last overload will cost less memory if you don't need the copy of original string.
|
||||
|
||||
If the source string (the string need to be split) is empty, or the decilmer is \c nullptr or empty,
|
||||
the result will only has 1 item and this item is source string itself.
|
||||
There is no way that this method return an empty list, except the code is buggy.
|
||||
There is no way that these methods return an empty list, except the code is buggy.
|
||||
|
||||
*/
|
||||
|
17
doc/src/win_fct_helper.dox
Normal file
17
doc/src/win_fct_helper.dox
Normal file
@ -0,0 +1,17 @@
|
||||
/**
|
||||
|
||||
\page win_fct_helper Windows Function Helper
|
||||
|
||||
This helper give a more convenient way to call Windows functions.
|
||||
|
||||
This namespace is Windows specific.
|
||||
It will be entirely invisible in other platforms.
|
||||
|
||||
Currently this namespace has following functions:
|
||||
|
||||
\li YYCC::WinFctHelper::GetCurrentModule: Get the handle to current module.
|
||||
\li YYCC::WinFctHelper::GetTempDirectory: Get temporary directory in Windows.
|
||||
\li YYCC::WinFctHelper::GetModuleFileName: Get the path to module in file system by given handle.
|
||||
\li YYCC::WinFctHelper::GetLocalAppData: Get the path inside \%LOCALAPPDATA\%
|
||||
|
||||
*/
|
@ -28,7 +28,7 @@ This guard can solve following issues:
|
||||
<LI>
|
||||
Programmer can not use \c std::max and \c std::min normally.
|
||||
<UL>
|
||||
<LI>Windows defines \c MAX and \c MIN as macros for personal use. This is why this happend.</LI>
|
||||
<LI>Windows defines \c MAX and \c MIN as macros for personal use. This is why this happened.</LI>
|
||||
<LI>Guard defines some special macros to tell Windows do not create these 2 macros.</LI>
|
||||
</UL>
|
||||
</LI>
|
||||
@ -36,7 +36,7 @@ This guard can solve following issues:
|
||||
Programmer will not be affected by the automatical rename of \c GetObject, \c GetClassName and etc.
|
||||
<UL>
|
||||
<LI>These are all macros for Windows personal use to automatically redirect calling to A function and W function by compiling environment.</LI>
|
||||
<LI>Guard \c #undef these annoy macros.</LI>
|
||||
<LI>Guard \c \#undef these annoy macros.</LI>
|
||||
</UL>
|
||||
</LI>
|
||||
<LI>
|
||||
@ -56,13 +56,13 @@ Because this guard operate some Windows macros as we introduced above.
|
||||
The headers depending on Windows may throw error if you put them outside of this pair.
|
||||
|
||||
Please note WinImportPrefix.hpp and WinImportSuffix.hpp can be included multiple times.
|
||||
Because they do not have the proprocessor command like <I>#pragma once</I> or etc to make sure they only can be included once.
|
||||
Because they do not have the proprocessor command like <I>\#pragma once</I> or etc to make sure they only can be included once.
|
||||
That's by design. Because we actually may use this pair multiple times.
|
||||
The only thing you should pledge is that you must make sure they are presented by pair.
|
||||
|
||||
This guard is Windows specific.
|
||||
It does nothing if you accidently use it in other platforms such as Linux,
|
||||
because the headers use \c #if to check environment out and will do nothing in non-Windows environment.
|
||||
because the headers use \c \#if to check environment out and will do nothing in non-Windows environment.
|
||||
However, we still highly recommend you use this pair with platform checker bracket like example does,
|
||||
if your program need to be run on multiple platforms.
|
||||
|
||||
|
@ -1,35 +0,0 @@
|
||||
@ECHO OFF
|
||||
SET README_PATH=%CD%\README.md
|
||||
IF EXIST %README_PATH% (
|
||||
REM DO NOTHING
|
||||
) ELSE (
|
||||
ECHO Error: You must run this script at the root folder of this project!
|
||||
EXIT /b
|
||||
)
|
||||
|
||||
:: Create essential folder
|
||||
MKDIR bin
|
||||
CD bin
|
||||
MKDIR Win32
|
||||
MKDIR x64
|
||||
MKDIR install
|
||||
|
||||
:: Build for Win32
|
||||
CD Win32
|
||||
cmake -G "Visual Studio 16 2019" -A Win32 -DYYCC_BUILD_TESTBENCH=ON ../..
|
||||
cmake --build . --config Debug
|
||||
cmake --install . --prefix=../install --config Debug
|
||||
cmake --build . --config Release
|
||||
cmake --install . --prefix=../install --config Release
|
||||
CD ..
|
||||
|
||||
:: Build for x64
|
||||
CD x64
|
||||
cmake -G "Visual Studio 16 2019" -A x64 -DYYCC_BUILD_TESTBENCH=ON ../..
|
||||
cmake --build . --config Debug
|
||||
cmake --install . --prefix=../install --config Debug
|
||||
cmake --build . --config Release
|
||||
cmake --install . --prefix=../install --config Release
|
||||
CD ..
|
||||
|
||||
ECHO DONE
|
32
script/linux_build.sh
Normal file
32
script/linux_build.sh
Normal file
@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
README_PATH=$(pwd)/README.md
|
||||
if [ ! -f "$README_PATH" ]; then
|
||||
echo "Error: You must run this script at the root folder of this project!"
|
||||
exit
|
||||
fi
|
||||
|
||||
# Create main binary directory
|
||||
mkdir bin
|
||||
cd bin
|
||||
# Create build directory
|
||||
mkdir build
|
||||
# Create install directory
|
||||
mkdir install
|
||||
cd install
|
||||
mkdir Debug
|
||||
mkdir Release
|
||||
cd ..
|
||||
|
||||
# Build current system debug and release version
|
||||
cd build
|
||||
cmake -DCMAKE_BUILD_TYPE=Debug ../.. --fresh
|
||||
cmake --build .
|
||||
cmake --install . --prefix ../install/Debug
|
||||
cmake -DCMAKE_BUILD_TYPE=Release -DYYCC_BUILD_TESTBENCH=ON ../.. --fresh
|
||||
cmake --build .
|
||||
cmake --install . --prefix ../install/Release
|
||||
cd ..
|
||||
|
||||
# Exit to original path
|
||||
cd ..
|
||||
echo "Linux CMake Build Done"
|
54
script/win_build.bat
Normal file
54
script/win_build.bat
Normal file
@ -0,0 +1,54 @@
|
||||
@ECHO OFF
|
||||
SET README_PATH=%CD%\README.md
|
||||
IF EXIST %README_PATH% (
|
||||
REM DO NOTHING
|
||||
) ELSE (
|
||||
ECHO Error: You must run this script at the root folder of this project!
|
||||
EXIT /b
|
||||
)
|
||||
|
||||
:: Create main binary directory
|
||||
MKDIR bin
|
||||
CD bin
|
||||
:: Create build folder
|
||||
MKDIR Win32
|
||||
MKDIR x64
|
||||
MKDIR documentation
|
||||
:: Create install folder
|
||||
MKDIR install
|
||||
CD install
|
||||
MKDIR Win32_Debug
|
||||
MKDIR Win32_Release
|
||||
MKDIR x64_Debug
|
||||
MKDIR x64_Release
|
||||
CD ..
|
||||
|
||||
:: Build for Win32
|
||||
CD Win32
|
||||
cmake -G "Visual Studio 16 2019" -A Win32 -DYYCC_BUILD_TESTBENCH=ON ../..
|
||||
cmake --build . --config Debug
|
||||
cmake --install . --prefix=../install/Win32_Debug --config Debug
|
||||
cmake --build . --config Release
|
||||
cmake --install . --prefix=../install/Win32_Release --config Release
|
||||
CD ..
|
||||
|
||||
:: Build for x64
|
||||
CD x64
|
||||
cmake -G "Visual Studio 16 2019" -A x64 -DYYCC_BUILD_TESTBENCH=ON ../..
|
||||
cmake --build . --config Debug
|
||||
cmake --install . --prefix=../install/x64_Debug --config Debug
|
||||
cmake --build . --config Release
|
||||
cmake --install . --prefix=../install/x64_Release --config Release
|
||||
CD ..
|
||||
|
||||
:: Build for documentation
|
||||
CD documentation
|
||||
cmake -G "Visual Studio 16 2019" -A x64 -DYYCC_BUILD_DOC=ON ../..
|
||||
cmake --build . --config Release
|
||||
cmake --build . --target YYCCDocumentation
|
||||
cmake --install . --prefix=../install/x64_Release --config Release
|
||||
CD ..
|
||||
|
||||
:: Exit to original path
|
||||
CD ..
|
||||
ECHO Windows CMake Build Done
|
50
script/win_msvc_build.bat
Normal file
50
script/win_msvc_build.bat
Normal file
@ -0,0 +1,50 @@
|
||||
@ECHO OFF
|
||||
SET README_PATH=%CD%\README.md
|
||||
IF EXIST %README_PATH% (
|
||||
REM DO NOTHING
|
||||
) ELSE (
|
||||
ECHO Error: You must run this script at the root folder of this project!
|
||||
EXIT /b
|
||||
)
|
||||
|
||||
:: Enter main binary directory
|
||||
CD bin
|
||||
|
||||
:: Create MSVC binary directory
|
||||
MKDIR msvc_install
|
||||
CD msvc_install
|
||||
:: Create direcotries tree
|
||||
MKDIR bin
|
||||
MKDIR include
|
||||
MKDIR lib
|
||||
MKDIR share
|
||||
CD bin
|
||||
MKDIR Win32
|
||||
MKDIR x64
|
||||
CD ..
|
||||
CD lib
|
||||
MKDIR Win32\Debug
|
||||
MKDIR Win32\Release
|
||||
MKDIR x64\Debug
|
||||
MKDIR x64\Release
|
||||
CD ..
|
||||
:: Exit MSVC binary directory
|
||||
CD ..
|
||||
|
||||
:: Copy result
|
||||
:: Copy include from x64_Release build
|
||||
XCOPY install\x64_Release\include msvc_install\include\ /E /Y
|
||||
:: Copy document from x64_Release build
|
||||
XCOPY install\x64_Release\share msvc_install\share\ /E /Y
|
||||
:: Copy binary testbench
|
||||
COPY install\Win32_Release\bin\YYCCTestbench.exe msvc_install\bin\Win32\YYCCTestbench.exe /Y
|
||||
COPY install\x64_Release\bin\YYCCTestbench.exe msvc_install\bin\x64\YYCCTestbench.exe /Y
|
||||
:: Copy static library
|
||||
COPY install\Win32_Debug\lib\YYCCommonplace.lib msvc_install\lib\Win32\Debug\YYCCommonplace.lib /Y
|
||||
COPY install\Win32_Release\lib\YYCCommonplace.lib msvc_install\lib\Win32\Release\YYCCommonplace.lib /Y
|
||||
COPY install\x64_Debug\lib\YYCCommonplace.lib msvc_install\lib\x64\Debug\YYCCommonplace.lib /Y
|
||||
COPY install\x64_Release\lib\YYCCommonplace.lib msvc_install\lib\x64\Release\YYCCommonplace.lib /Y
|
||||
|
||||
:: Exit to original path
|
||||
CD ..
|
||||
ECHO Windows MSVC Build Done
|
@ -14,6 +14,8 @@ PRIVATE
|
||||
IOHelper.cpp
|
||||
StringHelper.cpp
|
||||
WinFctHelper.cpp
|
||||
# Natvis (only for MSVC)
|
||||
$<$<CXX_COMPILER_ID:MSVC>:YYCC.natvis>
|
||||
)
|
||||
target_sources(YYCCommonplace
|
||||
PUBLIC
|
||||
@ -72,8 +74,8 @@ PRIVATE
|
||||
# Install binary and headers
|
||||
install(TARGETS YYCCommonplace
|
||||
EXPORT YYCCommonplaceTargets
|
||||
LIBRARY DESTINATION ${YYCC_INSTALL_PATH_LIB}
|
||||
ARCHIVE DESTINATION ${YYCC_INSTALL_PATH_LIB}
|
||||
INCLUDES DESTINATION include
|
||||
FILE_SET HEADERS DESTINATION include
|
||||
LIBRARY DESTINATION ${YYCC_INSTALL_LIB_PATH}
|
||||
ARCHIVE DESTINATION ${YYCC_INSTALL_LIB_PATH}
|
||||
INCLUDES DESTINATION ${YYCC_INSTALL_INCLUDE_PATH}
|
||||
FILE_SET HEADERS DESTINATION ${YYCC_INSTALL_INCLUDE_PATH}
|
||||
)
|
||||
|
@ -10,29 +10,16 @@
|
||||
#include "WinImportSuffix.hpp"
|
||||
|
||||
/**
|
||||
* @brief COM fucntions related namespace.
|
||||
* @brief Windows COM related types and checker.
|
||||
* @details
|
||||
* This namespace is Windows specific and is unavailable on other platforms.
|
||||
* This namespace is Windows specific.
|
||||
* In other platforms, this whole namespace will be unavailable.
|
||||
*
|
||||
* This namespace contain a COM Guard which make sure COM was initialized in current module when loading current module.
|
||||
* It is essential because all calling to COM functions should be under the premise that COM has been initialized.
|
||||
* This guard also will uninitialize COM when unloading this module.
|
||||
*
|
||||
* This namespace also provided various memory-safe types for interacting with COM functions.
|
||||
* Although Microsoft also has similar smart pointer called \c CComPtr.
|
||||
* But this library is eager to hide all Microsoft-related functions calling.
|
||||
* Using \c CComPtr is not corresponding with the philosophy of this library.
|
||||
* So these std-based smart pointer type were created.
|
||||
*
|
||||
* This namespace is used by internal functions as intended.
|
||||
* They should not be used outside of this library.
|
||||
* But if you compel to use them, it is also okey.
|
||||
* See also \ref com_helper.
|
||||
*/
|
||||
namespace YYCC::COMHelper {
|
||||
|
||||
/**
|
||||
* @brief C++ standard deleter for every COM interfaces inheriting IUnknown.
|
||||
*/
|
||||
/// @brief C++ standard deleter for every COM interfaces inheriting IUnknown.
|
||||
class ComPtrDeleter {
|
||||
public:
|
||||
ComPtrDeleter() {}
|
||||
@ -43,15 +30,18 @@ namespace YYCC::COMHelper {
|
||||
}
|
||||
};
|
||||
|
||||
/// @brief Smart unique pointer of \c IFileDialog
|
||||
using SmartIFileDialog = std::unique_ptr<IFileDialog, ComPtrDeleter>;
|
||||
/// @brief Smart unique pointer of \c IFileOpenDialog
|
||||
using SmartIFileOpenDialog = std::unique_ptr<IFileOpenDialog, ComPtrDeleter>;
|
||||
/// @brief Smart unique pointer of \c IShellItem
|
||||
using SmartIShellItem = std::unique_ptr<IShellItem, ComPtrDeleter>;
|
||||
/// @brief Smart unique pointer of \c IShellItemArray
|
||||
using SmartIShellItemArray = std::unique_ptr<IShellItemArray, ComPtrDeleter>;
|
||||
/// @brief Smart unique pointer of \c IShellFolder
|
||||
using SmartIShellFolder = std::unique_ptr<IShellFolder, ComPtrDeleter>;
|
||||
|
||||
/**
|
||||
* @brief C++ standard deleter for almost raw pointer used in COM which need to be free by CoTaskMemFree()
|
||||
*/
|
||||
/// @brief C++ standard deleter for almost raw pointer used in COM which need to be free by CoTaskMemFree()
|
||||
class CoTaskMemDeleter {
|
||||
public:
|
||||
CoTaskMemDeleter() {}
|
||||
@ -61,7 +51,8 @@ namespace YYCC::COMHelper {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/// @brief Smart unique pointer of COM created \c WCHAR sequence.
|
||||
using SmartLPWSTR = std::unique_ptr<std::remove_pointer_t<LPWSTR>, CoTaskMemDeleter>;
|
||||
|
||||
/**
|
||||
|
@ -2,6 +2,7 @@
|
||||
|
||||
#include "EncodingHelper.hpp"
|
||||
#include "IOHelper.hpp"
|
||||
#include <stdexcept>
|
||||
|
||||
namespace YYCC::ConfigManager {
|
||||
|
||||
@ -17,7 +18,11 @@ namespace YYCC::ConfigManager {
|
||||
m_CfgFilePath = cfg_file_path;
|
||||
// assign settings
|
||||
for (auto* setting : settings) {
|
||||
m_Settings.try_emplace(setting->GetName(), setting);
|
||||
auto result = m_Settings.try_emplace(setting->GetName(), setting);
|
||||
if (!result.second) {
|
||||
// if not inserted because duplicated, raise exception
|
||||
throw std::invalid_argument("Duplicated setting name");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -9,11 +9,20 @@
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
#include <cstring>
|
||||
|
||||
/**
|
||||
* @brief Universal configuration manager
|
||||
* @details For how to use this namespace, please see \ref config_manager.
|
||||
*/
|
||||
namespace YYCC::ConfigManager {
|
||||
|
||||
/**
|
||||
* @brief The constraint applied to settings to limit its stored value.
|
||||
* @tparam _Ty The internal data type stroed in corresponding setting.
|
||||
*/
|
||||
template<typename _Ty>
|
||||
struct Constrain {
|
||||
struct Constraint {
|
||||
using CheckFct_t = std::function<bool(const _Ty&)>;
|
||||
//using CorrectFct_t = std::function<_Ty(const _Ty&)>;
|
||||
CheckFct_t m_CheckFct;
|
||||
@ -24,13 +33,23 @@ namespace YYCC::ConfigManager {
|
||||
}
|
||||
};
|
||||
|
||||
namespace ConstrainPresets {
|
||||
/**
|
||||
* @brief The namespace containing functions generating common used constraint.
|
||||
*/
|
||||
namespace ConstraintPresets {
|
||||
|
||||
/**
|
||||
* @brief Get constraint for arithmetic values by minimum and maximum value range.
|
||||
* @tparam _Ty The underlying arithmetic type.
|
||||
* @param[in] min_value The minimum value of range (inclusive).
|
||||
* @param[in] max_value The maximum value of range (inclusive).
|
||||
* @return The generated constraint instance which can be directly applied.
|
||||
*/
|
||||
template<typename _Ty, std::enable_if_t<std::is_arithmetic_v<_Ty> && !std::is_enum_v<_Ty> && !std::is_same_v<_Ty, bool>, int> = 0>
|
||||
Constrain<_Ty> GetNumberRangeConstrain(_Ty min_value, _Ty max_value) {
|
||||
Constraint<_Ty> GetNumberRangeConstraint(_Ty min_value, _Ty max_value) {
|
||||
if (min_value > max_value)
|
||||
throw std::invalid_argument("invalid min max value for NumberRangeConstrain");
|
||||
return Constrain<_Ty> {
|
||||
throw std::invalid_argument("invalid min max value for NumberRangeConstraint");
|
||||
return Constraint<_Ty> {
|
||||
[min_value, max_value](const _Ty& val) -> bool { return (val <= max_value) && (val >= min_value); }
|
||||
/*[min_value, max_value](const _Ty& val) -> _Ty { return std::clamp(val, min_value, max_value); }*/
|
||||
};
|
||||
@ -38,9 +57,15 @@ namespace YYCC::ConfigManager {
|
||||
|
||||
}
|
||||
|
||||
/// @brief The base class of every setting.
|
||||
/// @details Programmer can inherit this class and implement essential to create custom setting.
|
||||
class AbstractSetting {
|
||||
friend class CoreManager;
|
||||
public:
|
||||
/**
|
||||
* @brief Construct a setting
|
||||
* @param[in] name The name of this setting.
|
||||
*/
|
||||
AbstractSetting(const yycc_char8_t* name) : m_Name(), m_RawData() {
|
||||
if (name != nullptr) m_Name = name;
|
||||
}
|
||||
@ -48,28 +73,57 @@ namespace YYCC::ConfigManager {
|
||||
|
||||
// Name interface
|
||||
public:
|
||||
/// @brief Get name of this setting.
|
||||
/// @details Name was used in storing setting in file.
|
||||
const yycc_u8string& GetName() const { return m_Name; }
|
||||
private:
|
||||
yycc_u8string m_Name;
|
||||
|
||||
// User Implementations
|
||||
protected:
|
||||
/// @brief User implemented custom load functions
|
||||
/// @remarks
|
||||
/// In this function, programmer should read data from internal buffer
|
||||
/// and store it to its own another internal variables.
|
||||
/// @return True if success, otherwise false.
|
||||
virtual bool UserLoad() = 0;
|
||||
/// @brief User implemented custom save functions
|
||||
/// @remarks
|
||||
/// In this function, programmer should write data,
|
||||
/// which is stored in another variavle by it own, to internal buffer.
|
||||
/// @return True if success, otherwise false.
|
||||
virtual bool UserSave() = 0;
|
||||
/// @brief User implemented custom reset functions
|
||||
/// @remarks In this function, programmer should reset its internal variable to default value.
|
||||
virtual void UserReset() = 0;
|
||||
|
||||
// Buffer related functions
|
||||
protected:
|
||||
/// @brief Resize internal buffer to given size.
|
||||
/// @remarks It is usually used in UserSave.
|
||||
/// @param[in] new_size The new size of internal buffer.
|
||||
void ResizeData(size_t new_size) { m_RawData.resize(new_size); }
|
||||
/// @brief Get data pointer to internal buffer.
|
||||
/// @remarks It is usually used in UserLoad.
|
||||
const void* GetDataPtr() const { return m_RawData.data(); }
|
||||
/// @brief Get mutable data pointer to internal buffer.
|
||||
/// @remarks It is usually used in UserSave.
|
||||
void* GetDataPtr() { return m_RawData.data(); }
|
||||
/// @brief Get the length of internal buffer.
|
||||
size_t GetDataSize() const { return m_RawData.size(); }
|
||||
private:
|
||||
std::vector<uint8_t> m_RawData;
|
||||
};
|
||||
|
||||
|
||||
/// @brief Settings manager and config file reader writer.
|
||||
class CoreManager {
|
||||
public:
|
||||
/**
|
||||
* @brief Build core manager.
|
||||
* @param[in] cfg_file_path The path to config file.
|
||||
* @param[in] version_identifier The identifier of version. Higher is newer. Lower config will try doing migration.
|
||||
* @param[in] settings An initializer list containing pointers to all managed settings.
|
||||
*/
|
||||
CoreManager(
|
||||
const yycc_char8_t* cfg_file_path,
|
||||
uint64_t version_identifier,
|
||||
@ -78,8 +132,14 @@ namespace YYCC::ConfigManager {
|
||||
|
||||
// Core functions
|
||||
public:
|
||||
/// @brief Load settings from file.
|
||||
/// @details Before loading, all settings will be reset to default value first.
|
||||
/// @return True if success, otherwise false.
|
||||
bool Load();
|
||||
/// @brief Save settings to file.
|
||||
/// @return True if success, otherwise false.
|
||||
bool Save();
|
||||
/// @brief Reset all settings to default value.
|
||||
void Reset();
|
||||
|
||||
private:
|
||||
@ -93,17 +153,33 @@ namespace YYCC::ConfigManager {
|
||||
|
||||
#pragma region Setting Presets
|
||||
|
||||
/**
|
||||
* @brief Arithmetic (integral, floating point, bool) and enum type setting
|
||||
* @tparam _Ty The internal stored type belongs to arithmetic type.
|
||||
*/
|
||||
template<typename _Ty, std::enable_if_t<std::is_arithmetic_v<_Ty> || std::is_enum_v<_Ty>, int> = 0>
|
||||
class NumberSetting : public AbstractSetting {
|
||||
public:
|
||||
NumberSetting(const yycc_char8_t* name, _Ty default_value, Constrain<_Ty> constrain = Constrain<_Ty> {}) :
|
||||
AbstractSetting(name), m_Data(default_value), m_DefaultData(default_value), m_Constrain(constrain) {}
|
||||
/**
|
||||
* @brief Construct arithmetic type setting.
|
||||
* @param[in] name The name of this setting.
|
||||
* @param[in] default_value The default value of this setting.
|
||||
* @param[in] constraint The constraint applied to this setting.
|
||||
*/
|
||||
NumberSetting(const yycc_char8_t* name, _Ty default_value, Constraint<_Ty> constraint = Constraint<_Ty> {}) :
|
||||
AbstractSetting(name), m_Data(default_value), m_DefaultData(default_value), m_Constraint(constraint) {}
|
||||
virtual ~NumberSetting() {}
|
||||
|
||||
|
||||
/// @brief Get stored data in setting.
|
||||
_Ty Get() const { return m_Data; }
|
||||
bool Set(_Ty new_data) {
|
||||
/**
|
||||
* @brief Set data to setting.
|
||||
* @param[in] new_data The new data.
|
||||
* @return True if success, otherwise false (given value is invalid)
|
||||
*/
|
||||
bool Set(_Ty new_data) {
|
||||
// validate data
|
||||
if (m_Constrain.IsValid() && !m_Constrain.m_CheckFct(new_data))
|
||||
if (m_Constraint.IsValid() && !m_Constraint.m_CheckFct(new_data))
|
||||
return false;
|
||||
// assign data
|
||||
m_Data = new_data;
|
||||
@ -117,7 +193,7 @@ namespace YYCC::ConfigManager {
|
||||
return false;
|
||||
m_Data = *reinterpret_cast<const _Ty*>(GetDataPtr());
|
||||
// check data
|
||||
if (m_Constrain.IsValid() && !m_Constrain.m_CheckFct(m_Data))
|
||||
if (m_Constraint.IsValid() && !m_Constraint.m_CheckFct(m_Data))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
@ -132,26 +208,35 @@ namespace YYCC::ConfigManager {
|
||||
}
|
||||
|
||||
_Ty m_Data, m_DefaultData;
|
||||
Constrain<_Ty> m_Constrain;
|
||||
Constraint<_Ty> m_Constraint;
|
||||
};
|
||||
|
||||
/// @brief String type setting
|
||||
class StringSetting : public AbstractSetting {
|
||||
public:
|
||||
StringSetting(const yycc_char8_t* name, const yycc_char8_t* default_value, Constrain<yycc_u8string> constrain = Constrain<yycc_u8string> {}) :
|
||||
AbstractSetting(name), m_Data(), m_DefaultData(), m_Constrain(constrain) {
|
||||
if (default_value != nullptr) {
|
||||
m_Data = default_value;
|
||||
m_DefaultData = default_value;
|
||||
}
|
||||
/**
|
||||
* @brief Construct string setting
|
||||
* @param[in] name The name of this setting.
|
||||
* @param[in] default_value The default value of this setting.
|
||||
* @param[in] constraint The constraint applied to this setting.
|
||||
*/
|
||||
StringSetting(const yycc_char8_t* name, const yycc_u8string_view& default_value, Constraint<yycc_u8string_view> constraint = Constraint<yycc_u8string_view> {}) :
|
||||
AbstractSetting(name), m_Data(), m_DefaultData(), m_Constraint(constraint) {
|
||||
m_Data = default_value;
|
||||
m_DefaultData = default_value;
|
||||
}
|
||||
virtual ~StringSetting() {}
|
||||
|
||||
|
||||
/// @brief Get reference to stored string.
|
||||
const yycc_u8string& Get() const { return m_Data; }
|
||||
bool Set(const yycc_char8_t* new_data) {
|
||||
/**
|
||||
* @brief Set string data to setting.
|
||||
* @param[in] new_data The new string data.
|
||||
* @return True if success, otherwise false (given value is invalid)
|
||||
*/
|
||||
bool Set(const yycc_u8string_view& new_data) {
|
||||
// check data validation
|
||||
if (new_data == nullptr)
|
||||
return false;
|
||||
if (m_Constrain.IsValid() && !m_Constrain.m_CheckFct(m_Data))
|
||||
if (m_Constraint.IsValid() && !m_Constraint.m_CheckFct(new_data))
|
||||
return false;
|
||||
// assign data
|
||||
m_Data = new_data;
|
||||
@ -173,7 +258,7 @@ namespace YYCC::ConfigManager {
|
||||
string_length
|
||||
);
|
||||
// check data
|
||||
if (m_Constrain.IsValid() && !m_Constrain.m_CheckFct(m_Data))
|
||||
if (m_Constraint.IsValid() && !m_Constraint.m_CheckFct(m_Data))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
@ -194,7 +279,7 @@ namespace YYCC::ConfigManager {
|
||||
}
|
||||
|
||||
yycc_u8string m_Data, m_DefaultData;
|
||||
Constrain<yycc_u8string> m_Constrain;
|
||||
Constraint<yycc_u8string_view> m_Constraint;
|
||||
};
|
||||
|
||||
#pragma endregion
|
||||
|
@ -226,7 +226,7 @@ namespace YYCC::ConsoleHelper {
|
||||
WinConsoleWrite(strl, bIsErr);
|
||||
#else
|
||||
// in linux, directly use C function to write.
|
||||
std::fputs(EncodingHelper::ToNative(strl.c_str()), bIsErr ? stderr : stdout);
|
||||
std::fputs(EncodingHelper::ToOrdinary(strl.c_str()), bIsErr ? stderr : stdout);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
@ -5,170 +5,158 @@
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @brief The namespace providing universal Console visiting functions like C-Sharp Console class.
|
||||
* @brief The helper providing universal C\# style console function and other console related stuff
|
||||
* @details
|
||||
* \par Why this Namespace
|
||||
* Windows console doesn't support UTF8 very well.
|
||||
* The standard input output functions can not work properly on Windows with UTF8.
|
||||
* So we create this namespace and provide various console-related functions
|
||||
* to patch Windows console and let it more like the console in other platforms.
|
||||
* \par
|
||||
* The function provided in this function can be called in any platforms.
|
||||
* In Windows, the implementation will use Windows native function,
|
||||
* and in other platform, the implementation will redirect request to standard C function
|
||||
* like std::fputs and etc.
|
||||
* So the programmer do not need to be worried about which function should they use,
|
||||
* and don't need to use macro to use different IO function in different platforms.
|
||||
* It is just enough that fully use the functions provided in this namespace.
|
||||
* \par
|
||||
* All IO functions this namespace provided are UTF8-based.
|
||||
* It also means that input output string should always be UTF8 encoded.
|
||||
*
|
||||
* \par Input Functions
|
||||
* Please note that EOL will automatically converted into LF on Windows platform, not CRLF.
|
||||
* This action actually is removing all CR chars in result string.
|
||||
* This behavior affect nothing in most cases but it still is possible break something in some special case.
|
||||
* \par
|
||||
* Due to implementation, if you decide to use this function,
|
||||
* you should give up using any other function to read stdin stream,
|
||||
* such as std::gets() and std::cin.
|
||||
* Because this function may read chars which is more than needed.
|
||||
* These extra chars will be stored in this function and can be used next calling.
|
||||
* But these chars can not be visited by stdin again.
|
||||
* This behavior may cause bug.
|
||||
* So if you decide using this function, stick on it and do not change.
|
||||
* \par
|
||||
* Due to implementation, this function do not support hot switch of stdin.
|
||||
* It means that stdin can be redirected before first calling of this function,
|
||||
* but it should not be redirected during program running.
|
||||
* The reason is the same one introduced above.
|
||||
*
|
||||
* \par Output Functions
|
||||
* In current implementation, EOL will not be converted automatically to CRLF.
|
||||
* This is different with other stream read functions provided in this namespace.
|
||||
* \par
|
||||
* Comparing with other stream read functions provided in this namespace,
|
||||
* stream write function support hot switch of stdout and stderr.
|
||||
* Because they do not have internal buffer storing something.
|
||||
* \par
|
||||
* In this namespace, there are various stream write function.
|
||||
* There is a list telling you how to choose one from them for using:
|
||||
* \li Functions with leading "Err" will write data into stderr,
|
||||
* otherwise they will write data into stdout.
|
||||
* \li Functions with embedded "Format" are output functions with format feature
|
||||
* like std::fprintf(), otherwise the functions with embedded "Write" will
|
||||
* only write plain string like std::fputs().
|
||||
* \li Functions with trailing "Line" will write extra EOL to break current line.
|
||||
* This is commonly used, otherwise functions will only write the text provided by arguments,
|
||||
* without adding something.
|
||||
* For how to utilize this functions provided by this namespace, please view \ref console_helper.
|
||||
*/
|
||||
namespace YYCC::ConsoleHelper {
|
||||
|
||||
/// @brief The head of ASCII escape code of black color.
|
||||
#define YYCC_COLORHDR_BLACK "\033[30m"
|
||||
/// @brief The head of ASCII escape code of red color.
|
||||
#define YYCC_COLORHDR_RED "\033[31m"
|
||||
/// @brief The head of ASCII escape code of green color.
|
||||
#define YYCC_COLORHDR_GREEN "\033[32m"
|
||||
/// @brief The head of ASCII escape code of yellow color.
|
||||
#define YYCC_COLORHDR_YELLOW "\033[33m"
|
||||
/// @brief The head of ASCII escape code of blue color.
|
||||
#define YYCC_COLORHDR_BLUE "\033[34m"
|
||||
/// @brief The head of ASCII escape code of magenta color.
|
||||
#define YYCC_COLORHDR_MAGENTA "\033[35m"
|
||||
/// @brief The head of ASCII escape code of cyan color.
|
||||
#define YYCC_COLORHDR_CYAN "\033[36m"
|
||||
/// @brief The head of ASCII escape code of white color.
|
||||
#define YYCC_COLORHDR_WHITE "\033[37m"
|
||||
|
||||
|
||||
/// @brief The head of ASCII escape code of light black color.
|
||||
#define YYCC_COLORHDR_LIGHT_BLACK "\033[90m"
|
||||
/// @brief The head of ASCII escape code of light red color.
|
||||
#define YYCC_COLORHDR_LIGHT_RED "\033[91m"
|
||||
/// @brief The head of ASCII escape code of light green color.
|
||||
#define YYCC_COLORHDR_LIGHT_GREEN "\033[92m"
|
||||
/// @brief The head of ASCII escape code of light yellow color.
|
||||
#define YYCC_COLORHDR_LIGHT_YELLOW "\033[93m"
|
||||
/// @brief The head of ASCII escape code of light blue color.
|
||||
#define YYCC_COLORHDR_LIGHT_BLUE "\033[94m"
|
||||
/// @brief The head of ASCII escape code of light magenta color.
|
||||
#define YYCC_COLORHDR_LIGHT_MAGENTA "\033[95m"
|
||||
/// @brief The head of ASCII escape code of light cyan color.
|
||||
#define YYCC_COLORHDR_LIGHT_CYAN "\033[96m"
|
||||
/// @brief The head of ASCII escape code of light white color.
|
||||
#define YYCC_COLORHDR_LIGHT_WHITE "\033[97m"
|
||||
|
||||
|
||||
/// @brief The tail of ASCII escape code of every color.
|
||||
#define YYCC_COLORTAIL "\033[0m"
|
||||
|
||||
|
||||
|
||||
/// @brief The ASCII escape code pair of black color.
|
||||
#define YYCC_COLOR_BLACK(T) "\033[30m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of red color.
|
||||
#define YYCC_COLOR_RED(T) "\033[31m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of green color.
|
||||
#define YYCC_COLOR_GREEN(T) "\033[32m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of yellow color.
|
||||
#define YYCC_COLOR_YELLOW(T) "\033[33m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of blue color.
|
||||
#define YYCC_COLOR_BLUE(T) "\033[34m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of magenta color.
|
||||
#define YYCC_COLOR_MAGENTA(T) "\033[35m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of cyan color.
|
||||
#define YYCC_COLOR_CYAN(T) "\033[36m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of white color.
|
||||
#define YYCC_COLOR_WHITE(T) "\033[37m" T "\033[0m"
|
||||
|
||||
|
||||
/// @brief The ASCII escape code pair of light black color.
|
||||
#define YYCC_COLOR_LIGHT_BLACK(T) "\033[90m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of light red color.
|
||||
#define YYCC_COLOR_LIGHT_RED(T) "\033[91m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of light green color.
|
||||
#define YYCC_COLOR_LIGHT_GREEN(T) "\033[92m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of light yellow color.
|
||||
#define YYCC_COLOR_LIGHT_YELLOW(T) "\033[93m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of light blue color.
|
||||
#define YYCC_COLOR_LIGHT_BLUE(T) "\033[94m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of light magenta color.
|
||||
#define YYCC_COLOR_LIGHT_MAGENTA(T) "\033[95m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of light cyan color.
|
||||
#define YYCC_COLOR_LIGHT_CYAN(T) "\033[96m" T "\033[0m"
|
||||
/// @brief The ASCII escape code pair of light white color.
|
||||
#define YYCC_COLOR_LIGHT_WHITE(T) "\033[97m" T "\033[0m"
|
||||
|
||||
/**
|
||||
* @brief Enable Windows console color support.
|
||||
* @details This actually is enable virtual console feature for stdout and stderr.
|
||||
* @brief Enable console color support for Windows.
|
||||
* @details This actually is enable virtual console feature for \c stdout and \c stderr.
|
||||
* @return True if success, otherwise false.
|
||||
* @remarks This function only works on Windows and do nothing on other platforms such as Linux,
|
||||
* @remarks
|
||||
* This function only works on Windows and do nothing on other platforms such as Linux,
|
||||
* because we assume all terminals existing on other platform support color feature as default.
|
||||
*/
|
||||
bool EnableColorfulConsole();
|
||||
|
||||
/**
|
||||
* @brief Universal console read function
|
||||
* @brief Reads the next line of UTF8 characters from the standard input stream.
|
||||
* @return
|
||||
* The UTF8 encoded string this function read. EOL is excluded.
|
||||
* The next line of UTF8 characters from the input stream.
|
||||
* Empty string if user just press Enter key or function failed.
|
||||
* @remarks
|
||||
* This function is more like C# Console.ReadLine().
|
||||
* It read user input with UTF8 encoding until reaching EOL.
|
||||
* \par
|
||||
* This function also can be used as ordering user press Enter key by
|
||||
* simply calling this function and ignoring its return value.
|
||||
*/
|
||||
yycc_u8string ReadLine();
|
||||
|
||||
/**
|
||||
* @brief Universal console write function with format feature.
|
||||
* @brief
|
||||
* Writes the text representation of the specified object
|
||||
* to the standard output stream using the specified format information.
|
||||
* @param[in] u8_fmt The format string.
|
||||
* @param[in] ... The arguments to be formatted.
|
||||
* @param[in] ... The arguments of format string.
|
||||
*/
|
||||
void Format(const yycc_char8_t* u8_fmt, ...);
|
||||
/**
|
||||
* @brief Universal console write function with format and auto EOL feature.
|
||||
* @brief
|
||||
* Writes the text representation of the specified object,
|
||||
* followed by the current line terminator,
|
||||
* to the standard output stream using the specified format information.
|
||||
* @param[in] u8_fmt The format string.
|
||||
* @param[in] ... The arguments to be formatted.
|
||||
* @param[in] ... The arguments of format string.
|
||||
*/
|
||||
void FormatLine(const yycc_char8_t* u8_fmt, ...);
|
||||
/**
|
||||
* @brief Universal console write function.
|
||||
* @param[in] u8_strl The string to be written.
|
||||
* @brief Writes the specified string value to the standard output stream.
|
||||
* @param[in] u8_strl The value to write.
|
||||
*/
|
||||
void Write(const yycc_char8_t* u8_strl);
|
||||
/**
|
||||
* @brief Universal console write function with auto EOL feature.
|
||||
* @param[in] u8_strl The string to be written.
|
||||
* @brief
|
||||
* Writes the specified string value, followed by the current line terminator,
|
||||
* to the standard output stream.
|
||||
* @param[in] u8_strl The value to write.
|
||||
*/
|
||||
void WriteLine(const yycc_char8_t* u8_strl);
|
||||
|
||||
/**
|
||||
* @brief Universal console error write function with format and feature.
|
||||
* @brief
|
||||
* Writes the text representation of the specified object
|
||||
* to the standard error stream using the specified format information.
|
||||
* @param[in] u8_fmt The format string.
|
||||
* @param[in] ... The arguments to be formatted.
|
||||
* @param[in] ... The arguments of format string.
|
||||
*/
|
||||
void ErrFormat(const yycc_char8_t* u8_fmt, ...);
|
||||
/**
|
||||
* @brief Universal console error write function with format and auto EOL feature.
|
||||
* @brief
|
||||
* Writes the text representation of the specified object,
|
||||
* followed by the current line terminator,
|
||||
* to the standard error stream using the specified format information.
|
||||
* @param[in] u8_fmt The format string.
|
||||
* @param[in] ... The arguments to be formatted.
|
||||
* @param[in] ... The arguments of format string.
|
||||
*/
|
||||
void ErrFormatLine(const yycc_char8_t* u8_fmt, ...);
|
||||
/**
|
||||
* @brief Universal console error write function.
|
||||
* @param[in] u8_strl The string to be written.
|
||||
* @brief Writes the specified string value to the standard error stream.
|
||||
* @param[in] u8_strl The value to write.
|
||||
*/
|
||||
void ErrWrite(const yycc_char8_t* u8_strl);
|
||||
/**
|
||||
* @brief Universal console error write function with auto EOL feature.
|
||||
* @param[in] u8_strl The string to be written.
|
||||
* @brief
|
||||
* Writes the specified string value, followed by the current line terminator,
|
||||
* to the standard error stream.
|
||||
* @param[in] u8_strl The value to write.
|
||||
*/
|
||||
void ErrWriteLine(const yycc_char8_t* u8_strl);
|
||||
|
||||
|
@ -12,11 +12,19 @@
|
||||
#include <shlobj_core.h>
|
||||
#include "WinImportSuffix.hpp"
|
||||
|
||||
/**
|
||||
* @brief The namespace providing Windows universal dialog features.
|
||||
* @details
|
||||
* This namespace only available on Windows platform.
|
||||
* See also \ref dialog_helper.
|
||||
*/
|
||||
namespace YYCC::DialogHelper {
|
||||
|
||||
/**
|
||||
* @brief The class represent the file types region in file dialog
|
||||
* @details THis class is specific for Windows use, not user oriented.
|
||||
* @brief The class representing the file types region in file dialog.
|
||||
* @details
|
||||
* This class is served for Windows used.
|
||||
* Programmer should \b not create this class manually.
|
||||
*/
|
||||
class WinFileFilters {
|
||||
friend class FileFilters;
|
||||
@ -24,9 +32,11 @@ namespace YYCC::DialogHelper {
|
||||
public:
|
||||
WinFileFilters() : m_WinFilters(), m_WinDataStruct(nullptr) {}
|
||||
|
||||
/// @brief Get the count of available file filters
|
||||
UINT GetFilterCount() const {
|
||||
return static_cast<UINT>(m_WinFilters.size());
|
||||
}
|
||||
/// @brief Get pointer to Windows used file filters declarations
|
||||
const COMDLG_FILTERSPEC* GetFilterSpecs() const {
|
||||
return m_WinDataStruct.get();
|
||||
}
|
||||
@ -39,6 +49,7 @@ namespace YYCC::DialogHelper {
|
||||
std::vector<WinFilterPair> m_WinFilters;
|
||||
std::unique_ptr<COMDLG_FILTERSPEC[]> m_WinDataStruct;
|
||||
|
||||
/// @brief Clear all current file filters
|
||||
void Clear() {
|
||||
m_WinDataStruct.reset();
|
||||
m_WinFilters.clear();
|
||||
@ -46,9 +57,12 @@ namespace YYCC::DialogHelper {
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The class represent the file types region in file dialog.
|
||||
* @details This class is user oriented. User can use function manipulate file types
|
||||
* and final generation function will produce Windows-understood data struct from this.
|
||||
* @brief The class representing the file types region in file dialog.
|
||||
* @details
|
||||
* This class is served for programmer using.
|
||||
* But you don't need create it on your own.
|
||||
* You can simply fetch it by FileDialog::ConfigreFileTypes ,
|
||||
* because this class is a part of FileDialog.
|
||||
*/
|
||||
class FileFilters {
|
||||
public:
|
||||
@ -56,31 +70,34 @@ namespace YYCC::DialogHelper {
|
||||
|
||||
/**
|
||||
* @brief Add a filter pair in file types list.
|
||||
* @param filter_name[in] The friendly name of the filter.
|
||||
* @param il[in] A C++ initialize list.
|
||||
* Every entries must be `const yycc_char8_t*` represent a single filter pattern.
|
||||
* @param[in] filter_name The friendly name of the filter.
|
||||
* @param[in] il
|
||||
* A C++ initialize list containing acceptable file filter pattern.
|
||||
* Every entries must be `const yycc_char8_t*` representing a single filter pattern.
|
||||
* The list at least should have one valid pattern.
|
||||
* This function will not validate these filter patterns, so please write them carefully.
|
||||
* @return True if added success, otherwise false.
|
||||
* @remarks This function allow you register multiple filter patterns for single friendly name.
|
||||
* For example: `Add("Microsoft Word (*.doc; *.docx)", {"*.doc", "*.docx"})`
|
||||
* @remarks
|
||||
* This function allow you register multiple filter patterns for single friendly name.
|
||||
* For example: <TT>Add(u8"Microsoft Word (*.doc; *.docx)", {u8"*.doc", u8"*.docx"})</TT>
|
||||
*/
|
||||
bool Add(const yycc_char8_t* filter_name, std::initializer_list<const yycc_char8_t*> il);
|
||||
/**
|
||||
* @brief Clear filter pairs for following re-use.
|
||||
*/
|
||||
void Clear() { m_Filters.clear(); }
|
||||
/**
|
||||
* @brief Get the count of added filter pairs.
|
||||
* @return The count of already added filter pairs.
|
||||
*/
|
||||
size_t Count() const { return m_Filters.size(); }
|
||||
|
||||
/// @brief Clear filter pairs for following re-use.
|
||||
void Clear() { m_Filters.clear(); }
|
||||
|
||||
/**
|
||||
* @brief Generate Windows dialog system used data struct.
|
||||
* @param win_result[out] The class holding the generated filter data struct.
|
||||
* @return True if generation is success, otherwise false.
|
||||
* @remarks User should not call this function, this function is used in internal code.
|
||||
* @param[out] win_result The class receiving the generated filter data struct.
|
||||
* @return True if generation success, otherwise false.
|
||||
* @remarks
|
||||
* Programmer should not call this function,
|
||||
* this function is used as YYCC internal code.
|
||||
*/
|
||||
bool Generate(WinFileFilters& win_result) const;
|
||||
|
||||
@ -93,8 +110,10 @@ namespace YYCC::DialogHelper {
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The class represent the file dialog
|
||||
* @details THis class is specific for Windows use, not user oriented.
|
||||
* @brief The class representing the file dialog.
|
||||
* @details
|
||||
* This class is served for Windows used.
|
||||
* Programmer should \b not create this class manually.
|
||||
*/
|
||||
class WinFileDialog {
|
||||
friend class FileDialog;
|
||||
@ -105,18 +124,28 @@ namespace YYCC::DialogHelper {
|
||||
m_HasTitle(false), m_HasInitFileName(false), m_WinTitle(), m_WinInitFileName(),
|
||||
m_WinInitDirectory(nullptr) {}
|
||||
|
||||
/// @brief Get whether this dialog has owner.
|
||||
bool HasOwner() const { return m_WinOwner != NULL; }
|
||||
/// @brief Get the \c HWND of dialog owner.
|
||||
HWND GetOwner() const { return m_WinOwner; }
|
||||
|
||||
|
||||
/// @brief Get the struct holding Windows used file filters data.
|
||||
const WinFileFilters& GetFileTypes() const { return m_WinFileTypes; }
|
||||
/// @brief Get the index of default selected file filter.
|
||||
UINT GetDefaultFileTypeIndex() const { return m_WinDefaultFileTypeIndex; }
|
||||
|
||||
|
||||
/// @brief Get whether dialog has custom title.
|
||||
bool HasTitle() const { return m_HasTitle; }
|
||||
/// @brief Get custom title of dialog.
|
||||
const wchar_t* GetTitle() const { return m_WinTitle.c_str(); }
|
||||
/// @brief Get whether dialog has custom initial file name.
|
||||
bool HasInitFileName() const { return m_HasInitFileName; }
|
||||
/// @brief Get custom initial file name of dialog
|
||||
const wchar_t* GetInitFileName() const { return m_WinInitFileName.c_str(); }
|
||||
|
||||
|
||||
/// @brief Get whether dialog has custom initial directory.
|
||||
bool HasInitDirectory() const { return m_WinInitDirectory.get() != nullptr; }
|
||||
/// @brief Get custom initial directory of dialog.
|
||||
IShellItem* GetInitDirectory() const { return m_WinInitDirectory.get(); }
|
||||
|
||||
protected:
|
||||
@ -124,15 +153,17 @@ namespace YYCC::DialogHelper {
|
||||
WinFileFilters m_WinFileTypes;
|
||||
/**
|
||||
* @brief The default selected file type in dialog
|
||||
* @remarks This is 1-based index according to Windows specification.
|
||||
* In other words, you should plus 1 for this index when generating this struct from
|
||||
* user oriented file dialog parameters.
|
||||
* @remarks
|
||||
* This is 1-based index according to Windows specification.
|
||||
* In other words, when generating this struct from FileDialog to this struct this field should plus 1.
|
||||
* Because the same field located in FileDialog is 0-based index.
|
||||
*/
|
||||
UINT m_WinDefaultFileTypeIndex;
|
||||
bool m_HasTitle, m_HasInitFileName;
|
||||
std::wstring m_WinTitle, m_WinInitFileName;
|
||||
COMHelper::SmartIShellItem m_WinInitDirectory;
|
||||
|
||||
|
||||
/// @brief Clear all data and reset them to default value.
|
||||
void Clear() {
|
||||
m_WinOwner = nullptr;
|
||||
m_WinFileTypes.Clear();
|
||||
@ -145,9 +176,10 @@ namespace YYCC::DialogHelper {
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The class represent the file dialog.
|
||||
* @details This class is user oriented. User can use function manipulate file dialog properties
|
||||
* and final generation function will produce Windows-understood data struct from this.
|
||||
* @brief The class representing the file dialog.
|
||||
* @details
|
||||
* This class is served for programming using to describe every aspectes of the dialog.
|
||||
* For how to use this struct, see \ref dialog_helper.
|
||||
*/
|
||||
class FileDialog {
|
||||
public:
|
||||
@ -158,27 +190,55 @@ namespace YYCC::DialogHelper {
|
||||
m_Title(), m_InitFileName(), m_InitDirectory(),
|
||||
m_HasTitle(false), m_HasInitFileName(false), m_HasInitDirectory(false) {}
|
||||
|
||||
/**
|
||||
* @brief Set the owner of dialog.
|
||||
* @param[in] owner The \c HWND pointing to the owner of dialog, or NULL to remove owner.
|
||||
*/
|
||||
void SetOwner(HWND owner) { m_Owner = owner; }
|
||||
/**
|
||||
* @brief Set custom title of dialog
|
||||
* @param[in] title The string pointer to custom title, or nullptr to remove it.
|
||||
*/
|
||||
void SetTitle(const yycc_char8_t* title) {
|
||||
if (m_HasTitle = title != nullptr)
|
||||
m_Title = title;
|
||||
}
|
||||
/**
|
||||
* @brief Fetch the struct describing file filters for future configuration.
|
||||
* @return The reference to the struct describing file filters.
|
||||
*/
|
||||
FileFilters& ConfigreFileTypes() {
|
||||
return m_FileTypes;
|
||||
}
|
||||
/**
|
||||
* @brief Set the index of default selected file filter.
|
||||
* @param[in] idx
|
||||
* The index to default one.
|
||||
* This must be a valid index in file filters.
|
||||
*/
|
||||
void SetDefaultFileTypeIndex(size_t idx) { m_DefaultFileTypeIndex = idx; }
|
||||
/**
|
||||
* @brief Set the initial file name of dialog
|
||||
* @details If set, the file name will always be same one when opening dialog.
|
||||
* @param[in] init_filename String pointer to initial file name, or nullptr to remove it.
|
||||
*/
|
||||
void SetInitFileName(const yycc_char8_t* init_filename) {
|
||||
if (m_HasInitFileName = init_filename != nullptr)
|
||||
m_InitFileName = init_filename;
|
||||
}
|
||||
/**
|
||||
* @brief Set the initial directory of dialog
|
||||
* @details If set, the opended directory will always be the same one when opening dialog
|
||||
* @param[in] init_dir
|
||||
* String pointer to initial directory.
|
||||
* Invalid path or nullptr will remove this feature.
|
||||
*/
|
||||
void SetInitDirectory(const yycc_char8_t* init_dir) {
|
||||
if (m_HasInitDirectory = init_dir != nullptr)
|
||||
m_InitDirectory = init_dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Clear file dialog parameters for following re-use.
|
||||
*/
|
||||
/// @brief Clear file dialog parameters for following re-use.
|
||||
void Clear() {
|
||||
m_Owner = nullptr;
|
||||
m_HasTitle = m_HasInitFileName = m_HasInitDirectory = false;
|
||||
@ -191,9 +251,11 @@ namespace YYCC::DialogHelper {
|
||||
|
||||
/**
|
||||
* @brief Generate Windows dialog system used data struct.
|
||||
* @param win_result[out] The class holding the generated filter data struct.
|
||||
* @param[out] win_result The class receiving the generated filter data struct.
|
||||
* @return True if generation is success, otherwise false.
|
||||
* @remarks User should not call this function, this function is used in internal code.
|
||||
* @remarks
|
||||
* Programmer should not call this function.
|
||||
* This function is used as YYCC internal code.
|
||||
*/
|
||||
bool Generate(WinFileDialog& win_result) const;
|
||||
|
||||
@ -204,16 +266,41 @@ namespace YYCC::DialogHelper {
|
||||
FileFilters m_FileTypes;
|
||||
/**
|
||||
* @brief The default selected file type in dialog
|
||||
* @remarks Although Windows notice that this is a 1-based index,
|
||||
* but for universal experience, we order this is 0-based index.
|
||||
* @remarks
|
||||
* The index Windows used is 1-based index.
|
||||
* But for universal experience, we order this is 0-based index.
|
||||
* And do convertion when generating Windows used struct.
|
||||
*/
|
||||
size_t m_DefaultFileTypeIndex;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Open the dialog which order user select single file to open.
|
||||
* @param[in] params The configuration of dialog.
|
||||
* @param[out] ret Full path to user selected file.
|
||||
* @return False if user calcel the operation or something went wrong, otherwise true.
|
||||
*/
|
||||
bool OpenFileDialog(const FileDialog& params, yycc_u8string& ret);
|
||||
/**
|
||||
* @brief Open the dialog which order user select multiple file to open.
|
||||
* @param[in] params The configuration of dialog.
|
||||
* @param[out] ret The list of full path of user selected files.
|
||||
* @return False if user calcel the operation or something went wrong, otherwise true.
|
||||
*/
|
||||
bool OpenMultipleFileDialog(const FileDialog& params, std::vector<yycc_u8string>& ret);
|
||||
/**
|
||||
* @brief Open the dialog which order user select single file to save.
|
||||
* @param[in] params The configuration of dialog.
|
||||
* @param[out] ret Full path to user selected file.
|
||||
* @return False if user calcel the operation or something went wrong, otherwise true.
|
||||
*/
|
||||
bool SaveFileDialog(const FileDialog& params, yycc_u8string& ret);
|
||||
|
||||
/**
|
||||
* @brief Open the dialog which order user select single directory to open.
|
||||
* @param[in] params The configuration of dialog.
|
||||
* @param[out] ret Full path to user selected directory.
|
||||
* @return False if user calcel the operation or something went wrong, otherwise true.
|
||||
*/
|
||||
bool OpenFolderDialog(const FileDialog& params, yycc_u8string& ret);
|
||||
|
||||
}
|
||||
|
@ -4,7 +4,7 @@
|
||||
|
||||
namespace YYCC::EncodingHelper {
|
||||
|
||||
#pragma region UTF8 Native Convertion
|
||||
#pragma region UTF8 Ordinary Convertion
|
||||
|
||||
const yycc_char8_t* ToUTF8(const char* src) {
|
||||
return reinterpret_cast<const yycc_char8_t*>(src);
|
||||
@ -19,16 +19,16 @@ namespace YYCC::EncodingHelper {
|
||||
return yycc_u8string_view(reinterpret_cast<const yycc_char8_t*>(src.data()), src.size());
|
||||
}
|
||||
|
||||
const char* ToNative(const yycc_char8_t* src) {
|
||||
const char* ToOrdinary(const yycc_char8_t* src) {
|
||||
return reinterpret_cast<const char*>(src);
|
||||
}
|
||||
char* ToNative(yycc_char8_t* src) {
|
||||
char* ToOrdinary(yycc_char8_t* src) {
|
||||
return reinterpret_cast<char*>(src);
|
||||
}
|
||||
std::string ToNative(const yycc_u8string_view& src) {
|
||||
std::string ToOrdinary(const yycc_u8string_view& src) {
|
||||
return std::string(reinterpret_cast<const char*>(src.data()), src.size());
|
||||
}
|
||||
std::string_view ToNativeView(const yycc_u8string_view& src) {
|
||||
std::string_view ToOrdinaryView(const yycc_u8string_view& src) {
|
||||
return std::string_view(reinterpret_cast<const char*>(src.data()), src.size());
|
||||
}
|
||||
|
||||
@ -176,7 +176,7 @@ return ret;
|
||||
#pragma region UTF8ToWchar
|
||||
|
||||
bool UTF8ToWchar(const yycc_u8string_view& src, std::wstring& dst) {
|
||||
std::string_view adapted_src(ToNativeView(src));
|
||||
std::string_view adapted_src(ToOrdinaryView(src));
|
||||
return CharToWchar(adapted_src, dst, CP_UTF8);
|
||||
}
|
||||
bool UTF8ToWchar(const yycc_char8_t* src, std::wstring& dst) {
|
||||
@ -191,6 +191,44 @@ return ret;
|
||||
|
||||
#pragma endregion
|
||||
|
||||
#pragma region CharToUTF8
|
||||
|
||||
bool CharToUTF8(const std::string_view& src, yycc_u8string& dst, UINT code_page) {
|
||||
std::string adapted_dst;
|
||||
bool ret = CharToChar(src, adapted_dst, code_page, CP_UTF8);
|
||||
if (ret) dst = ToUTF8(adapted_dst);
|
||||
return ret;
|
||||
}
|
||||
bool CharToUTF8(const char* src, yycc_u8string& dst, UINT code_page) {
|
||||
CONVFCT_TYPE2(CharToUTF8, char, yycc_char8_t, code_page);
|
||||
}
|
||||
yycc_u8string CharToUTF8(const std::string_view& src, UINT code_page) {
|
||||
CONVFCT_TYPE3(CharToUTF8, char, yycc_char8_t, code_page);
|
||||
}
|
||||
yycc_u8string CharToUTF8(const char* src, UINT code_page) {
|
||||
CONVFCT_TYPE4(CharToUTF8, char, yycc_char8_t, code_page);
|
||||
}
|
||||
|
||||
#pragma endregion
|
||||
|
||||
#pragma region UTF8ToChar
|
||||
|
||||
bool UTF8ToChar(const yycc_u8string_view& src, std::string& dst, UINT code_page) {
|
||||
std::string_view adapted_src(ToOrdinaryView(src));
|
||||
return CharToChar(adapted_src, dst, CP_UTF8, code_page);
|
||||
}
|
||||
bool UTF8ToChar(const yycc_char8_t* src, std::string& dst, UINT code_page) {
|
||||
CONVFCT_TYPE2(UTF8ToChar, yycc_char8_t, char, code_page);
|
||||
}
|
||||
std::string UTF8ToChar(const yycc_u8string_view& src, UINT code_page) {
|
||||
CONVFCT_TYPE3(UTF8ToChar, yycc_char8_t, char, code_page);
|
||||
}
|
||||
std::string UTF8ToChar(const yycc_char8_t* src, UINT code_page) {
|
||||
CONVFCT_TYPE4(UTF8ToChar, yycc_char8_t, char, code_page);
|
||||
}
|
||||
|
||||
#pragma endregion
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
@ -10,58 +10,26 @@
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief The namespace handling encoding issues.
|
||||
* @brief The helper for all encoding stuff.
|
||||
* @details
|
||||
* \par Windows Encoding Convertion
|
||||
* This namespace provides the convertion between wchar_t, UTF8 and code-page-based string:
|
||||
* The function name has following format: \c AAAToBBB.
|
||||
* AAA is the source string and BBB is target string.
|
||||
* AAA and BBB has following possible value:
|
||||
* \li \c Char: Code-page-based string. Usually it will add a code page parameter for function to get the code page of this string. For code page, please see Microsoft document.
|
||||
* \li \c UTF8: UTF8 string.
|
||||
* \li \c Wchar: wchar_t string.
|
||||
* \par
|
||||
* For example: \c WcharToUTF8 will perform the convertion from wchar_t to UTF8,
|
||||
* and \c CharToChar will perform the convertion between 2 code-page-based string and caller can specify individual code page for these 2 string.
|
||||
* \par
|
||||
* These functions are Windows specific and are unavailable on other platforms.
|
||||
* Becasue Windows use wchar_t string as its function arguments for globalization, and this library use UTF8 everywhere.
|
||||
* So it should have a bidirectional way to do convertion between wchar_t string and UTF8 string.
|
||||
*
|
||||
* \par UTF32, UTF16 and UTF8 Convertion
|
||||
* This namespace also provide the convertion among UTF32, UTF16 and UTF8.
|
||||
* These convertion functions are suit for all platforms, not Windows oriented.
|
||||
* \par
|
||||
* Due to implementation, this library assume all non-Windows system use UTF8 as their C locale.
|
||||
* Otherwise these functions will produce wrong result.
|
||||
*
|
||||
* \par Function Parameters
|
||||
* We provide these encoding convertion functions with following 2 types:
|
||||
* \li Function returns \c bool and its parameter order source string pointer and a corresponding \c std::basic_string container for receiving result.
|
||||
* \li Function returns corresponding \c std::basic_string result, and its parameter only order source string pointer.
|
||||
* \par
|
||||
* For these 2 declarations, both of them will not throw any exception and do not accept nullptr as source string.
|
||||
* The only difference is that the way to indicate convertion error.
|
||||
* \par
|
||||
* First declaration will return false to indicate there is an error when doing convertion. Please note that the content of string container passing in may still be changed!
|
||||
* Last declaration will return empty string to indicate error. Please note if you pass empty string in, they still will output empty string but it doesn't mean an error.
|
||||
* So last declaration is used in the scenario that we don't care whether the convertion success did. For example, output something to console.
|
||||
*
|
||||
* For more infomations about how to use the functions provided by this namespace,
|
||||
* please see \ref library_encoding and \ref encoding_helper.
|
||||
*/
|
||||
namespace YYCC::EncodingHelper {
|
||||
|
||||
#define _YYCC_U8(strl) u8 ## strl
|
||||
#define YYCC_U8(strl) (reinterpret_cast<const ::YYCC::yycc_char8_t*>(_YYCC_U8(strl)))
|
||||
#define _YYCC_U8(strl) u8 ## strl ///< The assistant macro for YYCC_U8.
|
||||
#define YYCC_U8(strl) (reinterpret_cast<const ::YYCC::yycc_char8_t*>(_YYCC_U8(strl))) ///< The macro for creating UTF8 string literal. See \ref library_encoding.
|
||||
#define YYCC_U8_CHAR(chr) (static_cast<YYCC::yycc_char8_t>(chr)) ///< The macro for casting ordinary char type into YYCC UTF8 char type.
|
||||
|
||||
const yycc_char8_t* ToUTF8(const char* src);
|
||||
yycc_char8_t* ToUTF8(char* src);
|
||||
yycc_u8string ToUTF8(const std::string_view& src);
|
||||
yycc_u8string_view ToUTF8View(const std::string_view& src);
|
||||
|
||||
const char* ToNative(const yycc_char8_t* src);
|
||||
char* ToNative(yycc_char8_t* src);
|
||||
std::string ToNative(const yycc_u8string_view& src);
|
||||
std::string_view ToNativeView(const yycc_u8string_view& src);
|
||||
const char* ToOrdinary(const yycc_char8_t* src);
|
||||
char* ToOrdinary(yycc_char8_t* src);
|
||||
std::string ToOrdinary(const yycc_u8string_view& src);
|
||||
std::string_view ToOrdinaryView(const yycc_u8string_view& src);
|
||||
|
||||
#if YYCC_OS == YYCC_OS_WINDOWS
|
||||
|
||||
@ -90,6 +58,16 @@ namespace YYCC::EncodingHelper {
|
||||
bool UTF8ToWchar(const yycc_char8_t* src, std::wstring& dst);
|
||||
std::wstring UTF8ToWchar(const yycc_u8string_view& src);
|
||||
std::wstring UTF8ToWchar(const yycc_char8_t* src);
|
||||
|
||||
bool CharToUTF8(const std::string_view& src, yycc_u8string& dst, UINT code_page);
|
||||
bool CharToUTF8(const char* src, yycc_u8string& dst, UINT code_page);
|
||||
yycc_u8string CharToUTF8(const std::string_view& src, UINT code_page);
|
||||
yycc_u8string CharToUTF8(const char* src, UINT code_page);
|
||||
|
||||
bool UTF8ToChar(const yycc_u8string_view& src, std::string& dst, UINT code_page);
|
||||
bool UTF8ToChar(const yycc_char8_t* src, std::string& dst, UINT code_page);
|
||||
std::string UTF8ToChar(const yycc_u8string_view& src, UINT code_page);
|
||||
std::string UTF8ToChar(const yycc_char8_t* src, UINT code_page);
|
||||
|
||||
#endif
|
||||
|
||||
|
@ -11,6 +11,7 @@
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cinttypes>
|
||||
#include <mutex>
|
||||
|
||||
#include "WinImportPrefix.hpp"
|
||||
#include <Windows.h>
|
||||
@ -19,38 +20,153 @@
|
||||
|
||||
namespace YYCC::ExceptionHelper {
|
||||
|
||||
/**
|
||||
* @brief True if the exception handler already registered, otherwise false.
|
||||
* @details
|
||||
* This variable is designed to prevent multiple register operation
|
||||
* because unhandled exception handler should only be registered once.
|
||||
* \n
|
||||
* Register function should check whether this variable is false before registering,
|
||||
* and set this variable to true after registing.
|
||||
* Unregister as well as should do the same check.
|
||||
*/
|
||||
static bool g_IsRegistered = false;
|
||||
/**
|
||||
* @brief True if a exception handler is running, otherwise false.
|
||||
* @details
|
||||
* This variable is served for blocking possible infinity recursive exception handling.
|
||||
* \n
|
||||
* When entering unhandled exception handler, we must check whether this variable is true.
|
||||
* If it is true, it mean that there is another unhandled exception handler running.
|
||||
* Then we should exit immediately.
|
||||
* Otherwise, this variable should be set to true indicating we are processing unhandled exception.
|
||||
* After processing exception, at the end of unhandled exception handler,
|
||||
* we should restore this value to false.
|
||||
*
|
||||
*/
|
||||
static bool g_IsProcessing = false;
|
||||
/**
|
||||
* @brief The backup of original exception handler.
|
||||
* @details
|
||||
* This variable was set when registering unhandled exception handler.
|
||||
* And will be used when unregistering for restoring.
|
||||
*/
|
||||
static LPTOP_LEVEL_EXCEPTION_FILTER g_ProcBackup;
|
||||
static LONG WINAPI UExceptionImpl(LPEXCEPTION_POINTERS);
|
||||
class ExceptionRegister {
|
||||
public:
|
||||
ExceptionRegister() :
|
||||
m_CoreMutex(),
|
||||
m_IsRegistered(false), m_IsProcessing(false), m_PrevProcHandler(nullptr),
|
||||
m_SingletonMutex(NULL) {}
|
||||
~ExceptionRegister() {
|
||||
Unregister();
|
||||
}
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Try to register unhandled exception handler.
|
||||
*/
|
||||
void Register() {
|
||||
std::lock_guard<std::mutex> locker(m_CoreMutex);
|
||||
// if we have registered, return
|
||||
if (m_IsRegistered) return;
|
||||
|
||||
// check singleton
|
||||
// build mutex string first
|
||||
yycc_u8string mutex_name;
|
||||
if (!StringHelper::Printf(mutex_name, YYCC_U8("Global\\%" PRIu32 ".{61634294-d23c-43f9-8490-b5e09837eede}"), GetCurrentProcessId()))
|
||||
return;
|
||||
std::wstring mutex_wname;
|
||||
if (!EncodingHelper::UTF8ToWchar(mutex_name, mutex_wname))
|
||||
return;
|
||||
// create mutex
|
||||
m_SingletonMutex = CreateMutexW(NULL, FALSE, mutex_wname.c_str());
|
||||
DWORD errcode = GetLastError();
|
||||
// check whether be created
|
||||
if (m_SingletonMutex == NULL)
|
||||
return;
|
||||
if (errcode == ERROR_ALREADY_EXISTS) {
|
||||
CloseHandle(m_SingletonMutex);
|
||||
m_SingletonMutex = NULL;
|
||||
return;
|
||||
}
|
||||
|
||||
// okey, we can register it.
|
||||
// backup old handler
|
||||
m_PrevProcHandler = SetUnhandledExceptionFilter(UExceptionImpl);
|
||||
// mark registered
|
||||
m_IsRegistered = true;
|
||||
}
|
||||
/**
|
||||
* @brief Try to unregister unhandled exception handler.
|
||||
*/
|
||||
void Unregister() {
|
||||
std::lock_guard<std::mutex> locker(m_CoreMutex);
|
||||
// if we are not registered, skip
|
||||
if (!m_IsRegistered) return;
|
||||
|
||||
// unregister handler
|
||||
// restore old handler
|
||||
SetUnhandledExceptionFilter(m_PrevProcHandler);
|
||||
m_PrevProcHandler = nullptr;
|
||||
|
||||
// release singleton handler
|
||||
if (m_SingletonMutex != NULL) {
|
||||
CloseHandle(m_SingletonMutex);
|
||||
m_SingletonMutex = NULL;
|
||||
}
|
||||
|
||||
// mark unregistered
|
||||
m_IsRegistered = false;
|
||||
}
|
||||
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Check whether handler is registered.
|
||||
* @return True if it is, otherwise false.
|
||||
*/
|
||||
bool IsRegistered() const {
|
||||
std::lock_guard<std::mutex> locker(m_CoreMutex);
|
||||
return m_IsRegistered;
|
||||
}
|
||||
/**
|
||||
* @brief Check whether we are processing unhandled exception.
|
||||
* @return True if it is, otherwise false.
|
||||
*/
|
||||
bool IsProcessing() const {
|
||||
std::lock_guard<std::mutex> locker(m_CoreMutex);
|
||||
return m_IsProcessing;
|
||||
}
|
||||
/**
|
||||
* @brief Get the old unhandled exception handler before registering.
|
||||
* @return The fucntion pointer to old unhandled exception handler. May be nullptr.
|
||||
*/
|
||||
LPTOP_LEVEL_EXCEPTION_FILTER GetPrevProcHandler() const {
|
||||
std::lock_guard<std::mutex> locker(m_CoreMutex);
|
||||
return m_PrevProcHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Try to start process unhandled exception.
|
||||
* @return True if you can start to process.
|
||||
* False means there is already a process running. You should not process it now.
|
||||
*/
|
||||
bool StartProcessing() {
|
||||
std::lock_guard<std::mutex> locker(m_CoreMutex);
|
||||
if (m_IsProcessing) return false;
|
||||
else {
|
||||
m_IsProcessing = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @brief Mark current process of unhandled exception has done.
|
||||
* @details This should only be called when StartProcessing() return true.
|
||||
*/
|
||||
void StopProcessing() {
|
||||
std::lock_guard<std::mutex> locker(m_CoreMutex);
|
||||
m_IsProcessing = false;
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief The core mutex for keeping this class is in synchronized.
|
||||
*/
|
||||
mutable std::mutex m_CoreMutex;
|
||||
|
||||
/**
|
||||
* @brief Whether we have registered unhandled exception handler.
|
||||
* True if it is, otherwise false.
|
||||
*/
|
||||
bool m_IsRegistered;
|
||||
/**
|
||||
* @brief Whether we are processing unhandled exception.
|
||||
* True if it is, otherwise false.
|
||||
*/
|
||||
bool m_IsProcessing;
|
||||
/**
|
||||
* @brief The backup of old unhandled exception handler.
|
||||
*/
|
||||
LPTOP_LEVEL_EXCEPTION_FILTER m_PrevProcHandler;
|
||||
/**
|
||||
* @brief The Windows mutex handle for singleton implementation.
|
||||
* Because we may have many DLLs using YYCC in the same process.
|
||||
* But the unhandled exception handler only need to be registered once.
|
||||
*/
|
||||
HANDLE m_SingletonMutex;
|
||||
};
|
||||
|
||||
static ExceptionRegister g_ExceptionRegister;
|
||||
|
||||
#pragma region Exception Handler Implementation
|
||||
|
||||
@ -122,7 +238,7 @@ namespace YYCC::ExceptionHelper {
|
||||
if (fs != nullptr) {
|
||||
va_list arg1;
|
||||
va_start(arg1, fmt);
|
||||
std::vfprintf(fs, EncodingHelper::ToNative(fmt), arg1);
|
||||
std::vfprintf(fs, EncodingHelper::ToOrdinary(fmt), arg1);
|
||||
std::fputs("\n", fs);
|
||||
va_end(arg1);
|
||||
}
|
||||
@ -145,7 +261,7 @@ namespace YYCC::ExceptionHelper {
|
||||
static void UExceptionErrLogWriteLine(std::FILE* fs, const yycc_char8_t* strl) {
|
||||
// write to file
|
||||
if (fs != nullptr) {
|
||||
std::fputs(EncodingHelper::ToNative(strl), fs);
|
||||
std::fputs(EncodingHelper::ToOrdinary(strl), fs);
|
||||
std::fputs("\n", fs);
|
||||
}
|
||||
// write to stderr
|
||||
@ -316,28 +432,24 @@ namespace YYCC::ExceptionHelper {
|
||||
}
|
||||
|
||||
static bool UExceptionFetchRecordPath(yycc_u8string& log_path, yycc_u8string& coredump_path) {
|
||||
// build two file names like: "module.dll.1234.log" and "module.dll.1234.dmp".
|
||||
// "module.dll" is the name of current module. "1234" is current process id.
|
||||
// get self module name
|
||||
yycc_u8string u8_self_module_name;
|
||||
// build two file names like: "error.exe.1234.log" and "error.exe.1234.dmp".
|
||||
// "error.exe" is the name of current process. "1234" is current process id.
|
||||
// get process name
|
||||
yycc_u8string u8_process_name;
|
||||
{
|
||||
// get module handle
|
||||
HMODULE hSelfModule = YYCC::WinFctHelper::GetCurrentModule();
|
||||
if (hSelfModule == nullptr)
|
||||
return false;
|
||||
// get full path of self module
|
||||
yycc_u8string u8_self_module_path;
|
||||
if (!YYCC::WinFctHelper::GetModuleFileName(hSelfModule, u8_self_module_path))
|
||||
// get full path of process
|
||||
yycc_u8string u8_process_path;
|
||||
if (!YYCC::WinFctHelper::GetModuleFileName(NULL, u8_process_path))
|
||||
return false;
|
||||
// extract file name from full path by std::filesystem::path
|
||||
std::filesystem::path self_module_path(FsPathPatch::FromUTF8Path(u8_self_module_path.c_str()));
|
||||
u8_self_module_name = FsPathPatch::ToUTF8Path(self_module_path.filename());
|
||||
std::filesystem::path process_path(FsPathPatch::FromUTF8Path(u8_process_path.c_str()));
|
||||
u8_process_name = FsPathPatch::ToUTF8Path(process_path.filename());
|
||||
}
|
||||
// then get process id
|
||||
DWORD process_id = GetCurrentProcessId();
|
||||
// conbine them as a file name prefix
|
||||
yycc_u8string u8_filename_prefix;
|
||||
if (!YYCC::StringHelper::Printf(u8_filename_prefix, YYCC_U8("%s.%" PRIu32), u8_self_module_name.c_str(), process_id))
|
||||
if (!YYCC::StringHelper::Printf(u8_filename_prefix, YYCC_U8("%s.%" PRIu32), u8_process_name.c_str(), process_id))
|
||||
return false;
|
||||
// then get file name for log and minidump
|
||||
yycc_u8string u8_log_filename = u8_filename_prefix + YYCC_U8(".log");
|
||||
@ -367,10 +479,9 @@ namespace YYCC::ExceptionHelper {
|
||||
}
|
||||
|
||||
static LONG WINAPI UExceptionImpl(LPEXCEPTION_POINTERS info) {
|
||||
// detect loop calling
|
||||
if (g_IsProcessing) goto end_proc;
|
||||
// start process
|
||||
g_IsProcessing = true;
|
||||
// try to start process current unhandled exception
|
||||
// to prevent any possible recursive calling.
|
||||
if (!g_ExceptionRegister.StartProcessing()) goto end_proc;
|
||||
|
||||
// core implementation
|
||||
{
|
||||
@ -396,14 +507,15 @@ namespace YYCC::ExceptionHelper {
|
||||
|
||||
}
|
||||
|
||||
// end process
|
||||
failed:
|
||||
g_IsProcessing = false;
|
||||
// stop process
|
||||
g_ExceptionRegister.StartProcessing();
|
||||
|
||||
end_proc:
|
||||
// if backup proc can be run, run it
|
||||
// otherwise directly return.
|
||||
end_proc:
|
||||
if (g_ProcBackup != nullptr) {
|
||||
return g_ProcBackup(info);
|
||||
auto prev_proc = g_ExceptionRegister.GetPrevProcHandler();
|
||||
if (prev_proc != nullptr) {
|
||||
return prev_proc(info);
|
||||
} else {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
@ -412,15 +524,11 @@ namespace YYCC::ExceptionHelper {
|
||||
#pragma endregion
|
||||
|
||||
void Register() {
|
||||
if (g_IsRegistered) return;
|
||||
g_ProcBackup = SetUnhandledExceptionFilter(UExceptionImpl);
|
||||
g_IsRegistered = true;
|
||||
g_ExceptionRegister.Register();
|
||||
}
|
||||
|
||||
void Unregister() {
|
||||
if (!g_IsRegistered) return;
|
||||
SetUnhandledExceptionFilter(g_ProcBackup);
|
||||
g_IsRegistered = false;
|
||||
g_ExceptionRegister.Unregister();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -6,10 +6,7 @@
|
||||
* @brief Windows specific unhandled exception processor.
|
||||
* @details
|
||||
* This namespace is Windows specific. On other platforms, the whole namespace is unavailable.
|
||||
*
|
||||
* This namespace allow user register unhandled exception handler on Windows
|
||||
* to output error log into \c stderr and log file, and generate coredump if possible.
|
||||
* This is useful for bug tracing on Windows, especially most Windows user are naive and don't know how to report bug.
|
||||
* For how to utilize this namespace, please see \ref exception_helper.
|
||||
*
|
||||
*/
|
||||
namespace YYCC::ExceptionHelper {
|
||||
@ -20,9 +17,9 @@ namespace YYCC::ExceptionHelper {
|
||||
* This function will set an internal function as unhandled exception handler on Windows.
|
||||
*
|
||||
* When unhandled exception raised,
|
||||
* That internal function will output error stacktrace in standard output
|
||||
* and log file (located in temp folder), and also generate a dump file
|
||||
* in temp folder (for convenient debugging of developer when reporting bugs) if it can.
|
||||
* That internal function will output error stacktrace in standard output,
|
||||
* and generate log file and dump file in \c \%APPDATA\%/CrashDumps folder if it is possible.
|
||||
* (for convenient debugging of developer when reporting bugs.)
|
||||
*
|
||||
* This function usually is called at the start of program.
|
||||
*/
|
||||
@ -33,7 +30,7 @@ namespace YYCC::ExceptionHelper {
|
||||
* The reverse operation of Register().
|
||||
*
|
||||
* This function and Register() should always be used as a pair.
|
||||
* You must call this function if you have called Register() before.
|
||||
* You must call this function to release reources if you have called Register().
|
||||
*
|
||||
* This function usually is called at the end of program.
|
||||
*/
|
||||
|
@ -18,7 +18,7 @@ namespace YYCC::FsPathPatch {
|
||||
return std::filesystem::path(wpath);
|
||||
|
||||
#else
|
||||
return std::filesystem::path(EncodingHelper::ToNative(u8_path));
|
||||
return std::filesystem::path(EncodingHelper::ToOrdinary(u8_path));
|
||||
#endif
|
||||
}
|
||||
|
||||
|
@ -4,37 +4,25 @@
|
||||
#include <filesystem>
|
||||
|
||||
/**
|
||||
* @brief The patch namespace resolving \c std::filesystem::path encoding issue.
|
||||
* @brief \c std::filesystem::path related patches for UTF8 compatibility
|
||||
* @details
|
||||
* This patch is Windows oriented.
|
||||
* If you are in Windows, this patch will perform extra operations to achieve goals,
|
||||
* and in other platforms, they just redirect request to corresponding vanilla C++ functions.
|
||||
*
|
||||
* As you know, the underlying char type of \c std::filesystem::path is \c wchar_t on Windows,
|
||||
* and in other platforms, it is simple \c char.
|
||||
* Due to this, if you passing UTF8 char sequence to \c std::filesystem::path on Windows,
|
||||
* the library implementation will assume your input is based on current Windows code page, not UTF8.
|
||||
* And the final path stored in \c std::filesystem::path is not what you expcected.
|
||||
*
|
||||
* This patch namespace always use UTF8 as its argument. There is no ambiguous issue.
|
||||
* You should use the functions provided by this namespace on any platforms
|
||||
* instead of vanilla \c std::filesystem::path functions.
|
||||
* See also \ref fs_path_patch.
|
||||
*/
|
||||
namespace YYCC::FsPathPatch {
|
||||
|
||||
/**
|
||||
* @brief Constructs the path from a UTF8 character sequence
|
||||
* @param[in] u8_path UTF8 path string for building this std::filesystem::path.
|
||||
* @return std::filesystem::path instance.
|
||||
* @brief Constructs \c std::filesystem::path from UTF8 path.
|
||||
* @param[in] u8_path UTF8 path string for building.
|
||||
* @return \c std::filesystem::path instance.
|
||||
* @exception std::invalid_argument Fail to parse given UTF8 string (maybe invalid?).
|
||||
*/
|
||||
std::filesystem::path FromUTF8Path(const yycc_char8_t* u8_path);
|
||||
|
||||
/**
|
||||
* @brief Returns the UTF8 representation of the pathname
|
||||
* @param path[in] The string to be output.
|
||||
* @return UTF8 encoded string representing given path.
|
||||
* @exception std::invalid_argument Fail to parse to UTF8 string.
|
||||
* @brief Returns the UTF8 representation of given \c std::filesystem::path.
|
||||
* @param[in] path The \c std::filesystem::path instance converting to UTF8 path.
|
||||
* @return The UTF8 representation of given \c std::filesystem::path.
|
||||
* @exception std::invalid_argument Fail to convert to UTF8 string.
|
||||
*/
|
||||
yycc_u8string ToUTF8Path(const std::filesystem::path& path);
|
||||
|
||||
|
@ -28,7 +28,7 @@ namespace YYCC::IOHelper {
|
||||
return _wfopen(wpath.c_str(), wmode.c_str());
|
||||
|
||||
#else
|
||||
return std::fopen(u8_filepath, u8_mode);
|
||||
return std::fopen(EncodingHelper::ToOrdinary(u8_filepath), EncodingHelper::ToOrdinary(u8_mode));
|
||||
#endif
|
||||
}
|
||||
|
||||
|
@ -4,6 +4,11 @@
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
|
||||
/**
|
||||
* @brief Some IO related stuff
|
||||
* @details
|
||||
* See also \ref io_helper.
|
||||
*/
|
||||
namespace YYCC::IOHelper {
|
||||
|
||||
#if UINTPTR_MAX == UINT32_MAX
|
||||
@ -24,13 +29,13 @@ namespace YYCC::IOHelper {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief The UTF8 version of std::fopen.
|
||||
* @brief The UTF8 version of \c std::fopen.
|
||||
* @param[in] u8_filepath The UTF8 encoded path to the file to be opened.
|
||||
* @param[in] u8_mode UTF8 encoded mode string of the file to be opened.
|
||||
* @remarks
|
||||
* This function is suit for Windows because std::fopen do not support UTF8 on Windows.
|
||||
* On other platforms, this function will delegate request directly to std::fopen.
|
||||
* @return FILE* of the file to be opened, or nullptr if failed.
|
||||
* @return \c FILE* of the file to be opened, or nullptr if failed.
|
||||
*/
|
||||
FILE* UTF8FOpen(const yycc_char8_t* u8_filepath, const yycc_char8_t* u8_mode);
|
||||
|
||||
|
@ -9,20 +9,34 @@
|
||||
#include <charconv>
|
||||
#include <array>
|
||||
|
||||
/**
|
||||
* @brief The helper involving convertion between arithmetic types (integral, floating point and bool) and string
|
||||
* @details
|
||||
* See also \ref parser_helper.
|
||||
*/
|
||||
namespace YYCC::ParserHelper {
|
||||
|
||||
// Reference: https://zh.cppreference.com/w/cpp/utility/from_chars
|
||||
|
||||
/**
|
||||
* @brief Try parsing given string to floating point types.
|
||||
* @tparam _Ty The type derived from floating point type.
|
||||
* @param[in] strl The string need to be parsed.
|
||||
* @param[out] num
|
||||
* The variable receiving result.
|
||||
* There is no guarantee that the content is not modified when parsing failed.
|
||||
* @return True if success, otherwise false.
|
||||
*/
|
||||
template<typename _Ty, std::enable_if_t<std::is_floating_point_v<_Ty>, int> = 0>
|
||||
bool TryParse(const yycc_u8string_view& strl, _Ty& num) {
|
||||
auto [ptr, ec] = std::from_chars(
|
||||
EncodingHelper::ToNative(strl.data()),
|
||||
EncodingHelper::ToNative(strl.data() + strl.size()),
|
||||
EncodingHelper::ToOrdinary(strl.data()),
|
||||
EncodingHelper::ToOrdinary(strl.data() + strl.size()),
|
||||
num, std::chars_format::general
|
||||
);
|
||||
if (ec == std::errc()) {
|
||||
// check whether the full string is matched
|
||||
return ptr == EncodingHelper::ToNative(strl.data() + strl.size());
|
||||
return ptr == EncodingHelper::ToOrdinary(strl.data() + strl.size());
|
||||
} else if (ec == std::errc::invalid_argument) {
|
||||
// given string is invalid
|
||||
return false;
|
||||
@ -34,16 +48,26 @@ namespace YYCC::ParserHelper {
|
||||
throw std::runtime_error("unreachable code.");
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @brief Try parsing given string to integral types.
|
||||
* @tparam _Ty The type derived from integral type.
|
||||
* @param[in] strl The string need to be parsed.
|
||||
* @param[out] num
|
||||
* The variable receiving result.
|
||||
* There is no guarantee that the content is not modified when parsing failed.
|
||||
* @param[in] base integer base to use: a value between 2 and 36 (inclusive).
|
||||
* @return True if success, otherwise false.
|
||||
*/
|
||||
template<typename _Ty, std::enable_if_t<std::is_integral_v<_Ty> && !std::is_same_v<_Ty, bool>, int> = 0>
|
||||
bool TryParse(const yycc_u8string_view& strl, _Ty& num, int base = 10) {
|
||||
auto [ptr, ec] = std::from_chars(
|
||||
EncodingHelper::ToNative(strl.data()),
|
||||
EncodingHelper::ToNative(strl.data() + strl.size()),
|
||||
EncodingHelper::ToOrdinary(strl.data()),
|
||||
EncodingHelper::ToOrdinary(strl.data() + strl.size()),
|
||||
num, base
|
||||
);
|
||||
if (ec == std::errc()) {
|
||||
// check whether the full string is matched
|
||||
return ptr == EncodingHelper::ToNative(strl.data() + strl.size());
|
||||
return ptr == EncodingHelper::ToOrdinary(strl.data() + strl.size());
|
||||
} else if (ec == std::errc::invalid_argument) {
|
||||
// given string is invalid
|
||||
return false;
|
||||
@ -55,6 +79,15 @@ namespace YYCC::ParserHelper {
|
||||
throw std::runtime_error("unreachable code.");
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @brief Try parsing given string to bool types.
|
||||
* @tparam _Ty The type derived from bool type.
|
||||
* @param[in] strl The string need to be parsed ("true" or "false").
|
||||
* @param[out] num
|
||||
* The variable receiving result.
|
||||
* There is no guarantee that the content is not modified when parsing failed.
|
||||
* @return True if success, otherwise false.
|
||||
*/
|
||||
template<typename _Ty, std::enable_if_t<std::is_same_v<_Ty, bool>, int> = 0>
|
||||
bool TryParse(const yycc_u8string_view& strl, _Ty& num) {
|
||||
if (strl == YYCC_U8("true")) num = true;
|
||||
@ -63,6 +96,15 @@ namespace YYCC::ParserHelper {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Parse given string to arithmetic types.
|
||||
* @tparam _Ty The type derived from arithmetic type.
|
||||
* @param[in] strl The string need to be parsed.
|
||||
* @return
|
||||
* The parsing result.
|
||||
* There is no guarantee about the content of this return value when parsing failed.
|
||||
* It may be any possible value but usually is its default value.
|
||||
*/
|
||||
template<typename _Ty, std::enable_if_t<std::is_arithmetic_v<_Ty>, int> = 0>
|
||||
_Ty Parse(const yycc_u8string_view& strl) {
|
||||
_Ty ret;
|
||||
@ -72,25 +114,37 @@ namespace YYCC::ParserHelper {
|
||||
|
||||
// Reference: https://en.cppreference.com/w/cpp/utility/to_chars
|
||||
|
||||
/**
|
||||
* @brief Return a string version of given arithmetic value.
|
||||
* @tparam _Ty The type derived from arithmetic type.
|
||||
* @param[in] num The value getting string version.
|
||||
* @return The string version of given value.
|
||||
*/
|
||||
template<typename _Ty, std::enable_if_t<std::is_arithmetic_v<_Ty> && !std::is_same_v<_Ty, bool>, int> = 0>
|
||||
yycc_u8string ToString(_Ty num) {
|
||||
std::array<yycc_char8_t, 64> buffer;
|
||||
auto [ptr, ec] = std::to_chars(
|
||||
EncodingHelper::ToNative(buffer.data()),
|
||||
EncodingHelper::ToNative(buffer.data() + buffer.size()),
|
||||
EncodingHelper::ToOrdinary(buffer.data()),
|
||||
EncodingHelper::ToOrdinary(buffer.data() + buffer.size()),
|
||||
num
|
||||
);
|
||||
if (ec == std::errc()) {
|
||||
return yycc_u8string(buffer.data(), EncodingHelper::ToUTF8(ptr) - buffer.data());
|
||||
} else if (ec == std::errc::value_too_large) {
|
||||
// too short buffer
|
||||
// this should not happend
|
||||
// this should not happened
|
||||
throw std::out_of_range("ToString() buffer is not sufficient.");
|
||||
} else {
|
||||
// unreachable
|
||||
throw std::runtime_error("unreachable code.");
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @brief Return a string version of given bool value.
|
||||
* @tparam _Ty The type derived from bool type.
|
||||
* @param[in] num The value getting string version.
|
||||
* @return The string version of given value ("true" or "false").
|
||||
*/
|
||||
template<typename _Ty, std::enable_if_t<std::is_same_v<_Ty, bool>, int> = 0>
|
||||
yycc_u8string ToString(_Ty num) {
|
||||
if (num) return yycc_u8string(YYCC_U8("true"));
|
||||
|
@ -25,7 +25,7 @@ namespace YYCC::StringHelper {
|
||||
int count = std::vsnprintf(
|
||||
nullptr,
|
||||
0,
|
||||
EncodingHelper::ToNative(format),
|
||||
EncodingHelper::ToOrdinary(format),
|
||||
args1
|
||||
);
|
||||
if (count < 0) {
|
||||
@ -40,9 +40,9 @@ namespace YYCC::StringHelper {
|
||||
// however std::vsnprintf already have a trailing NULL, so we plus 1 for it.
|
||||
strl.resize(count);
|
||||
int write_result = std::vsnprintf(
|
||||
EncodingHelper::ToNative(strl.data()),
|
||||
EncodingHelper::ToOrdinary(strl.data()),
|
||||
strl.size() + 1,
|
||||
EncodingHelper::ToNative(format),
|
||||
EncodingHelper::ToOrdinary(format),
|
||||
args2
|
||||
);
|
||||
va_end(args2);
|
||||
@ -170,7 +170,7 @@ namespace YYCC::StringHelper {
|
||||
#pragma region Upper Lower
|
||||
|
||||
template<bool bIsToLower>
|
||||
void GeneralStringLowerUpper(yycc_u8string& strl) {
|
||||
static void GeneralStringLowerUpper(yycc_u8string& strl) {
|
||||
// References:
|
||||
// https://en.cppreference.com/w/cpp/algorithm/transform
|
||||
// https://en.cppreference.com/w/cpp/string/byte/tolower
|
||||
|
@ -6,59 +6,141 @@
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
/**
|
||||
* @brief The helper containing string operations
|
||||
* @details
|
||||
* See also \ref string_helper.
|
||||
*/
|
||||
namespace YYCC::StringHelper {
|
||||
|
||||
/**
|
||||
* @brief Perform a string formatting operation.
|
||||
* @param[out] strl
|
||||
* The string container receiving the result.
|
||||
* There is no guarantee that the content is not modified when function failed.
|
||||
* @param[in] format The format string.
|
||||
* @param[in] ... Argument list of format string.
|
||||
* @return True if success, otherwise false.
|
||||
*/
|
||||
bool Printf(yycc_u8string& strl, const yycc_char8_t* format, ...);
|
||||
/**
|
||||
* @brief Perform a string formatting operation.
|
||||
* @param[out] strl
|
||||
* The string container receiving the result.
|
||||
* There is no guarantee that the content is not modified when function failed.
|
||||
* @param[in] format The format string.
|
||||
* @param[in] argptr Argument list of format string.
|
||||
* @return True if success, otherwise false.
|
||||
*/
|
||||
bool VPrintf(yycc_u8string& strl, const yycc_char8_t* format, va_list argptr);
|
||||
/**
|
||||
* @brief Perform a string formatting operation.
|
||||
* @param[in] format The format string.
|
||||
* @param[in] ... Argument list of format string.
|
||||
* @return The formatting result. Empty string if error happened.
|
||||
*/
|
||||
yycc_u8string Printf(const yycc_char8_t* format, ...);
|
||||
/**
|
||||
* @brief Perform a string formatting operation.
|
||||
* @param[in] format The format string.
|
||||
* @param[in] argptr Argument list of format string.
|
||||
* @return The formatting result. Empty string if error happened.
|
||||
*/
|
||||
yycc_u8string VPrintf(const yycc_char8_t* format, va_list argptr);
|
||||
|
||||
/**
|
||||
* @brief Modify given string with all occurrences of substring \e old replaced by \e new.
|
||||
* @param[in,out] strl The string for replacing
|
||||
* @param[in] _from_strl The \e old string.
|
||||
* @param[in] _to_strl The \e new string.
|
||||
*/
|
||||
void Replace(yycc_u8string& strl, const yycc_char8_t* _from_strl, const yycc_char8_t* _to_strl);
|
||||
/**
|
||||
* @brief Return a copy with all occurrences of substring \e old replaced by \e new.
|
||||
* @param[in] _strl The string for replacing
|
||||
* @param[in] _from_strl The \e old string.
|
||||
* @param[in] _to_strl The \e new string.
|
||||
* @return The result of replacement.
|
||||
*/
|
||||
yycc_u8string Replace(const yycc_char8_t* _strl, const yycc_char8_t* _from_strl, const yycc_char8_t* _to_strl);
|
||||
|
||||
/**
|
||||
* @brief The data provider of general Join function.
|
||||
* For the implementation of this function:
|
||||
* Function return true to continue join. otherwise return false to terminate join.
|
||||
* The argument assigned in the calling returning false is not included.
|
||||
* During calling, implementation should assign the string view to the string need to be joined in given argument.
|
||||
* @brief The data provider of general join function.
|
||||
* @details
|
||||
* For programmer using lambda to implement this function pointer:
|
||||
* \li During calling, implementation should assign the reference of string view passed in argument
|
||||
* to the string which need to be joined.
|
||||
* \li Function return true to continue joining. otherwise return false to stop joining.
|
||||
* The argument content assigned in the calling returning false is not included in join process.
|
||||
*/
|
||||
using JoinDataProvider = std::function<bool(yycc_u8string_view&)>;
|
||||
/**
|
||||
* @brief General Join function.
|
||||
* @details This function use function pointer as a general data provider interface,
|
||||
* so this function suit for all types container, the user only need write a little bit adaption code.
|
||||
* @param fct_data[in] The function pointer to data provider.
|
||||
* @param decilmer[in] The decilmer.
|
||||
* @return A std::string instance which containing the join result.
|
||||
* @brief Universal join function.
|
||||
* @details
|
||||
* This function use function pointer as a general data provider interface,
|
||||
* so this function suit for all types container.
|
||||
* You can use this universal join function for any custom container by
|
||||
* using C++ lambda syntax to create a code block adapted to this function pointer.
|
||||
* @param[in] fct_data The function pointer in JoinDataProvider type prividing the data to be joined.
|
||||
* @param[in] decilmer The decilmer used for joining.
|
||||
* @return The result string of joining.
|
||||
*/
|
||||
yycc_u8string Join(JoinDataProvider fct_data, const yycc_char8_t* decilmer);
|
||||
/**
|
||||
* @brief Specialized Join function for common used container.
|
||||
* @param data
|
||||
* @param decilmer
|
||||
* @param reversed
|
||||
* @return
|
||||
* @brief Specialized join function for \c std::vector.
|
||||
* @param[in] data The list to be joined.
|
||||
* @param[in] decilmer The decilmer used for joining.
|
||||
* @param[in] reversed True if this list should be joined in reversed order.
|
||||
* @return The result string of joining.
|
||||
*/
|
||||
yycc_u8string Join(const std::vector<yycc_u8string>& data, const yycc_char8_t* decilmer, bool reversed = false);
|
||||
|
||||
/**
|
||||
* @brief Return a copy of the string converted to lowercase.
|
||||
* @param[in] strl The string to be lowercase.
|
||||
* @return The copy of the string converted to lowercase.
|
||||
*/
|
||||
yycc_u8string Lower(const yycc_char8_t* strl);
|
||||
/**
|
||||
* @brief Convert given string to lowercase.
|
||||
* @param[in,out] strl The string to be lowercase.
|
||||
*/
|
||||
void Lower(yycc_u8string& strl);
|
||||
/**
|
||||
* @brief Return a copy of the string converted to uppercase.
|
||||
* @param[in] strl The string to be uppercase.
|
||||
* @return The copy of the string converted to uppercase.
|
||||
*/
|
||||
yycc_u8string Upper(const yycc_char8_t* strl);
|
||||
/**
|
||||
* @brief Convert given string to uppercase.
|
||||
* @param[in,out] strl The string to be uppercase.
|
||||
*/
|
||||
void Upper(yycc_u8string& strl);
|
||||
|
||||
/**
|
||||
* @brief General Split function.
|
||||
* @param strl[in] The string need to be splitting.
|
||||
* If this is nullptr, the result will be empty.
|
||||
* @param _decilmer[in] The decilmer for splitting.
|
||||
* If decilmer is nullptr or zero length, the result will only have 1 element which is original string.
|
||||
* @return
|
||||
* @remarks This function may be low performance because it just a homebrew Split functon.
|
||||
* It can works in most toy cases but not suit for high performance scenario.
|
||||
* Also, this function will produce a copy of original string because it is not zero copy.
|
||||
* @brief Split given string with specified decilmer.
|
||||
* @param[in] strl The string need to be splitting.
|
||||
* @param[in] _decilmer The decilmer for splitting.
|
||||
* @return
|
||||
* The split result.
|
||||
* \par
|
||||
* If given string is empty, or decilmer is nullptr or empty,
|
||||
* the result container will only contain 1 entry which is equal to given string.
|
||||
*/
|
||||
std::vector<yycc_u8string> Split(const yycc_u8string_view& strl, const yycc_char8_t* _decilmer);
|
||||
/**
|
||||
* @brief Split given string with specified decilmer as string view.
|
||||
* @param[in] strl The string need to be splitting.
|
||||
* @param[in] _decilmer The decilmer for splitting.
|
||||
* @return
|
||||
* The split result with string view format.
|
||||
* This will not produce any copy of original string.
|
||||
* \par
|
||||
* If given string is empty, or decilmer is nullptr or empty,
|
||||
* the result container will only contain 1 entry which is equal to given string.
|
||||
* @see Split(const yycc_u8string_view&, const yycc_char8_t*)
|
||||
*/
|
||||
std::vector<yycc_u8string_view> SplitView(const yycc_u8string_view& strl, const yycc_char8_t* _decilmer);
|
||||
|
||||
}
|
||||
|
@ -9,10 +9,11 @@
|
||||
#include "WinImportSuffix.hpp"
|
||||
|
||||
/**
|
||||
* @brief The helper providing assistance to Win32 functions.
|
||||
* @brief The helper providing assistance of Win32 functions.
|
||||
* @details
|
||||
* This helper is Windows specific.
|
||||
* If current environment is not Windows, the whole namespace will be unavailable.
|
||||
* See also \ref win_fct_helper
|
||||
*/
|
||||
namespace YYCC::WinFctHelper {
|
||||
|
||||
@ -24,16 +25,16 @@ namespace YYCC::WinFctHelper {
|
||||
*
|
||||
* This function is frequently used by DLL.
|
||||
* Because some design need the HANDLE of current module, not the host EXE loading your DLL.
|
||||
* For example, you may want to get the name of your built DLL at runtime, then you should pass current module HANDLE, not the HANDLE of EXE.
|
||||
* Or, if you want to get the path to your DLL, you also should pass current module HANDLE.
|
||||
* For example, you may want to get the path of your built DLL, or fetch resources from your DLL at runtime,
|
||||
* then you should pass current module HANDLE, not NULL or the HANDLE of EXE.
|
||||
* @return A Windows HANDLE pointing to current module, NULL if failed.
|
||||
*/
|
||||
HMODULE GetCurrentModule();
|
||||
|
||||
/**
|
||||
* @brief Get path to Windows temp folder.
|
||||
* @param[out] ret
|
||||
* The variable receiving UTF8 encoded path to Windows temp folder.
|
||||
* @brief Get path to Windows temporary folder.
|
||||
* @details Windows temporary folder usually is the target of \%TEMP\%.
|
||||
* @param[out] ret The variable receiving UTF8 encoded path to Windows temp folder.
|
||||
* @return True if success, otherwise false.
|
||||
*/
|
||||
bool GetTempDirectory(yycc_u8string& ret);
|
||||
@ -41,20 +42,18 @@ namespace YYCC::WinFctHelper {
|
||||
/**
|
||||
* @brief Get the file name of given module HANDLE
|
||||
* @param[in] hModule
|
||||
* The HANDLE to the module where we want get file name.
|
||||
* It is same as the HANDLE parameter of \c GetModuleFileName.
|
||||
* @param[out] ret
|
||||
* The variable receiving UTF8 encoded file name of given module.
|
||||
* The HANDLE to the module where you want to get file name.
|
||||
* It is same as the HANDLE parameter of Win32 \c GetModuleFileName.
|
||||
* @param[out] ret The variable receiving UTF8 encoded file name of given module.
|
||||
* @return True if success, otherwise false.
|
||||
*/
|
||||
bool GetModuleFileName(HINSTANCE hModule, yycc_u8string& ret);
|
||||
|
||||
/**
|
||||
* @brief Get the path to LOCALAPPDATA.
|
||||
* @details LOCALAPPDATA usually was used as putting local app data files
|
||||
* @param[out] ret
|
||||
* The variable receiving UTF8 encoded path to LOCALAPPDATA.
|
||||
* @return
|
||||
* @brief Get the path to \%LOCALAPPDATA\%.
|
||||
* @details \%LOCALAPPDATA\% usually was used as putting local app data files
|
||||
* @param[out] ret The variable receiving UTF8 encoded path to LOCALAPPDATA.
|
||||
* @return True if success, otherwise false.
|
||||
*/
|
||||
bool GetLocalAppData(yycc_u8string& ret);
|
||||
|
||||
|
73
src/YYCC.natvis
Normal file
73
src/YYCC.natvis
Normal file
@ -0,0 +1,73 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Copyright (c) Microsoft Corporation, yyc12345.
|
||||
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||
-->
|
||||
|
||||
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
|
||||
|
||||
<!-- Following XML are copied from Visual Studio embedded Natvis files. -->
|
||||
<!-- <Microsoft Visual Studio Install Directory>\Common7\Packages\Debugger\Visualizers\stl.natvis -->
|
||||
|
||||
<!-- VC 2013 -->
|
||||
<Type Name="std::basic_string<YYCC::yycc_char8_t,*>" Priority="MediumLow">
|
||||
<AlternativeType Name="std::basic_string<char8_t,*>" />
|
||||
<AlternativeType Name="std::basic_string<unsigned char,*>" />
|
||||
<DisplayString Condition="_Myres < _BUF_SIZE">{_Bx._Buf,s8}</DisplayString>
|
||||
<DisplayString Condition="_Myres >= _BUF_SIZE">{_Bx._Ptr,s8}</DisplayString>
|
||||
<StringView Condition="_Myres < _BUF_SIZE">_Bx._Buf,s8</StringView>
|
||||
<StringView Condition="_Myres >= _BUF_SIZE">_Bx._Ptr,s8</StringView>
|
||||
<Expand>
|
||||
<Item Name="[size]" ExcludeView="simple">_Mysize</Item>
|
||||
<Item Name="[capacity]" ExcludeView="simple">_Myres</Item>
|
||||
<ArrayItems>
|
||||
<Size>_Mysize</Size>
|
||||
<ValuePointer Condition="_Myres < _BUF_SIZE">_Bx._Buf</ValuePointer>
|
||||
<ValuePointer Condition="_Myres >= _BUF_SIZE">_Bx._Ptr</ValuePointer>
|
||||
</ArrayItems>
|
||||
</Expand>
|
||||
</Type>
|
||||
|
||||
<!-- VC 2015+ ABI basic_string -->
|
||||
<Type Name="std::basic_string<YYCC::yycc_char8_t,*>">
|
||||
<AlternativeType Name="std::basic_string<char8_t,*>" />
|
||||
<AlternativeType Name="std::basic_string<unsigned char,*>" />
|
||||
<Intrinsic Name="size" Expression="_Mypair._Myval2._Mysize" />
|
||||
<Intrinsic Name="capacity" Expression="_Mypair._Myval2._Myres" />
|
||||
<!-- _BUF_SIZE = 16 / sizeof(char) < 1 ? 1 : 16 / sizeof(char) == 16 -->
|
||||
<Intrinsic Name="bufSize" Expression="16" />
|
||||
<Intrinsic Name="isShortString" Expression="capacity() < bufSize()" />
|
||||
<Intrinsic Name="isLongString" Expression="capacity() >= bufSize()" />
|
||||
<DisplayString Condition="isShortString()">{_Mypair._Myval2._Bx._Buf,s8}</DisplayString>
|
||||
<DisplayString Condition="isLongString()">{_Mypair._Myval2._Bx._Ptr,s8}</DisplayString>
|
||||
<StringView Condition="isShortString()">_Mypair._Myval2._Bx._Buf,s8</StringView>
|
||||
<StringView Condition="isLongString()">_Mypair._Myval2._Bx._Ptr,s8</StringView>
|
||||
<Expand>
|
||||
<Item Name="[size]" ExcludeView="simple">size()</Item>
|
||||
<Item Name="[capacity]" ExcludeView="simple">capacity()</Item>
|
||||
<Item Name="[allocator]" ExcludeView="simple">_Mypair</Item>
|
||||
<ArrayItems>
|
||||
<Size>_Mypair._Myval2._Mysize</Size>
|
||||
<ValuePointer Condition="isShortString()">_Mypair._Myval2._Bx._Buf</ValuePointer>
|
||||
<ValuePointer Condition="isLongString()">_Mypair._Myval2._Bx._Ptr</ValuePointer>
|
||||
</ArrayItems>
|
||||
</Expand>
|
||||
</Type>
|
||||
|
||||
<Type Name="std::basic_string_view<YYCC::yycc_char8_t,*>">
|
||||
<AlternativeType Name="std::basic_string_view<char8_t,*>" />
|
||||
<AlternativeType Name="std::basic_string_view<unsigned char,*>" />
|
||||
<Intrinsic Name="size" Expression="_Mysize" />
|
||||
<Intrinsic Name="data" Expression="_Mydata" />
|
||||
<DisplayString>{_Mydata,[_Mysize],s8}</DisplayString>
|
||||
<StringView>_Mydata,[_Mysize],s8</StringView>
|
||||
<Expand>
|
||||
<Item Name="[size]" ExcludeView="simple">size()</Item>
|
||||
<ArrayItems>
|
||||
<Size>size()</Size>
|
||||
<ValuePointer>data()</ValuePointer>
|
||||
</ArrayItems>
|
||||
</Expand>
|
||||
</Type>
|
||||
|
||||
</AutoVisualizer>
|
@ -26,8 +26,14 @@
|
||||
|
||||
// Define the UTF8 char type we used.
|
||||
// And do a polyfill if no embedded char8_t type.
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
/**
|
||||
* @brief Library core namespace
|
||||
* @details Almost library functions are located in this namespace.
|
||||
*/
|
||||
namespace YYCC {
|
||||
#if defined(__cpp_char8_t)
|
||||
using yycc_char8_t = char8_t;
|
||||
@ -38,6 +44,27 @@ namespace YYCC {
|
||||
using yycc_u8string = std::basic_string<yycc_char8_t>;
|
||||
using yycc_u8string_view = std::basic_string_view<yycc_char8_t>;
|
||||
#endif
|
||||
|
||||
}
|
||||
/**
|
||||
\typedef yycc_char8_t
|
||||
\brief YYCC UTF8 char type.
|
||||
\details
|
||||
This char type is an alias to \c std::char8_t if your current C++ standard support it.
|
||||
Otherwise it is defined as <TT>unsigned char</TT> as C++ 20 stdandard does.
|
||||
*/
|
||||
/**
|
||||
\typedef yycc_u8string
|
||||
\brief YYCC UTF8 string container type.
|
||||
\details
|
||||
This type is defined as \c std::basic_string<yycc_char8_t>.
|
||||
It is equal to \c std::u8string if your current C++ standard support it.
|
||||
*/
|
||||
/**
|
||||
\typedef yycc_u8string_view
|
||||
\brief YYCC UTF8 string view type.
|
||||
\details
|
||||
This type is defined as \c std::basic_string_view<yycc_char8_t>.
|
||||
It is equal to \c std::u8string_view if your current C++ standard support it.
|
||||
*/
|
||||
|
||||
|
||||
|
@ -35,7 +35,6 @@ PRIVATE
|
||||
|
||||
# Install testbench only on Release mode
|
||||
install(TARGETS YYCCTestbench
|
||||
EXPORT YYCCTestbenchTargets
|
||||
CONFIGURATIONS Release
|
||||
RUNTIME DESTINATION ${YYCC_INSTALL_PATH_BIN}
|
||||
RUNTIME DESTINATION ${YYCC_INSTALL_BIN_PATH}
|
||||
)
|
||||
|
@ -134,7 +134,8 @@ namespace YYCCTestbench {
|
||||
Console::Write(YYCC_U8("\t> "));
|
||||
|
||||
YYCC::yycc_u8string gotten(Console::ReadLine());
|
||||
Assert(gotten == strl, YYCC::StringHelper::Printf(YYCC_U8("Got: %s"), gotten.c_str()).c_str());
|
||||
if (gotten == strl) Console::FormatLine(YYCC_U8(YYCC_COLOR_LIGHT_GREEN("\tMatched! Got: %s")), gotten.c_str());
|
||||
else Console::FormatLine(YYCC_U8(YYCC_COLOR_LIGHT_RED("\tNOT Matched! Got: %s")), gotten.c_str());
|
||||
}
|
||||
|
||||
}
|
||||
@ -401,7 +402,7 @@ namespace YYCCTestbench {
|
||||
m_FloatSetting(YYCC_U8("float-setting"), 0.0f),
|
||||
m_StringSetting(YYCC_U8("string-setting"), YYCC_U8("")),
|
||||
m_BoolSetting(YYCC_U8("bool-setting"), false),
|
||||
m_ClampedFloatSetting(YYCC_U8("clamped-float-setting"), 0.0f, YYCC::ConfigManager::ConstrainPresets::GetNumberRangeConstrain<float>(-1.0f, 1.0f)),
|
||||
m_ClampedFloatSetting(YYCC_U8("clamped-float-setting"), 0.0f, YYCC::ConfigManager::ConstraintPresets::GetNumberRangeConstraint<float>(-1.0f, 1.0f)),
|
||||
m_EnumSetting(YYCC_U8("enum-setting"), TestEnum::Test1),
|
||||
m_CoreManager(YYCC_U8("test.cfg"), UINT64_C(0), {
|
||||
&m_IntSetting, &m_FloatSetting, &m_StringSetting, &m_BoolSetting, &m_ClampedFloatSetting, &m_EnumSetting
|
||||
@ -436,7 +437,7 @@ namespace YYCCTestbench {
|
||||
// init cfg manager
|
||||
TestConfigManager test;
|
||||
|
||||
// test constrain works
|
||||
// test constraint works
|
||||
Assert(!test.m_ClampedFloatSetting.Set(2.0f), YYCC_U8("YYCC::ConfigManager::Constraint"));
|
||||
Assert(test.m_ClampedFloatSetting.Get() == 0.0f, YYCC_U8("YYCC::ConfigManager::Constraint"));
|
||||
|
||||
|
Reference in New Issue
Block a user