44 Commits

Author SHA1 Message Date
9e5a5970a3 Improved PIBlockingDeque constructors
- resolve creation from constant (see test construct_from_constant_is_max_size_eq_capacity)
- add tests for constructors
2020-08-11 12:30:28 +03:00
46d93c6c9f Improved PIBlockingDeque behaviour and unit tests for put, offer, take methods
- Methods put, offer, take begins working with move and copy semantics
- Mocking queue condition variables with GMock in Unit tests
- Rewrite part of unit tests
2020-08-07 19:12:09 +03:00
662a2fc464 Refactor PIBlockingDequeue 2020-08-07 10:10:05 +03:00
194389ef6d Refactor templates & submit doc 2020-08-06 13:23:49 +03:00
3cfdda7365 PIThreadPoolExecutor & PIBlockingDequeue improvements
- add support move & copy semantic
- introduce submit method for executor with future result
2020-08-05 22:59:33 +03:00
3ec1ecfb5b refactor concurrent module code 2020-08-04 16:39:08 +03:00
be51728570 Merge remote-tracking branch 'origin/master' into concurrent 2020-08-03 17:48:36 +03:00
41e54e5859 Merge pip2 2020-08-03 17:47:19 +03:00
9cd108cf20 tests binary dir fix 2020-08-03 11:10:27 +03:00
22208fbf51 tests binary dir fix 2020-08-03 11:10:05 +03:00
badaa01deb Merge remote-tracking branch 'origin/master' into concurrent
# Conflicts:
#	lib/main/thread/pithreadpoolexecutor.cpp
#	lib/main/thread/pithreadpoolexecutor.h
#	tests/concurrent/ExecutorIntegrationTest.cpp
#	tests/concurrent/ExecutorUnitTest.cpp
#	tests/concurrent/testutil.h
2020-08-03 10:18:52 +03:00
e8a066abcd doc 2020-08-03 09:04:50 +03:00
427e7411c1 move most old PIMap iterators to new
Documentation of PIVector, PIMap and PIMapIterator
2020-08-03 01:43:23 +03:00
df457a1602 rename "iterate" 2020-08-02 19:18:28 +03:00
1dfcaf4952 Merge branch 'master' of https://git.shs.tools/SHS/pip 2020-08-02 15:57:27 +03:00
b468a6d581 PIMapIterator
small PIString optimize
general PIChunkStream pack optimization
2020-08-02 15:57:21 +03:00
b68e8f7a65 Merge picloud branch 2020-08-02 14:00:46 +03:00
1fb5356825 move picompress.h 2020-08-01 23:34:23 +03:00
01f7b15818 remove " " 2020-08-01 23:27:10 +03:00
284971fe8d Merge branch 'master' of https://git.shs.tools/SHS/pip 2020-08-01 23:24:16 +03:00
edacac54f9 PIByteArray rvalue, some fixes 2020-08-01 23:24:08 +03:00
0821742e45 missed exports 2020-08-01 23:18:02 +03:00
2d317a9959 missed exports 2020-08-01 22:42:11 +03:00
7486866c17 CMakeLists.txt fix 2020-08-01 22:34:20 +03:00
c7ac4fa551 Refactored CMakeLists.txt
* new pip_module() macro
 * fixed exports
 * automatic gather all exports and pass them to Doxygen and PICodeParser
2020-08-01 21:29:32 +03:00
21111b3e67 move tests to separate dir
create macro "pip_test()" for easily add new tests
2020-07-31 15:47:08 +03:00
e728b30e5e PIString hard optimization 2020-07-31 14:12:47 +03:00
1d5c979607 fix bug in move constructor 2020-07-31 00:00:26 +03:00
79e17b48b8 rvalue functions for containers 2020-07-30 22:26:05 +03:00
a12e63e569 PIStringList move operator fix 2020-07-30 20:41:38 +03:00
52062e6ccd move operators works 2020-07-30 20:30:24 +03:00
557f2a4d0d replace piForeach* to for(:)
another c++11 try ...
2020-07-30 20:08:33 +03:00
2ffc457566 merged concurrent to main library
removed PIConditionLock, use PIMutex instead
2020-07-30 18:50:42 +03:00
4dd59132d5 LUA lib status, some fixes 2020-07-30 16:17:45 +03:00
48692a4724 remove remote_console 2020-07-30 00:20:19 +03:00
4de3a052f1 time to merge v2 to master 2020-07-29 01:30:46 +03:00
b153673974 CMakeLists.txt 2020-07-27 17:54:07 +03:00
abbbce1380 Merge branch 'pip_2' of https://git.shs.tools/SHS/pip into pip_2 2020-07-25 13:13:58 +03:00
e82831377a CMakeLists.txt 2020-07-25 13:13:53 +03:00
9bd87dcc63 поправил PIP_CONCURRENT_TEST 2020-07-24 14:42:49 +03:00
8efd2cf447 Rewrite executor to template & come back executor unit tests 2020-07-17 18:36:28 +03:00
101164902a Merge branch 'master' into picloud 2020-06-28 09:09:59 +03:00
d3ffc19610 Merge commit '02ac4020d3f7a948c87dd0349db093934c0aed3c' into picloud 2020-06-18 19:09:21 +03:00
3f7f67e198 picloud start develop 2020-06-15 11:09:34 +03:00
150 changed files with 3280 additions and 4070 deletions

View File

@@ -3,8 +3,8 @@ cmake_policy(SET CMP0017 NEW) # need include() with .cmake
project(pip) project(pip)
set(_PIP_MAJOR 1) set(_PIP_MAJOR 1)
set(_PIP_MINOR 99) set(_PIP_MINOR 99)
set(_PIP_REVISION 0) set(_PIP_REVISION 3)
set(_PIP_SUFFIX _prealpha) set(_PIP_SUFFIX _prebeta)
set(_PIP_COMPANY SHS) set(_PIP_COMPANY SHS)
set(_PIP_DOMAIN org.SHS) set(_PIP_DOMAIN org.SHS)
@@ -14,6 +14,7 @@ endif()
include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
set(PIP_BUILD 1) set(PIP_BUILD 1)
include(CheckFunctionExists) include(CheckFunctionExists)
include(GenerateExportHeader)
include(DeployMacros) include(DeployMacros)
include(PIPMacros) include(PIPMacros)
if(NOT DEFINED BUILD_NUMBER) if(NOT DEFINED BUILD_NUMBER)
@@ -40,56 +41,94 @@ set(PIP_UTILS 1)
if(LIBPROJECT) if(LIBPROJECT)
set(PIP_UTILS ${UTILS}) set(PIP_UTILS ${UTILS})
endif() endif()
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD 11)
# Basic # Basic
macro(gather_src DIR CPP H H_P) set(PIP_MODULES)
set(CS)
set(HS)
set(PHS)
file(GLOB CS "${DIR}/*.cpp")
file(GLOB HS "${DIR}/*.h")
file(GLOB PHS "${DIR}/*_p.h")
list(REMOVE_ITEM HS "${PHS}")
list(APPEND ${CPP} ${CS})
list(APPEND ${H} ${HS})
list(APPEND ${H_P} ${PHS})
endmacro()
set(PIP_SRC_MAIN "lib/main")
set(PIP_SRC_CONSOLE "lib/console")
set(PIP_SRC_CRYPT "lib/crypt")
set(PIP_SRC_COMPRESS "lib/compress")
set(PIP_SRC_USB "lib/usb")
set(PIP_SRC_FFTW "lib/fftw")
set(PIP_SRC_OPENCL "lib/opencl")
set(PIP_SRC_IO_UTILS "lib/io_utils")
set(PIP_SRC_CONCURRENT "lib/concurrent")
set(PIP_SRC_CLOUD "lib/cloud")
set(PIP_SRC_LUA "lib/lua")
set(PIP_SRC_DIRS ${PIP_SRC_MAIN}
${PIP_SRC_CONSOLE}
${PIP_SRC_CRYPT}
${PIP_SRC_COMPRESS}
${PIP_SRC_USB}
${PIP_SRC_FFTW}
${PIP_SRC_OPENCL}
${PIP_SRC_IO_UTILS}
${PIP_SRC_CONCURRENT}
${PIP_SRC_CLOUD}
)
set(PIP_LIBS_TARGETS pip)
set(LIBS_MAIN) set(LIBS_MAIN)
set(LIBS_STATUS) set(LIBS_STATUS)
set(HDRS) set(HDRS)
set(PHDRS) set(PHDRS)
set(HDR_DIRS) set(HDR_DIRS)
set(PIP_UTILS_LIST)
set(PIP_TESTS_LIST)
set(PIP_EXPORTS)
if (TESTS) set(PIP_SRC_MODULES "console;crypt;compress;usb;fftw;opencl;io_utils;cloud;lua")
include(DownloadGTest) foreach(_m ${PIP_SRC_MODULES})
set(PIP_CONCURRENT_TEST "lib/concurrent/test") set(PIP_MSG_${_m} "no")
endif() endforeach()
macro(pip_module NAME LIBS LABEL INCLUDES MSG)
set(CPPS)
set(HS)
set(PHS)
set(CRES)
file(GLOB_RECURSE CPPS "lib/${NAME}/*.cpp")
file(GLOB_RECURSE HS "lib/${NAME}/*.h")
file(GLOB_RECURSE PHS "lib/${NAME}/*_p.h")
file(GLOB_RECURSE RES "lib/${NAME}/*conf.h")
list(REMOVE_ITEM HS "${PHS}")
list(APPEND HDRS ${HS})
list(APPEND PHDRS ${PHS})
set(_target "pip_${NAME}")
set(_libs "${LIBS}")
if ("${NAME}" STREQUAL "main")
set(_target "pip")
else()
list(APPEND _libs "pip")
endif()
string(TOUPPER "${_target}" DEF_NAME)
set(PIP_MSG_${NAME} "yes${MSG}")
import_version(${_target} PIP)
set_deploy_property(${_target} ${PIP_LIB_TYPE}
LABEL "${LABEL}"
FULLNAME "${_PIP_DOMAIN}.${_target}"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(${_target} _RC)
set(LINK_LIBS)
foreach (_l ${_libs})
if (${${_l}_FOUND})
list(APPEND LINK_LIBS ${${_l}_LIBRARIES})
else()
list(APPEND LINK_LIBS ${_l})
endif()
endforeach()
if (NOT "${RES}" STREQUAL "")
pip_resources(CRES "${RES}")
endif()
add_definitions(-D${DEF_NAME})
add_library(${_target} ${PIP_LIB_TYPE} ${CPPS} ${CRES} ${_RC})
if (NOT "${RES}" STREQUAL "")
add_dependencies(${_target} pip_rc)
endif()
if (NOT "${INCLUDES}" STREQUAL "")
target_include_directories(${_target} PRIVATE ${INCLUDES})
endif()
generate_export_header(${_target})
list(APPEND HDRS "${CMAKE_CURRENT_BINARY_DIR}/${_target}_export.h")
list(APPEND PIP_EXPORTS "${DEF_NAME}_EXPORT")
target_link_libraries(${_target} ${LINK_LIBS})
list(APPEND PIP_MODULES ${_target})
if (NOT "${LIBS}" STREQUAL "")
list(APPEND LIBS_STATUS ${LIBS})
endif()
endmacro()
macro(pip_find_lib NAME)
find_library(${NAME}_LIBRARIES ${NAME} ${ARGN})
set(${NAME}_FOUND FALSE)
if(${NAME}_LIBRARIES)
set(${NAME}_FOUND TRUE)
endif()
endmacro()
if (DEFINED ENV{QNX_HOST} OR PIP_FREERTOS) if (DEFINED ENV{QNX_HOST} OR PIP_FREERTOS)
set(STATIC_LIB ON) set(STATIC_LIB ON)
@@ -97,11 +136,11 @@ endif()
if(STATIC_LIB) if(STATIC_LIB)
set(PIP_LIB_TYPE STATIC) set(PIP_LIB_TYPE STATIC)
set(PIP_LIB_TYPE_MSG "Static")
add_definitions(-DPIP_STATIC_DEFINE) add_definitions(-DPIP_STATIC_DEFINE)
#message(STATUS "Building PIP static library")
else() else()
set(PIP_LIB_TYPE SHARED) set(PIP_LIB_TYPE SHARED)
#message(STATUS "Building PIP shared library") set(PIP_LIB_TYPE_MSG "Shared")
endif() endif()
@@ -113,16 +152,10 @@ set_version(PIP
BUILD "${BUILD_NUMBER}" BUILD "${BUILD_NUMBER}"
SUFFIX "${_PIP_SUFFIX}" SUFFIX "${_PIP_SUFFIX}"
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/piversion.h") OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/piversion.h")
set_deploy_property(pip ${PIP_LIB_TYPE}
LABEL "PIP main library"
FULLNAME "${_PIP_DOMAIN}.pip"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${PIP_SRC_MAIN}/piversion.h") if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${PIP_SRC_MAIN}/piversion.h")
file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/${PIP_SRC_MAIN}/piversion.h") file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/${PIP_SRC_MAIN}/piversion.h")
endif() endif()
list(APPEND HDRS "${CMAKE_CURRENT_BINARY_DIR}/piversion.h") list(APPEND HDRS "${CMAKE_CURRENT_BINARY_DIR}/piversion.h")
message(STATUS "Building PIP version ${PIP_VERSION} (${PIP_LIB_TYPE})")
if(MINGW) if(MINGW)
find_package(MinGW REQUIRED) find_package(MinGW REQUIRED)
@@ -174,51 +207,26 @@ endif()
# Compiler # Compiler
get_filename_component(C_COMPILER "${CMAKE_C_COMPILER}" NAME) get_filename_component(C_COMPILER "${CMAKE_C_COMPILER}" NAME)
#message("${C_COMPILER}")
# Sources
# Main lib # Main lib
set(PIP_FOLDERS "." "core" "containers" "thread" "system" "io_devices" "io_utils" "console" "math" "code" "geo" "resources" "opencl" "crypt" "introspection" "concurrent" "cloud" "lua") file(GLOB PIP_FOLDERS LIST_DIRECTORIES TRUE "${CMAKE_CURRENT_SOURCE_DIR}/lib/main/*")
include_directories("${PIP_SRC_MAIN}") list(APPEND PIP_FOLDERS "${CMAKE_CURRENT_SOURCE_DIR}/lib/main")
set(PIP_MAIN_FOLDERS) set(PIP_MAIN_FOLDERS)
foreach(F ${PIP_FOLDERS}) foreach(F ${PIP_FOLDERS})
list(APPEND PIP_MAIN_FOLDERS "\"${PROJECT_SOURCE_DIR}/${PIP_SRC_MAIN}/${F}\"") if (IS_DIRECTORY "${F}")
include_directories("${PIP_SRC_MAIN}/${F}") list(APPEND PIP_MAIN_FOLDERS "${F}")
gather_src("${PIP_SRC_MAIN}/${F}" CPP_LIB_MAIN HDRS PHDRS) include_directories("${F}")
endif()
endforeach(F) endforeach(F)
# Crypt lib if (DEFINED LIBPROJECT)
gather_src("${PIP_SRC_CRYPT}" CPP_LIB_CRYPT HDRS PHDRS) set(PIP_MAIN_FOLDERS "${PIP_MAIN_FOLDERS}" PARENT_SCOPE)
endif()
# Console lib if (TESTS)
gather_src("${PIP_SRC_CONSOLE}" CPP_LIB_CONSOLE HDRS PHDRS) set(PIP_ROOT_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}")
add_subdirectory(tests)
# Compress lib endif()
gather_src("${PIP_SRC_COMPRESS}" CPP_LIB_COMPRESS HDRS PHDRS)
# USB lib
gather_src("${PIP_SRC_USB}" CPP_LIB_USB HDRS PHDRS)
# FFTW lib
gather_src("${PIP_SRC_FFTW}" CPP_LIB_FFTW HDRS PHDRS)
# OpenCL lib
gather_src("${PIP_SRC_OPENCL}" CPP_LIB_OPENCL HDRS PHDRS)
# IO Utils lib
gather_src("${PIP_SRC_IO_UTILS}" CPP_LIB_IO_UTILS HDRS PHDRS)
# Concurrent lib
gather_src("${PIP_SRC_CONCURRENT}" CPP_LIB_CONCURRENT HDRS PHDRS)
gather_src("${PIP_CONCURRENT_TEST}" CPP_CONCURRENT_TEST HDRS PHDRS)
# Cloud lib
gather_src("${PIP_SRC_CLOUD}" CPP_LIB_CLOUD HDRS PHDRS)
# LUA lib
gather_src("${PIP_SRC_LUA}" CPP_LIB_LUA HDRS PHDRS)
if(PIP_FREERTOS) if(PIP_FREERTOS)
add_definitions(-DPIP_FREERTOS) add_definitions(-DPIP_FREERTOS)
@@ -262,51 +270,47 @@ if((NOT DEFINED ENV{QNX_HOST}) AND (NOT APPLE) AND (NOT WIN32) AND (NOT DEFINED
list(APPEND LIBS_MAIN rt) list(APPEND LIBS_MAIN rt)
set(CMAKE_REQUIRED_LIBRARIES rt) set(CMAKE_REQUIRED_LIBRARIES rt)
endif() endif()
CHECK_FUNCTION_EXISTS(timer_create PIP_TIMER_RT_0) CHECK_FUNCTION_EXISTS(timer_create PIP_TIMER_RT_0)
CHECK_FUNCTION_EXISTS(timer_settime PIP_TIMER_RT_1) CHECK_FUNCTION_EXISTS(timer_settime PIP_TIMER_RT_1)
CHECK_FUNCTION_EXISTS(timer_delete PIP_TIMER_RT_2) CHECK_FUNCTION_EXISTS(timer_delete PIP_TIMER_RT_2)
# Check if build debug version # Check if build debug version
if (CMAKE_BUILD_TYPE MATCHES Debug) if (CMAKE_BUILD_TYPE MATCHES Debug)
set(PIP_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g3 -Wall") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g3 -Wall")
add_definitions(-DPIP_DEBUG) add_definitions(-DPIP_DEBUG)
message(STATUS "Building PIP debug version")
else() else()
set(PIP_BUILD_TYPE "Release")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -Wall") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -Wall")
message(STATUS "Building PIP release version")
endif() endif()
# Check if std::iostream operators support # Check if std::iostream operators support
set(PIP_STD_IOSTREAM "no")
if(STD_IOSTREAM) if(STD_IOSTREAM)
set(PIP_STD_IOSTREAM "yes")
add_definitions(-DPIP_STD_IOSTREAM) add_definitions(-DPIP_STD_IOSTREAM)
message(STATUS "Building PIP with std iostream operators support")
else()
message(STATUS "Building PIP without std iostream operators support")
endif() endif()
# Check if ICU used for PIString and PIChar # Check if ICU used for PIString and PIChar
set(PIP_ICU "no")
if(ICU) if(ICU)
message(STATUS "Building PIP with ICU") set(PIP_ICU "yes")
add_definitions(-DPIP_ICU) add_definitions(-DPIP_ICU)
list(APPEND LIBS_MAIN icuuc) list(APPEND LIBS_MAIN icuuc)
else()
message(STATUS "Building PIP without ICU")
endif() endif()
# Check if PIP should be built with introspection # Check if PIP should be built with introspection
set(_PIP_DEFS "") set(_PIP_DEFS "")
set(_PIP_DEFS_FILE "${CMAKE_CURRENT_BINARY_DIR}/pip_defs.h") set(_PIP_DEFS_FILE "${CMAKE_CURRENT_BINARY_DIR}/pip_defs.h")
set(PIP_INTROSPECTION "no")
if(INTROSPECTION) if(INTROSPECTION)
message(STATUS "Building PIP with introspection") set(PIP_INTROSPECTION "yes")
message(STATUS "Warning: Introspection reduces the performance!")
add_definitions(-DPIP_INTROSPECTION) add_definitions(-DPIP_INTROSPECTION)
set(_PIP_DEFS "PIP_INTROSPECTION") set(_PIP_DEFS "PIP_INTROSPECTION")
else()
message(STATUS "Building PIP without introspection")
endif() endif()
if ((NOT DEFINED _PIP_SAVED_DEFS) OR (NOT "x${_PIP_SAVED_DEFS}" STREQUAL "x${_PIP_DEFS}")) if ((NOT DEFINED _PIP_SAVED_DEFS) OR (NOT "x${_PIP_SAVED_DEFS}" STREQUAL "x${_PIP_DEFS}"))
set(_PIP_SAVED_DEFS "${_PIP_DEFS}" CACHE STRING "pip_defs" FORCE) set(_PIP_SAVED_DEFS "${_PIP_DEFS}" CACHE STRING "pip_defs" FORCE)
@@ -321,10 +325,10 @@ list(APPEND HDRS ${_PIP_DEFS_FILE})
# Check if RT timers exists # Check if RT timers exists
if(PIP_TIMER_RT_0 AND PIP_TIMER_RT_1 AND PIP_TIMER_RT_2) if(PIP_TIMER_RT_0 AND PIP_TIMER_RT_1 AND PIP_TIMER_RT_2)
set(PIP_TIMERS "Thread, ThreadRT, Pool")
add_definitions(-DPIP_TIMER_RT) add_definitions(-DPIP_TIMER_RT)
message(STATUS "Building PIP with timers: Thread, ThreadRT, Pool")
else() else()
message(STATUS "Building PIP with timers: Thread, Pool") set(PIP_TIMERS "Thread, Pool")
endif() endif()
@@ -360,19 +364,12 @@ if(PIP_FREERTOS)
set(PIP_LIBS ${LIBS_MAIN}) set(PIP_LIBS ${LIBS_MAIN})
else() else()
foreach(LIB_ ${LIBS_MAIN}) foreach(LIB_ ${LIBS_MAIN})
find_library(${LIB_}_FOUND ${LIB_}) pip_find_lib(${LIB_})
if(${LIB_}_FOUND)
list(APPEND CMAKE_REQUIRED_LIBRARIES ${${LIB_}_FOUND})
list(APPEND PIP_LIBS ${${LIB_}_FOUND})
endif()
endforeach() endforeach()
endif() endif()
list(APPEND LIBS_STATUS ${LIBS_MAIN})
import_version(pip PIP) import_version(pip PIP)
if(WIN32) if(WIN32)
make_rc(pip _RC)
add_definitions(-DPSAPI_VERSION=1) add_definitions(-DPSAPI_VERSION=1)
add_library(pip ${PIP_LIB_TYPE} ${CPP_LIB_MAIN} ${HDRS} ${PHDRS} ${_RC})
if(${C_COMPILER} STREQUAL "cl.exe") if(${C_COMPILER} STREQUAL "cl.exe")
set(CMAKE_CXX_FLAGS "/O2 /Ob2 /Ot /W0") set(CMAKE_CXX_FLAGS "/O2 /Ob2 /Ot /W0")
endif() endif()
@@ -380,91 +377,37 @@ else()
set(${CMAKE_CXX_FLAGS} "${CMAKE_CXX_FLAGS} -fPIC") set(${CMAKE_CXX_FLAGS} "${CMAKE_CXX_FLAGS} -fPIC")
if(DEFINED ENV{QNX_HOST} OR PIP_FREERTOS) if(DEFINED ENV{QNX_HOST} OR PIP_FREERTOS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftemplate-depth-32") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftemplate-depth-32")
else()
endif() endif()
add_library(pip ${PIP_LIB_TYPE} ${CPP_LIB_MAIN})
endif() endif()
set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS}")
include(GenerateExportHeader)
generate_export_header(pip)
list(APPEND HDRS "${CMAKE_CURRENT_BINARY_DIR}/pip_export.h") pip_module(main "${LIBS_MAIN}" "PIP main library" "" "")
target_link_libraries(pip ${PIP_LIBS})
if (NOT CROSSTOOLS) if (NOT CROSSTOOLS)
if (NOT PIP_FREERTOS) if (NOT PIP_FREERTOS)
# Check if USB is supported
find_library(usb_FOUND usb SHARED)
pip_module(console "" "PIP console support" "" "")
pip_find_lib(usb)
if(usb_FOUND) if(usb_FOUND)
message(STATUS "Building PIP with USB support") pip_module(usb "usb" "PIP usb support" "" "")
import_version(pip_usb pip)
set_deploy_property(pip_usb ${PIP_LIB_TYPE}
LABEL "PIP usb support"
FULLNAME "${_PIP_DOMAIN}.pip_usb"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_usb _RC)
add_definitions(-DPIP_USB)
add_library(pip_usb ${PIP_LIB_TYPE} ${CPP_LIB_USB} ${_RC})
target_link_libraries(pip_usb pip ${usb_FOUND})
list(APPEND LIBS_STATUS usb)
list(APPEND PIP_LIBS_TARGETS pip_usb)
else()
message(STATUS "Building PIP without USB support")
endif() endif()
# Add console library pip_find_lib(zlib NAMES z zlib)
import_version(pip_console pip)
set_deploy_property(pip_console ${PIP_LIB_TYPE}
LABEL "PIP console support"
FULLNAME "${_PIP_DOMAIN}.pip_console"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_console _RC)
add_library(pip_console ${PIP_LIB_TYPE} ${CPP_LIB_CONSOLE} ${_RC})
target_link_libraries(pip_console pip)
list(APPEND PIP_LIBS_TARGETS pip_console)
# Check if PIP support cryptographic encryption/decryption using sodium library
find_library(sodium_FOUND sodium)
if(sodium_FOUND)
message(STATUS "Building PIP with crypt support")
import_version(pip_crypt pip)
set_deploy_property(pip_crypt ${PIP_LIB_TYPE}
LABEL "PIP crypt support"
FULLNAME "${_PIP_DOMAIN}.pip_crypt"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_crypt _RC)
add_definitions(-DPIP_CRYPT)
add_library(pip_crypt ${PIP_LIB_TYPE} ${CPP_LIB_CRYPT} ${_RC})
target_link_libraries(pip_crypt pip ${sodium_FOUND})
list(APPEND LIBS_STATUS sodium)
list(APPEND PIP_LIBS_TARGETS pip_crypt)
else()
message(STATUS "Building PIP without crypt support")
endif()
# Check if PIP support compress/decompress using zlib library
find_library(zlib_FOUND NAMES z zlib)
if(zlib_FOUND) if(zlib_FOUND)
message(STATUS "Building PIP with zlib compress support") pip_module(compress "zlib" "PIP compression support" "" "")
import_version(pip_compress pip) endif()
set_deploy_property(pip_compress ${PIP_LIB_TYPE}
LABEL "PIP compression support"
FULLNAME "${_PIP_DOMAIN}.pip_compress" pip_find_lib(sodium)
COMPANY "${_PIP_COMPANY}" if(sodium_FOUND)
INFO "Platform-Independent Primitives") pip_module(crypt "sodium" "PIP crypt support" "" "")
make_rc(pip_compress _RC) pip_module(cloud "pip_crypt" "PIP cloud support" "" "")
add_definitions(-DPIP_COMPRESS)
add_library(pip_compress ${PIP_LIB_TYPE} ${CPP_LIB_COMPRESS} ${_RC})
target_link_libraries(pip_compress pip ${zlib_FOUND})
list(APPEND LIBS_STATUS zlib)
list(APPEND PIP_LIBS_TARGETS pip_compress)
else()
message(STATUS "Building PIP without compress support")
endif() endif()
@@ -474,7 +417,6 @@ if (NOT CROSSTOOLS)
set(FFTW_LIB_SUFFIXES2 "" "-3") set(FFTW_LIB_SUFFIXES2 "" "-3")
set(FFTW_LIBS) set(FFTW_LIBS)
set(FFTW_ABS_LIBS) set(FFTW_ABS_LIBS)
set(PIP_FFTW_FOUND)
set(CMAKE_REQUIRED_INCLUDES fftw3.h) set(CMAKE_REQUIRED_INCLUDES fftw3.h)
foreach(FFTW_S_ IN LISTS FFTW_LIB_SUFFIXES) foreach(FFTW_S_ IN LISTS FFTW_LIB_SUFFIXES)
set(FFTW_BREAK false) set(FFTW_BREAK false)
@@ -482,164 +424,66 @@ if (NOT CROSSTOOLS)
if(NOT FFTW_BREAK) if(NOT FFTW_BREAK)
set(FFTW_CLN "${FFTW_LIB_NAME}${FFTW_S_}${FFTW_S2_}") set(FFTW_CLN "${FFTW_LIB_NAME}${FFTW_S_}${FFTW_S2_}")
set(FFTW_CLNT "${FFTW_LIB_NAME}${FFTW_S_}_threads${FFTW_S2_}") set(FFTW_CLNT "${FFTW_LIB_NAME}${FFTW_S_}_threads${FFTW_S2_}")
find_library(${FFTW_CLN}_FOUND ${FFTW_CLN}) find_library(${FFTW_CLN}_LIBRARIES ${FFTW_CLN})
find_library(${FFTW_CLNT}_FOUND ${FFTW_CLNT}) find_library(${FFTW_CLNT}_LIBRARIES ${FFTW_CLNT})
if(${FFTW_CLN}_FOUND) set(${FFTW_CLN}_FOUND FALSE)
set(${FFTW_CLNT}_FOUND FALSE)
if(${FFTW_CLN}_LIBRARIES)
set(${FFTW_CLN}_FOUND TRUE)
list(APPEND FFTW_LIBS "${FFTW_CLN}") list(APPEND FFTW_LIBS "${FFTW_CLN}")
list(APPEND FFTW_ABS_LIBS "${${FFTW_CLN}_FOUND}") list(APPEND FFTW_ABS_LIBS "${${FFTW_CLN}_LIBRARIES}")
#message(STATUS "PIFFTW found ${FFTW_CLN} = ${${FFTW_CLN}_FOUND}")
set(${FFTW_CLN}_CTS "${FFTW_CLN}") set(${FFTW_CLN}_CTS "${FFTW_CLN}")
if(${FFTW_CLNT}_FOUND) if(${FFTW_CLNT}_FLIBRARIES)
set(${FFTW_CLNT}_FOUND TRUE)
list(APPEND FFTW_LIBS "${FFTW_CLNT}") list(APPEND FFTW_LIBS "${FFTW_CLNT}")
list(APPEND FFTW_ABS_LIBS "${${FFTW_CLNT}_FOUND}") list(APPEND FFTW_ABS_LIBS "${${FFTW_CLNT}_LIBRARIES}")
list(APPEND ${FFTW_CLN}_CTS "${FFTW_CLNT}") list(APPEND ${FFTW_CLN}_CTS "${FFTW_CLNT}")
endif() endif()
set(CMAKE_REQUIRED_LIBRARIES ${${FFTW_CLN}_CTS}) set(CMAKE_REQUIRED_LIBRARIES ${${FFTW_CLN}_CTS})
CHECK_FUNCTION_EXISTS(fftw${FFTW_S_}_make_planner_thread_safe ${FFTW_CLN}_TSFE) CHECK_FUNCTION_EXISTS(fftw${FFTW_S_}_make_planner_thread_safe ${FFTW_CLN}_TSFE)
add_definitions(-DPIP_FFTW${FFTW_S_}) add_definitions(-DPIP_FFTW${FFTW_S_})
set(PIP_FFTW_FOUND true)
if(${FFTW_CLN}_TSFE) if(${FFTW_CLN}_TSFE)
add_definitions(-DPIP_FFTW${FFTW_S_}_THREADSAFE) add_definitions(-DPIP_FFTW${FFTW_S_}_THREADSAFE)
else() else()
message(STATUS "Warning: PIFFTW${FFTW_S_}::preparePlan was not threadsafe") message(STATUS "Warning: PIFFTW${FFTW_S_}::preparePlan was not threadsafe")
endif() endif()
#message(STATUS "${FFTW_CLN} -> ${${FFTW_CLN}_TSFE}")
endif() endif()
endif() endif()
endforeach() endforeach()
endforeach() endforeach()
if(FFTW_LIBS) if(FFTW_LIBS)
message(STATUS "Building PIP with fftw3 support: ${FFTW_LIBS}") pip_module(fftw "${FFTW_LIBS}" "PIP FFTW support" "" "")
import_version(pip_fftw pip)
set_deploy_property(pip_fftw ${PIP_LIB_TYPE}
LABEL "PIP FFTW support"
FULLNAME "${_PIP_DOMAIN}.pip_fftw"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_fftw _RC)
add_library(pip_fftw ${PIP_LIB_TYPE} ${CPP_LIB_FFTW} ${_RC})
target_link_libraries(pip_fftw pip ${FFTW_ABS_LIBS})
list(APPEND LIBS_STATUS ${FFTW_LIBS})
list(APPEND PIP_LIBS_TARGETS pip_fftw)
else()
message(STATUS "Building PIP without fftw3 support")
endif() endif()
# Check if PIP support OpenCL find_package(OpenCL QUIET) #OpenCL_VERSION_STRING
find_package(OpenCL QUIET)
if(OpenCL_FOUND) if(OpenCL_FOUND)
message(STATUS "Building PIP with OpenCL support") set(_opencl_lib OpenCL::OpenCL)
import_version(pip_opencl pip)
set_deploy_property(pip_opencl ${PIP_LIB_TYPE}
LABEL "PIP OpenCL support"
FULLNAME "${_PIP_DOMAIN}.pip_opencl"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_opencl _RC)
if(APPLE)
include_directories(${OpenCL_INCLUDE_DIRS}/Headers)
else()
include_directories(${OpenCL_INCLUDE_DIRS})
endif()
add_definitions(-DPIP_OPENCL)
pip_resources(CL_RES "${PIP_SRC_OPENCL}/resources.conf")
add_library(pip_opencl ${PIP_LIB_TYPE} ${CPP_LIB_OPENCL} ${CL_RES} ${_RC})
add_dependencies(pip_opencl pip_rc)
if(${CMAKE_VERSION} VERSION_LESS "3.7.0") if(${CMAKE_VERSION} VERSION_LESS "3.7.0")
target_link_libraries(pip_opencl pip OpenCL) target_link_libraries(_opencl_lib OpenCL)
else()
target_link_libraries(pip_opencl pip OpenCL::OpenCL)
endif() endif()
list(APPEND LIBS_STATUS OpenCL) pip_module(opencl "${_opencl_lib}" "PIP OpenCL support" "" " (${OpenCL_VERSION_STRING})")
list(APPEND PIP_LIBS_TARGETS pip_opencl)
set(OpenCL_FOUND ${OpenCL_LIBRARIES})
else()
message(STATUS "Building PIP without OpenCL support")
endif() endif()
# Check if PIP IO Utils library supports crypt
set(IO_UTILS_LIBS pip)
import_version(pip_io_utils pip)
set_deploy_property(pip_io_utils ${PIP_LIB_TYPE}
LABEL "PIP I/O utilites"
FULLNAME "${_PIP_DOMAIN}.pip_io_utils"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_io_utils _RC)
add_library(pip_io_utils ${PIP_LIB_TYPE} ${CPP_LIB_IO_UTILS} ${_RC})
if(sodium_FOUND) if(sodium_FOUND)
message(STATUS "Building PIP IO Utils library with crypt support") pip_module(io_utils "pip_crypt" "PIP I/O support" "" " (+crypt)")
list(APPEND IO_UTILS_LIBS pip_crypt)
else() else()
message(STATUS "Building PIP IO Utils library without crypt support, attention!") pip_module(io_utils "" "PIP I/O support" "" "")
endif()
target_link_libraries(pip_io_utils ${IO_UTILS_LIBS})
list(APPEND PIP_LIBS_TARGETS pip_io_utils)
# Concurrent module
set(CONCURRENT_LIBS pip)
import_version(pip_concurrent pip)
set_deploy_property(pip_concurrent ${PIP_LIB_TYPE}
LABEL "PIP concurrent support"
FULLNAME "${_PIP_DOMAIN}.pip_concurrent"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_concurrent _RC)
add_library(pip_concurrent ${PIP_LIB_TYPE} ${CPP_LIB_CONCURRENT} ${_RC})
target_link_libraries(pip_concurrent ${CONCURRENT_LIBS})
set_property(TARGET pip_concurrent PROPERTY CXX_STANDARD 11)
list(APPEND PIP_LIBS_TARGETS pip_concurrent)
# Enable build tests for concurrent module
if(CONCURRENT_TESTS)
add_executable(pip_concurrent_test ${CPP_CONCURRENT_TEST})
target_link_libraries(pip_concurrent_test gtest_main gmock_main pip_concurrent)
add_test(NAME pip_concurrent_test COMMAND tests)
add_custom_target(pip_concurrent_test_perform ALL COMMAND pip_concurrent_test)
endif() endif()
# Build cloud library if crypt enabled
if(sodium_FOUND)
message(STATUS "Building PICloud support")
import_version(pip_cloud pip)
set_deploy_property(pip_cloud ${PIP_LIB_TYPE}
LABEL "PIP cloud transport support"
FULLNAME "${_PIP_DOMAIN}.pip_cloud"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_cloud _RC)
add_definitions(-DPIP_CLOUD)
add_library(pip_cloud ${PIP_LIB_TYPE} ${CPP_LIB_CLOUD} ${_RC})
target_link_libraries(pip_cloud pip pip_crypt)
list(APPEND PIP_LIBS_TARGETS pip_cloud)
endif()
# Check Lua support # Check Lua support
if(MINGW) if(MINGW)
set(LUA_INCLUDE_DIR ${MINGW_INCLUDE}) set(LUA_INCLUDE_DIR ${MINGW_INCLUDE})
endif() endif()
find_package(Lua QUIET) find_package(Lua QUIET)
if (LUA_FOUND) if (LUA_FOUND)
message(STATUS "Building PIP with Lua support") pip_module(lua "LUA" "PIP Lua support" "${LUA_INCLUDE_DIR};${CMAKE_CURRENT_SOURCE_DIR}/lib/lua/3rd" " (${LUA_VERSION_STRING})")
import_version(pip_lua pip)
set_deploy_property(pip_lua ${PIP_LIB_TYPE}
LABEL "PIP Lua support"
FULLNAME "${_PIP_DOMAIN}.pip_lua"
COMPANY "${_PIP_COMPANY}"
INFO "Platform-Independent Primitives")
make_rc(pip_lua _RC)
add_definitions(-DPIP_LUA)
include_directories(${LUA_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/lib/lua/3rd)
list(APPEND HDR_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/lib/lua/3rd/LuaBridge") list(APPEND HDR_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/lib/lua/3rd/LuaBridge")
add_library(pip_lua ${PIP_LIB_TYPE} ${CPP_LIB_LUA} ${_RC})
target_link_libraries(pip_lua pip ${LUA_LIBRARIES})
list(APPEND PIP_LIBS_TARGETS pip_lua)
endif() endif()
# Test program # Test program
if(PIP_UTILS) if(PIP_UTILS)
add_executable(pip_test "main.cpp") add_executable(pip_test "main.cpp")
@@ -651,26 +495,29 @@ if (NOT CROSSTOOLS)
else() else()
message(STATUS "Building PIP with crypt support") set(PIP_MSG_crypt "yes")
set(PIP_MSG_compress "yes")
set(PIP_MODULES pip)
add_definitions(-DPIP_CRYPT) add_definitions(-DPIP_CRYPT)
add_library(pip_crypt ${PIP_LIB_TYPE} ${CPP_LIB_CRYPT}) add_library(pip_crypt ${PIP_LIB_TYPE} ${CPP_LIB_CRYPT})
target_link_libraries(pip_crypt pip) target_link_libraries(pip_crypt pip)
list(APPEND PIP_LIBS_TARGETS pip_crypt) list(APPEND PIP_MODULES pip_crypt)
set(IO_UTILS_LIBS pip) set(IO_UTILS_LIBS pip)
add_library(pip_io_utils ${PIP_LIB_TYPE} ${CPP_LIB_IO_UTILS}) add_library(pip_io_utils ${PIP_LIB_TYPE} ${CPP_LIB_IO_UTILS})
message(STATUS "Building PIP IO Utils library with crypt support")
list(APPEND IO_UTILS_LIBS pip_crypt) list(APPEND IO_UTILS_LIBS pip_crypt)
target_link_libraries(pip_io_utils ${IO_UTILS_LIBS}) target_link_libraries(pip_io_utils ${IO_UTILS_LIBS})
list(APPEND PIP_LIBS_TARGETS pip_io_utils) list(APPEND PIP_MODULES pip_io_utils)
message(STATUS "Building PIP with zlib compress support")
add_definitions(-DPIP_COMPRESS) add_definitions(-DPIP_COMPRESS)
add_library(pip_compress ${PIP_LIB_TYPE} ${CPP_LIB_COMPRESS}) add_library(pip_compress ${PIP_LIB_TYPE} ${CPP_LIB_COMPRESS})
target_link_libraries(pip_compress pip) target_link_libraries(pip_compress pip)
list(APPEND PIP_LIBS_TARGETS pip_compress) list(APPEND PIP_MODULES pip_compress)
endif() endif()
endif() endif()
string(REPLACE ";" "," PIP_EXPORTS_STR "${PIP_EXPORTS}")
target_compile_definitions(pip PRIVATE "PICODE_DEFINES=\"${PIP_EXPORTS_STR}\"")
# Install # Install
# Check if system or local install will be used (to system install use "-DLIB=" argument of cmake) # Check if system or local install will be used (to system install use "-DLIB=" argument of cmake)
if(LIB) if(LIB)
@@ -682,9 +529,9 @@ if(LIB)
if(HDR_DIRS) if(HDR_DIRS)
install(DIRECTORY ${HDR_DIRS} DESTINATION ${MINGW_INCLUDE}/pip) install(DIRECTORY ${HDR_DIRS} DESTINATION ${MINGW_INCLUDE}/pip)
endif() endif()
install(TARGETS ${PIP_LIBS_TARGETS} ARCHIVE DESTINATION ${MINGW_LIB}) install(TARGETS ${PIP_MODULES} ARCHIVE DESTINATION ${MINGW_LIB})
endif() endif()
install(TARGETS ${PIP_LIBS_TARGETS} RUNTIME DESTINATION ${MINGW_BIN}) install(TARGETS ${PIP_MODULES} RUNTIME DESTINATION ${MINGW_BIN})
find_library(STDLIB "stdc++-6" PATHS ${MINGW_BIN} NO_DEFAULT_PATH) find_library(STDLIB "stdc++-6" PATHS ${MINGW_BIN} NO_DEFAULT_PATH)
find_library(STDLIB "stdc++-6") find_library(STDLIB "stdc++-6")
#message("${STDLIB}") #message("${STDLIB}")
@@ -694,7 +541,6 @@ if(LIB)
file(COPY "${STDLIB}" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/utils/deploy_tool") file(COPY "${STDLIB}" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/utils/deploy_tool")
endif() endif()
else() else()
#message("${CMAKE_CURRENT_BINARY_DIR}/pip_export.h")
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/pip_export.h DESTINATION include) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/pip_export.h DESTINATION include)
endif() endif()
else() else()
@@ -704,24 +550,22 @@ if(LIB)
install(DIRECTORY ${HDR_DIRS} DESTINATION ${CMAKE_INSTALL_PREFIX}/include/pip) install(DIRECTORY ${HDR_DIRS} DESTINATION ${CMAKE_INSTALL_PREFIX}/include/pip)
endif() endif()
endif() endif()
install(TARGETS ${PIP_LIBS_TARGETS} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib) install(TARGETS ${PIP_MODULES} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
endif() endif()
message(STATUS "Install ${PROJECT_NAME} to system \"${CMAKE_INSTALL_PREFIX}\"")
file(GLOB CMAKES "cmake/*.cmake" "cmake/*.in" "cmake/android_debug.keystore") file(GLOB CMAKES "cmake/*.cmake" "cmake/*.in" "cmake/android_debug.keystore")
install(FILES ${CMAKES} DESTINATION ${CMAKE_ROOT}/Modules) install(FILES ${CMAKES} DESTINATION ${CMAKE_ROOT}/Modules)
else() else()
if(NOT PIP_FREERTOS) if(NOT PIP_FREERTOS)
if(WIN32) if(WIN32)
install(TARGETS ${PIP_LIBS_TARGETS} RUNTIME DESTINATION bin) install(TARGETS ${PIP_MODULES} RUNTIME DESTINATION bin)
install(TARGETS ${PIP_LIBS_TARGETS} ARCHIVE DESTINATION lib) install(TARGETS ${PIP_MODULES} ARCHIVE DESTINATION lib)
else() else()
install(TARGETS ${PIP_LIBS_TARGETS} DESTINATION lib) install(TARGETS ${PIP_MODULES} DESTINATION lib)
endif() endif()
install(FILES ${HDRS} DESTINATION include/pip) install(FILES ${HDRS} DESTINATION include/pip)
if(HDR_DIRS) if(HDR_DIRS)
install(DIRECTORY ${HDR_DIRS} DESTINATION include/pip) install(DIRECTORY ${HDR_DIRS} DESTINATION include/pip)
endif() endif()
message(STATUS "Install ${PROJECT_NAME} to local \"bin\", \"lib\" and \"include\"")
endif() endif()
endif() endif()
@@ -729,7 +573,7 @@ if(NOT PIP_FREERTOS)
# Auxiliary # Auxiliary
if (NOT CROSSTOOLS) if (NOT CROSSTOOLS)
add_subdirectory("${PIP_SRC_MAIN}/auxiliary/piterminal") add_subdirectory("utils/piterminal")
endif() endif()
# Utils # Utils
@@ -738,7 +582,6 @@ if(NOT PIP_FREERTOS)
add_subdirectory("utils/deploy_tool") add_subdirectory("utils/deploy_tool")
if(PIP_UTILS AND (NOT CROSSTOOLS)) if(PIP_UTILS AND (NOT CROSSTOOLS))
add_subdirectory("utils/system_test") add_subdirectory("utils/system_test")
add_subdirectory("utils/remote_console")
add_subdirectory("utils/udp_file_transfer") add_subdirectory("utils/udp_file_transfer")
if(sodium_FOUND) if(sodium_FOUND)
add_subdirectory("utils/system_daemon") add_subdirectory("utils/system_daemon")
@@ -751,20 +594,11 @@ endif()
# Libraries messages # Libraries messages
message(STATUS "Building PIP modules: ${PIP_LIBS_TARGETS}")
if(DEFINED LIBPROJECT) if(DEFINED LIBPROJECT)
set(PIP_LIBS_TARGETS ${PIP_LIBS_TARGETS} PARENT_SCOPE) set(PIP_MODULES ${PIP_MODULES} PARENT_SCOPE)
list(APPEND _ALL_TARGETS ${PIP_LIBS_TARGETS}) list(APPEND _ALL_TARGETS ${PIP_MODULES})
set(_ALL_TARGETS ${_ALL_TARGETS} PARENT_SCOPE) set(_ALL_TARGETS ${_ALL_TARGETS} PARENT_SCOPE)
endif() endif()
if(NOT PIP_FREERTOS)
foreach(LIB_ ${LIBS_STATUS})
message(STATUS "Library ${LIB_} -> " ${${LIB_}_FOUND})
if(NOT ${LIB_}_FOUND)
message(WARNING "Library ${LIB_} not found, please install it")
endif()
endforeach()
endif()
# #
# Build Documentation # Build Documentation
@@ -776,8 +610,9 @@ if ((NOT PIP_FREERTOS) AND (NOT CROSSTOOLS))
set(DOXY_PROJECT_NUMBER "${PIP_VERSION}") set(DOXY_PROJECT_NUMBER "${PIP_VERSION}")
set(DOXY_QHP_CUST_FILTER_ATTRS "\"PIP ${PIP_VERSION}\"") set(DOXY_QHP_CUST_FILTER_ATTRS "\"PIP ${PIP_VERSION}\"")
set(DOXY_QHP_SECT_FILTER_ATTRS "\"PIP ${PIP_VERSION}\"") set(DOXY_QHP_SECT_FILTER_ATTRS "\"PIP ${PIP_VERSION}\"")
set(DOXY_EXAMPLE_PATH "\"${PROJECT_SOURCE_DIR}/doc/examples\"") set(DOXY_EXAMPLE_PATH "\"${CMAKE_CURRENT_SOURCE_DIR}/doc/examples\"")
set(DOXY_IMAGE_PATH "\"${PROJECT_SOURCE_DIR}/doc/images\"") set(DOXY_IMAGE_PATH "\"${CMAKE_CURRENT_SOURCE_DIR}/doc/images\"")
set(DOXY_EXCLUDE "\"${CMAKE_CURRENT_SOURCE_DIR}/lib/lua/3rd\"")
if(DOXYGEN_DOT_EXECUTABLE) if(DOXYGEN_DOT_EXECUTABLE)
string(REPLACE "\\" "" _DOT_PATH "${DOXYGEN_DOT_PATH}") string(REPLACE "\\" "" _DOT_PATH "${DOXYGEN_DOT_PATH}")
set(DOXY_DOT_PATH "\"${_DOT_PATH}\"") set(DOXY_DOT_PATH "\"${_DOT_PATH}\"")
@@ -785,13 +620,70 @@ if ((NOT PIP_FREERTOS) AND (NOT CROSSTOOLS))
set(DOXY_DIA_PATH "\"${_DOT_PATH}\"") set(DOXY_DIA_PATH "\"${_DOT_PATH}\"")
endif() endif()
set(DOXY_INPUT) set(DOXY_INPUT)
foreach(F ${PIP_SRC_DIRS}) foreach(F ${PIP_MAIN_FOLDERS})
list(APPEND DOXY_INPUT "\"${PROJECT_SOURCE_DIR}/${F}\"") list(APPEND DOXY_INPUT "\"${F}\"")
endforeach(F) endforeach(F)
string(REPLACE ";" " " DOXY_INPUT "${DOXY_INPUT}") string(REPLACE ";" " " DOXY_INPUT "\"${CMAKE_CURRENT_SOURCE_DIR}/lib\"")
string(REPLACE ";" " " DOXY_INCLUDE_PATH "${PIP_MAIN_FOLDERS}") string(REPLACE ";" " " DOXY_INCLUDE_PATH "${DOXY_INPUT}")
string(REPLACE ";" " " DOXY_DEFINES "${PIP_EXPORTS};DOXYGEN;PIOBJECT;PIOBJECT_SUBCLASS")
add_documentation(doc doc/Doxyfile.in) add_documentation(doc doc/Doxyfile.in)
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doc/html DESTINATION ../share/doc/pip COMPONENT doc EXCLUDE_FROM_ALL OPTIONAL) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doc/html DESTINATION ../share/doc/pip COMPONENT doc EXCLUDE_FROM_ALL OPTIONAL)
endif() endif()
endif() endif()
list(REMOVE_ITEM LIBS_STATUS ${PIP_MODULES})
message("----------PIP----------")
message(" Version: ${PIP_VERSION} ")
message(" Linkage: ${PIP_LIB_TYPE_MSG}")
message(" Type : ${PIP_BUILD_TYPE}")
if(LIB)
message(" Install: \"${CMAKE_INSTALL_PREFIX}\"")
else()
if(NOT PIP_FREERTOS)
message(" Install: local \"bin\", \"lib\" and \"include\"")
endif()
endif()
message("")
message(" Options:")
message(" std::iostream: ${PIP_STD_IOSTREAM}")
message(" ICU strings : ${PIP_ICU}")
message(" Timer types : ${PIP_TIMERS}")
message(" Introspection: ${PIP_INTROSPECTION}")
if(INTROSPECTION)
message(STATUS " Warning: Introspection reduces the performance!")
endif()
message("")
message(" Modules:")
foreach(_m ${PIP_SRC_MODULES})
message(" ${_m}: ${PIP_MSG_${_m}}")
endforeach()
message("")
if (PIP_TESTS_LIST)
message(" Tests:")
foreach(_test ${PIP_TESTS_LIST})
message(" * ${_test}")
endforeach()
else()
message(" Tests: skip (tests off)")
endif()
message("")
message(" Utilites:")
foreach(_util ${PIP_UTILS_LIST})
message(" * ${_util}")
endforeach()
if(NOT PIP_FREERTOS)
message("")
message(" Using libraries:")
foreach(LIB_ ${LIBS_STATUS})
if (NOT TARGET ${LIB_})
if(${LIB_}_FOUND)
message(" ${LIB_} -> ${${LIB_}_LIBRARIES}")
else()
message(" ${LIB_} not found, may fail")
endif()
endif()
endforeach()
endif()
message("-----------------------")

View File

@@ -5,10 +5,10 @@ Also create imported targets:
* PIP::USB * PIP::USB
* PIP::Console * PIP::Console
* PIP::Crypt * PIP::Crypt
* PIP::FFTW
* PIP::Compress * PIP::Compress
* PIP::FFTW
* PIP::OpenCL
* PIP::IOUtils * PIP::IOUtils
* PIP::Concurrent
* PIP::Cloud * PIP::Cloud
* PIP::Lua * PIP::Lua
@@ -64,8 +64,8 @@ find_library(PIP_CONSOLE_LIBRARY pip_console${_pip_suffix} HINTS ${_PIP_LIBDIR})
find_library(PIP_CRYPT_LIBRARY pip_crypt${_pip_suffix} HINTS ${_PIP_LIBDIR}) find_library(PIP_CRYPT_LIBRARY pip_crypt${_pip_suffix} HINTS ${_PIP_LIBDIR})
find_library(PIP_FFTW_LIBRARY pip_fftw${_pip_suffix} HINTS ${_PIP_LIBDIR}) find_library(PIP_FFTW_LIBRARY pip_fftw${_pip_suffix} HINTS ${_PIP_LIBDIR})
find_library(PIP_COMPRESS_LIBRARY pip_compress${_pip_suffix} HINTS ${_PIP_LIBDIR}) find_library(PIP_COMPRESS_LIBRARY pip_compress${_pip_suffix} HINTS ${_PIP_LIBDIR})
find_library(PIP_OPENCL_LIBRARY pip_opencl${_pip_suffix} HINTS ${_PIP_LIBDIR})
find_library(PIP_IO_UTILS_LIBRARY pip_io_utils${_pip_suffix} HINTS ${_PIP_LIBDIR}) find_library(PIP_IO_UTILS_LIBRARY pip_io_utils${_pip_suffix} HINTS ${_PIP_LIBDIR})
find_library(PIP_CONCURRENT_LIBRARY pip_concurrent${_pip_suffix} HINTS ${_PIP_LIBDIR})
find_library(PIP_CLOUD_LIBRARY pip_cloud HINTS${_pip_suffix} ${_PIP_LIBDIR}) find_library(PIP_CLOUD_LIBRARY pip_cloud HINTS${_pip_suffix} ${_PIP_LIBDIR})
find_library(PIP_LUA_LIBRARY pip_lua HINTS${_pip_suffix} ${_PIP_LIBDIR}) find_library(PIP_LUA_LIBRARY pip_lua HINTS${_pip_suffix} ${_PIP_LIBDIR})
find_file(PIP_H_INCLUDE "pip.h" HINTS ${_PIP_INCDIR} $ENV{SMSDK_DIR}/include/pip) find_file(PIP_H_INCLUDE "pip.h" HINTS ${_PIP_INCDIR} $ENV{SMSDK_DIR}/include/pip)
@@ -132,14 +132,14 @@ if(PIP_FIND_VERSION VERSION_GREATER PIP_VERSION)
message(FATAL_ERROR "PIP version ${PIP_VERSION} is available, but ${PIP_FIND_VERSION} requested!") message(FATAL_ERROR "PIP version ${PIP_VERSION} is available, but ${PIP_FIND_VERSION} requested!")
endif() endif()
set(__modules "USB;Crypt;Console;FFTW;Compress;IOUtils;Concurrent;Cloud;Lua") set(__modules "USB;Crypt;Console;FFTW;Compress;IOUtils;Cloud;Lua")
set(__module_USB "${PIP_USB_LIBRARY}" ) set(__module_USB "${PIP_USB_LIBRARY}" )
set(__module_Console "${PIP_CONSOLE_LIBRARY}" ) set(__module_Console "${PIP_CONSOLE_LIBRARY}" )
set(__module_Crypt "${PIP_CRYPT_LIBRARY}" ) set(__module_Crypt "${PIP_CRYPT_LIBRARY}" )
set(__module_FFTW "${PIP_FFTW_LIBRARY}" ) set(__module_FFTW "${PIP_FFTW_LIBRARY}" )
set(__module_Compress "${PIP_COMPRESS_LIBRARY}" ) set(__module_Compress "${PIP_COMPRESS_LIBRARY}" )
set(__module_OpenCL "${PIP_OPENCL_LIBRARY}" )
set(__module_IOUtils "${PIP_IO_UTILS_LIBRARY}" ) set(__module_IOUtils "${PIP_IO_UTILS_LIBRARY}" )
set(__module_Concurrent "${PIP_CONCURRENT_LIBRARY}")
set(__module_Cloud "${PIP_CLOUD_LIBRARY}" ) set(__module_Cloud "${PIP_CLOUD_LIBRARY}" )
set(__module_Lua "${PIP_LUA_LIBRARY}" ) set(__module_Lua "${PIP_LUA_LIBRARY}" )
if((NOT TARGET PIP) AND PIP_LIBRARY) if((NOT TARGET PIP) AND PIP_LIBRARY)

View File

@@ -1,27 +1,6 @@
macro(CONFIGURE_DOXYGEN_FILE DOXYGEN_CONFIG_FILE FILE_NAME_SUFFIX)
if(EXISTS ${PROJECT_SOURCE_DIR}/${DOXYGEN_CONFIG_FILE})
file(REMOVE "${CMAKE_CURRENT_BINARY_DIR}/doxyfile-${FILE_NAME_SUFFIX}")
file(READ ${PROJECT_SOURCE_DIR}/${DOXYGEN_CONFIG_FILE} DOXYFILE_CONTENTS)
string(REPLACE "\\\n" " " DOXYFILE_CONTENTS "${DOXYFILE_CONTENTS}")
string(REPLACE "\n" ";" DOXYFILE_LINES "${DOXYFILE_CONTENTS}")
foreach(LINE IN LISTS DOXYFILE_LINES)
if(LINE STRGREATER "")
string(REGEX MATCH "^[a-zA-Z]([^ ])+" DOXY_PARAM ${LINE})
if(DEFINED DOXY_${DOXY_PARAM})
STRING(REGEX REPLACE "=([^\n])+" "= ${DOXY_${DOXY_PARAM}}" LINE ${LINE})
endif(DEFINED DOXY_${DOXY_PARAM})
endif()
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/doxyfile-${FILE_NAME_SUFFIX} "${LINE}\n")
endforeach()
else()
MESSAGE(SEND_ERROR "Doxygen configuration file '${DOXYGEN_CONFIG_FILE}' not found, can`t generate documentation")
endif()
endmacro(CONFIGURE_DOXYGEN_FILE)
macro(ADD_DOCUMENTATION TARGET DOXYGEN_CONFIG_FILE) macro(ADD_DOCUMENTATION TARGET DOXYGEN_CONFIG_FILE)
if(DOXYGEN_FOUND) if(DOXYGEN_FOUND)
configure_doxygen_file(${DOXYGEN_CONFIG_FILE} ${TARGET}) configure_file("${PROJECT_SOURCE_DIR}/${DOXYGEN_CONFIG_FILE}" "${CMAKE_CURRENT_BINARY_DIR}/doxyfile-${TARGET}")
add_custom_target("genereate.${TARGET}" COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxyfile-${TARGET}) add_custom_target("genereate.${TARGET}" COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxyfile-${TARGET})
add_custom_target("${TARGET}" COMMAND ${CMAKE_COMMAND} -D COMPONENT=doc -P cmake_install.cmake) add_custom_target("${TARGET}" COMMAND ${CMAKE_COMMAND} -D COMPONENT=doc -P cmake_install.cmake)
add_dependencies("${TARGET}" "genereate.${TARGET}") add_dependencies("${TARGET}" "genereate.${TARGET}")

View File

@@ -38,7 +38,7 @@ PROJECT_NAME = PIP
# could be handy for archiving the generated documentation or if some version # could be handy for archiving the generated documentation or if some version
# control system is used. # control system is used.
PROJECT_NUMBER = 1.8.0 PROJECT_NUMBER = ${DOXY_PROJECT_NUMBER}
# Using the PROJECT_BRIEF tag one can provide an optional one line description # Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a # for a project that appears at the top of each page and should give viewer a
@@ -816,13 +816,7 @@ WARN_LOGFILE =
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
# Note: If this tag is empty the current directory is searched. # Note: If this tag is empty the current directory is searched.
INPUT = src_main \ INPUT = ${DOXY_INPUT}
src_crypt \
src_fftw \
src_io_utils \
src_compress \
src_opencl \
src_usb
# This tag can be used to specify the character encoding of the source files # This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
@@ -895,7 +889,7 @@ RECURSIVE = YES
# Note that relative paths are relative to the directory from which doxygen is # Note that relative paths are relative to the directory from which doxygen is
# run. # run.
EXCLUDE = EXCLUDE = ${DOXY_EXCLUDE}
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded # directories that are symbolic links (a Unix file system feature) are excluded
@@ -928,7 +922,7 @@ EXCLUDE_SYMBOLS =
# that contain example code fragments that are included (see the \include # that contain example code fragments that are included (see the \include
# command). # command).
EXAMPLE_PATH = doc/examples EXAMPLE_PATH = ${DOXY_EXAMPLE_PATH}
# If the value of the EXAMPLE_PATH tag contains directories, you can use the # If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
@@ -948,7 +942,7 @@ EXAMPLE_RECURSIVE = NO
# that contain images that are to be included in the documentation (see the # that contain images that are to be included in the documentation (see the
# \image command). # \image command).
IMAGE_PATH = doc/images IMAGE_PATH = ${DOXY_IMAGE_PATH}
# The INPUT_FILTER tag can be used to specify a program that doxygen should # The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program # invoke to filter for each input file. Doxygen will invoke the filter program
@@ -1459,14 +1453,14 @@ QHP_CUST_FILTER_NAME = PIP
# filters). # filters).
# This tag requires that the tag GENERATE_QHP is set to YES. # This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_ATTRS = PIP QHP_CUST_FILTER_ATTRS = ${DOXY_QHP_CUST_FILTER_ATTRS}
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see: # project's filter section matches. Qt Help Project / Filter Attributes (see:
# http://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). # http://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES. # This tag requires that the tag GENERATE_QHP is set to YES.
QHP_SECT_FILTER_ATTRS = PIP QHP_SECT_FILTER_ATTRS = ${DOXY_QHP_SECT_FILTER_ATTRS}
# The QHG_LOCATION tag can be used to specify the location of Qt's # The QHG_LOCATION tag can be used to specify the location of Qt's
# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the # qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
@@ -2152,15 +2146,7 @@ SEARCH_INCLUDES = YES
# preprocessor. # preprocessor.
# This tag requires that the tag SEARCH_INCLUDES is set to YES. # This tag requires that the tag SEARCH_INCLUDES is set to YES.
INCLUDE_PATH = src_main/code \ INCLUDE_PATH = ${DOXY_INCLUDE_PATH}
src_main/containers \
src_main/core \
src_main/math \
src_main/system \
src_main/thread \
src_main/console \
src_main/io_devices \
src_main/io_utils
# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
# patterns (like *.h and *.hpp) to filter out the header-files in the # patterns (like *.h and *.hpp) to filter out the header-files in the
@@ -2178,8 +2164,8 @@ INCLUDE_FILE_PATTERNS =
# recursively expanded use the := operator instead of the = operator. # recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
PREDEFINED = DOXYGEN \ PREDEFINED = ${DOXY_DEFINES}
PIP_EXPORT
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # 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 # tag can be used to specify a list of macro names that should be expanded. The
@@ -2272,14 +2258,14 @@ CLASS_DIAGRAMS = YES
# the mscgen tool resides. If left empty the tool is assumed to be found in the # the mscgen tool resides. If left empty the tool is assumed to be found in the
# default search path. # default search path.
MSCGEN_PATH = "C:/Program Files/doxygen/graphviz/bin" MSCGEN_PATH = ${DOXY_MSCGEN_PATH}
# You can include diagrams made with dia in doxygen documentation. Doxygen will # You can include diagrams made with dia in doxygen documentation. Doxygen will
# then run dia to produce the diagram and insert it in the documentation. The # then run dia to produce the diagram and insert it in the documentation. The
# DIA_PATH tag allows you to specify the directory where the dia binary resides. # DIA_PATH tag allows you to specify the directory where the dia binary resides.
# If left empty dia is assumed to be found in the default search path. # If left empty dia is assumed to be found in the default search path.
DIA_PATH = "C:/Program Files/doxygen/graphviz/bin" DIA_PATH = ${DOXY_DIA_PATH}
# If set to YES the inheritance and collaboration graphs will hide inheritance # If set to YES the inheritance and collaboration graphs will hide inheritance
# and usage relations if the target is undocumented or is not a class. # and usage relations if the target is undocumented or is not a class.
@@ -2472,7 +2458,7 @@ INTERACTIVE_SVG = NO
# found. If left blank, it is assumed the dot tool can be found in the path. # found. If left blank, it is assumed the dot tool can be found in the path.
# This tag requires that the tag HAVE_DOT is set to YES. # This tag requires that the tag HAVE_DOT is set to YES.
DOT_PATH = "C:/Program Files/doxygen/graphviz/bin" DOT_PATH = ${DOXY_DOT_PATH}
# The DOTFILE_DIRS tag can be used to specify one or more directories that # The DOTFILE_DIRS tag can be used to specify one or more directories that
# contain dot files that are included in the documentation (see the \dotfile # contain dot files that are included in the documentation (see the \dotfile

View File

@@ -23,3 +23,18 @@
PICloudClient::PICloudClient() { PICloudClient::PICloudClient() {
} }
PICloudClient::~PICloudClient() {
}
bool PICloudClient::openDevice() {
}
bool PICloudClient::closeDevice() {
}

View File

@@ -1,74 +0,0 @@
/*
PIP - Platform Independent Primitives
Stephan Fomenko
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "executor.h"
PIThreadPoolExecutor::PIThreadPoolExecutor(size_t corePoolSize, PIBlockingDequeue<std::function<void()>> *taskQueue_) : isShutdown_(false), taskQueue(taskQueue_) {
for (size_t i = 0; i < corePoolSize; ++i) {
PIThread * thread = new PIThread([&, i](){
auto runnable = taskQueue->poll(100, std::function<void()>());
if (runnable) {
runnable();
}
if (isShutdown_ && taskQueue->size() == 0) threadPool[i]->stop();
});
threadPool.push_back(thread);
thread->start();
}
}
bool PIThreadPoolExecutor::awaitTermination(int timeoutMs) {
PITimeMeasurer measurer;
for (size_t i = 0; i < threadPool.size(); ++i) {
int dif = timeoutMs - (int)measurer.elapsed_m();
if (dif < 0) return false;
if (!threadPool[i]->waitForFinish(dif)) return false;
}
return true;
}
void PIThreadPoolExecutor::shutdownNow() {
isShutdown_ = true;
for (size_t i = 0; i < threadPool.size(); ++i) threadPool[i]->stop();
}
PIThreadPoolExecutor::~PIThreadPoolExecutor() {
shutdownNow();
while (threadPool.size() > 0) delete threadPool.take_back();
delete taskQueue;
}
void PIThreadPoolExecutor::execute(const std::function<void()> &runnable) {
if (!isShutdown_) taskQueue->offer(runnable);
}
bool PIThreadPoolExecutor::isShutdown() const {
return isShutdown_;
}
void PIThreadPoolExecutor::shutdown() {
isShutdown_ = true;
}

View File

@@ -1,95 +0,0 @@
/*
PIP - Platform Independent Primitives
Stephan Fomenko
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "piconditionlock.h"
#ifdef WINDOWS
# include <synchapi.h>
#else
# include <pthread.h>
#endif
PRIVATE_DEFINITION_START(PIConditionLock)
#ifdef WINDOWS
CRITICAL_SECTION
#else
pthread_mutex_t
#endif
nativeHandle;
PRIVATE_DEFINITION_END(PIConditionLock)
PIConditionLock::PIConditionLock() {
#ifdef WINDOWS
InitializeCriticalSection(&PRIVATE->nativeHandle);
#else
pthread_mutexattr_t attr;
memset(&attr, 0, sizeof(attr));
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
memset(&(PRIVATE->nativeHandle), 0, sizeof(PRIVATE->nativeHandle));
pthread_mutex_init(&(PRIVATE->nativeHandle), &attr);
pthread_mutexattr_destroy(&attr);
#endif
}
PIConditionLock::~PIConditionLock() {
#ifdef WINDOWS
DeleteCriticalSection(&PRIVATE->nativeHandle);
#else
pthread_mutex_destroy(&(PRIVATE->nativeHandle));
#endif
}
void PIConditionLock::lock() {
#ifdef WINDOWS
EnterCriticalSection(&PRIVATE->nativeHandle);
#else
pthread_mutex_lock(&(PRIVATE->nativeHandle));
#endif
}
void PIConditionLock::unlock() {
#ifdef WINDOWS
LeaveCriticalSection(&PRIVATE->nativeHandle);
#else
pthread_mutex_unlock(&(PRIVATE->nativeHandle));
#endif
}
void *PIConditionLock::handle() {
#ifdef WINDOWS
return &PRIVATE->nativeHandle;
#else
return &PRIVATE->nativeHandle;
#endif
}
bool PIConditionLock::tryLock() {
#ifdef WINDOWS
return TryEnterCriticalSection(&PRIVATE->nativeHandle) != 0;
#else
return (pthread_mutex_trylock(&(PRIVATE->nativeHandle)) == 0);
#endif
}

View File

@@ -1,264 +0,0 @@
#include "gtest/gtest.h"
#include "piblockingdequeue.h"
class MockConditionVar: public PIConditionVariable {
public:
bool isWaitCalled = false;
bool isWaitForCalled = false;
bool isTrueCondition = false;
int timeout = -1;
void wait(PIConditionLock& lk) override {
isWaitCalled = true;
}
void wait(PIConditionLock& lk, const std::function<bool()>& condition) override {
isWaitCalled = true;
lk.lock();
isTrueCondition = condition();
lk.unlock();
}
bool waitFor(PIConditionLock& lk, int timeoutMs) override {
isWaitForCalled = true;
timeout = timeoutMs;
return false;
}
bool waitFor(PIConditionLock& lk, int timeoutMs, const std::function<bool()>& condition) override {
isWaitForCalled = true;
lk.lock();
isTrueCondition = condition();
timeout = timeoutMs;
lk.unlock();
return isTrueCondition;
}
};
TEST(BlockingDequeueUnitTest, put_is_block_when_capacity_reach) {
size_t capacity = 0;
auto conditionVarAdd = new MockConditionVar();
auto conditionVarRem = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVarAdd, conditionVarRem);
dequeue.put(11);
ASSERT_TRUE(conditionVarRem->isWaitCalled);
ASSERT_FALSE(conditionVarRem->isTrueCondition);
}
TEST(BlockingDequeueUnitTest, offer_timedout_is_false_when_capacity_reach) {
size_t capacity = 0;
int timeout = 11;
auto conditionVarAdd = new MockConditionVar();
auto conditionVarRem = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVarAdd, conditionVarRem);
ASSERT_FALSE(dequeue.offer(11, timeout));
}
TEST(BlockingDequeueUnitTest, offer_timedout_is_block_when_capacity_reach) {
size_t capacity = 0;
int timeout = 11;
auto conditionVarAdd = new MockConditionVar();
auto conditionVarRem = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVarAdd, conditionVarRem);
dequeue.offer(11, timeout);
EXPECT_TRUE(conditionVarRem->isWaitForCalled);
EXPECT_EQ(timeout, conditionVarRem->timeout);
ASSERT_FALSE(conditionVarRem->isTrueCondition);
}
TEST(BlockingDequeueUnitTest, offer_is_true_before_capacity_reach) {
size_t capacity = 1;
PIBlockingDequeue<int> dequeue(capacity);
ASSERT_TRUE(dequeue.offer(10));
}
TEST(BlockingDequeueUnitTest, offer_is_false_when_capacity_reach) {
size_t capacity = 1;
PIBlockingDequeue<int> dequeue(capacity);
dequeue.offer(11);
ASSERT_FALSE(dequeue.offer(10));
}
// TODO change take_is_block_when_empty to prevent segfault
TEST(DISABLED_BlockingDequeueUnitTest, take_is_block_when_empty) {
size_t capacity = 1;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
// May cause segfault because take front of empty queue
dequeue.take();
EXPECT_TRUE(conditionVar->isWaitCalled);
ASSERT_FALSE(conditionVar->isTrueCondition);
}
TEST(BlockingDequeueUnitTest, take_is_not_block_when_not_empty) {
size_t capacity = 1;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
dequeue.offer(111);
dequeue.take();
EXPECT_TRUE(conditionVar->isWaitCalled);
ASSERT_TRUE(conditionVar->isTrueCondition);
}
TEST(BlockingDequeueUnitTest, take_is_value_eq_to_offer_value) {
size_t capacity = 1;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
dequeue.offer(111);
ASSERT_EQ(dequeue.take(), 111);
}
TEST(BlockingDequeueUnitTest, take_is_last) {
size_t capacity = 10;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
EXPECT_TRUE(dequeue.offer(111));
EXPECT_TRUE(dequeue.offer(222));
ASSERT_EQ(dequeue.take(), 111);
ASSERT_EQ(dequeue.take(), 222);
}
TEST(BlockingDequeueUnitTest, poll_is_not_block_when_empty) {
size_t capacity = 1;
bool isOk;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
dequeue.poll(111, &isOk);
EXPECT_FALSE(conditionVar->isWaitForCalled);
}
TEST(BlockingDequeueUnitTest, poll_is_default_value_when_empty) {
size_t capacity = 1;
bool isOk;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
ASSERT_EQ(dequeue.poll(111, &isOk), 111);
}
TEST(BlockingDequeueUnitTest, poll_is_offer_value_when_not_empty) {
size_t capacity = 1;
bool isOk;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
dequeue.offer(111);
ASSERT_EQ(dequeue.poll(-1, &isOk), 111);
}
TEST(BlockingDequeueUnitTest, poll_timeouted_is_block_when_empty) {
size_t capacity = 1;
int timeout = 11;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
dequeue.poll(timeout, 111);
EXPECT_TRUE(conditionVar->isWaitForCalled);
EXPECT_EQ(timeout, conditionVar->timeout);
ASSERT_FALSE(conditionVar->isTrueCondition);
}
TEST(BlockingDequeueUnitTest, poll_timeouted_is_default_value_when_empty) {
size_t capacity = 1;
int timeout = 11;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
ASSERT_EQ(dequeue.poll(timeout, 111), 111);
}
TEST(BlockingDequeueUnitTest, poll_timeouted_is_not_block_when_not_empty) {
size_t capacity = 1;
int timeout = 11;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
dequeue.offer(111);
dequeue.poll(timeout, -1);
EXPECT_TRUE(conditionVar->isWaitForCalled);
ASSERT_TRUE(conditionVar->isTrueCondition);
}
TEST(BlockingDequeueUnitTest, poll_timeouted_is_offer_value_when_not_empty) {
size_t capacity = 1;
int timeout = 11;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
dequeue.offer(111);
ASSERT_EQ(dequeue.poll(timeout, -1), 111);
}
TEST(BlockingDequeueUnitTest, poll_timeouted_is_last) {
size_t capacity = 10;
auto conditionVar = new MockConditionVar();
PIBlockingDequeue<int> dequeue(capacity, conditionVar);
dequeue.offer(111);
dequeue.offer(222);
ASSERT_EQ(dequeue.poll(10, -1), 111);
ASSERT_EQ(dequeue.poll(10, -1), 222);
}
TEST(BlockingDequeueUnitTest, capacity_is_eq_constructor_capacity) {
size_t capacity = 10;
PIBlockingDequeue<int> dequeue(capacity);
ASSERT_EQ(dequeue.capacity(), capacity);
}
TEST(BlockingDequeueUnitTest, remainingCapacity_is_dif_of_capacity_and_size) {
size_t capacity = 2;
PIBlockingDequeue<int> dequeue(capacity);
ASSERT_EQ(dequeue.remainingCapacity(), capacity);
dequeue.offer(111);
ASSERT_EQ(dequeue.remainingCapacity(), capacity - 1);
}
TEST(BlockingDequeueUnitTest, remainingCapacity_is_zero_when_capacity_reach) {
size_t capacity = 1;
PIBlockingDequeue<int> dequeue(capacity);
dequeue.offer(111);
dequeue.offer(111);
ASSERT_EQ(dequeue.remainingCapacity(), 0);
}
TEST(BlockingDequeueUnitTest, size_is_eq_to_num_of_elements) {
size_t capacity = 1;
PIBlockingDequeue<int> dequeue(capacity);
ASSERT_EQ(dequeue.size(), 0);
dequeue.offer(111);
ASSERT_EQ(dequeue.size(), 1);
}
TEST(BlockingDequeueUnitTest, size_is_eq_to_capacity_when_capacity_reach) {
size_t capacity = 1;
PIBlockingDequeue<int> dequeue(capacity);
dequeue.offer(111);
dequeue.offer(111);
ASSERT_EQ(dequeue.size(), capacity);
}
TEST(BlockingDequeueUnitTest, drainTo_is_elements_moved) {
size_t capacity = 10;
PIDeque<int> refDeque;
for (size_t i = 0; i < capacity / 2; ++i) refDeque.push_back(i * 10);
PIBlockingDequeue<int> blockingDequeue(refDeque);
PIDeque<int> deque;
blockingDequeue.drainTo(deque);
ASSERT_EQ(blockingDequeue.size(), 0);
ASSERT_TRUE(deque == refDeque);
}
TEST(BlockingDequeueUnitTest, drainTo_is_ret_eq_to_size_when_all_moved) {
size_t capacity = 10;
PIDeque<int> refDeque;
for (size_t i = 0; i < capacity / 2; ++i) refDeque.push_back(i * 10);
PIBlockingDequeue<int> blockingDequeue(refDeque);
PIDeque<int> deque;
ASSERT_EQ(blockingDequeue.drainTo(deque), refDeque.size());
}
TEST(BlockingDequeueUnitTest, drainTo_is_ret_eq_to_maxCount) {
size_t capacity = 10;
PIDeque<int> refDeque;
for (size_t i = 0; i < capacity / 2; ++i) refDeque.push_back(i * 10);
PIBlockingDequeue<int> blockingDequeue(refDeque);
PIDeque<int> deque;
ASSERT_EQ(blockingDequeue.drainTo(deque, refDeque.size() - 1), refDeque.size() - 1);
}

View File

@@ -1,1168 +0,0 @@
/*
PIP - Platform Independent Primitives
Console output/input
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "piconsole.h"
#include "piincludes_p.h"
#include "pipeer.h"
#include "pidiagnostics.h"
#include "pisystemmonitor.h"
#ifndef WINDOWS
# include <sys/ioctl.h>
# include <fcntl.h>
# include <termios.h>
#else
# include <wincon.h>
# define COMMON_LVB_UNDERSCORE 0x8000
#endif
/** \class PIConsole
* \brief Console output class
* \details
* \section PIConsole_sec0 Synopsis
* This class provides output to console with automatic alignment and update.
* It supports tabs, keyboard listening, formats and colors.
*
* \section PIConsole_sec1 Layout
* %PIConsole works with variable pointers. You should add your variables with
* functions \a addVariable() which receives label name, pointer to variable
* and optional column and format. Columns count is dynamically increased if
* new column used. E.g. if you add variable to empty tab to column 3, columns
* count will be increased to 3, but two firsts columns will be empty. Each column
* filled from top to bottom, but you can add just string with function
* \a addString() or add empty line with function \a addEmptyLine(). Layout scheme:
* \image html piconsole_layout.png
*
* \section PIConsole_sec2 Keyboard usage
* %PIConsole should to be single in application. %PIConsole aggregate PIKbdListener
* which grab keyboard and automatic switch tabs by theirs bind keys. If there is no
* tab binded to pressed key external function "slot" will be called
*
**/
PRIVATE_DEFINITION_START(PIConsole)
#ifdef WINDOWS
void getWinCurCoord() {GetConsoleScreenBufferInfo(hOut, &csbi); ccoord = csbi.dwCursorPosition;}
COORD & getWinCoord(int dx = 0, int dy = 0) {getWinCurCoord(); ccoord.X += dx; ccoord.Y += dy; return ccoord;}
void * hOut;
CONSOLE_SCREEN_BUFFER_INFO sbi, csbi;
CONSOLE_CURSOR_INFO curinfo;
COORD ccoord, ulcoord;
WORD dattr;
DWORD smode, written;
#endif
PRIVATE_DEFINITION_END(PIConsole)
PIConsole::PIConsole(bool startNow, PIKbdListener::KBFunc slot): PIThread() {
setName("console");
setPriority(piLow);
needLockRun(true);
ret_func = slot;
num_format = systime_format = 0;
vid = 0;
cur_tab = width = height = pwidth = pheight = max_y = 0;
def_align = Nothing;
tabs.reserve(16);
#ifdef WINDOWS
PRIVATE->ulcoord.X = 0;
PRIVATE->hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(PRIVATE->hOut, &PRIVATE->sbi);
PRIVATE->dattr = PRIVATE->sbi.wAttributes;
width = PRIVATE->sbi.srWindow.Right - PRIVATE->sbi.srWindow.Left;
height = PRIVATE->sbi.srWindow.Bottom - PRIVATE->sbi.srWindow.Top;
PRIVATE->ulcoord.Y = PRIVATE->sbi.srWindow.Top;
GetConsoleMode(PRIVATE->hOut, &PRIVATE->smode);
GetConsoleCursorInfo(PRIVATE->hOut, &PRIVATE->curinfo);
#else
# ifdef FREERTOS
width = 80;
height = 24;
# else
winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
width = ws.ws_col;
height = ws.ws_row;
# endif
#endif
addTab("main");
listener = new PIKbdListener(key_event, this);
peer_timer = new PITimer();
peer_timer->setName("__S__.PIConsole.peer_timer");
peer = 0;
server_mode = pause_ = false;
state = Disconnected;
peer_timer->addDelimiter(20);
peer_timer->setName("__S__PIConsole::peer_timer");
CONNECT2(void, void * , int, peer_timer, tickEvent, this, peerTimer);
if (startNow) start();
}
PIConsole::~PIConsole() {
stopPeer();
if (isRunning())
stop();
clearTabs(false);
delete listener;
delete peer_timer;
#ifdef WINDOWS
SetConsoleMode(PRIVATE->hOut, PRIVATE->smode);
SetConsoleTextAttribute(PRIVATE->hOut, PRIVATE->dattr);
#endif
}
int PIConsole::addTab(const PIString & name, char bind_key) {
if (isRunning()) lock();
tabs.push_back(Tab(name, bind_key));
cur_tab = tabs.size() - 1;
if (isRunning()) unlock();
return tabs.size();
}
void PIConsole::removeTab(uint index) {
if (index >= tabs.size()) return;
if (isRunning()) lock();
tabs.remove(index);
if (cur_tab >= tabs.size()) cur_tab = tabs.size() - 1;
if (isRunning()) unlock();
}
void PIConsole::removeTab(const PIString & name) {
uint index = tabs.size() + 1;
for (uint i = 0; i < tabs.size(); ++i) {
if (tabs[i].name == name) {
index = i;
break;
}
}
removeTab(index);
}
void PIConsole::clearTab(uint index) {
if (index >= tabs.size()) return;
lock();
tabs[index].columns.clear();
if (cur_tab == index) {
clearScreen();
fillLabels();
}
if (cur_tab >= tabs.size()) cur_tab = tabs.size() - 1;
unlock();
}
void PIConsole::clearTab(const PIString & name) {
uint index = tabs.size() + 1;
for (uint i = 0; i < tabs.size(); ++i) {
if (tabs[i].name == name) {
index = i;
break;
}
}
clearTab(index);
}
void PIConsole::update() {
lock();
fillLabels();
unlock();
}
bool PIConsole::setTab(uint index) {
if (index >= tabs.size())
return false;
if (!isRunning()) {
cur_tab = index;
return true;
}
lock();
PICout::__mutex__().lock();
cur_tab = index;
clearScreen();
fillLabels();
PICout::__mutex__().unlock();
unlock();
return true;
}
bool PIConsole::setTab(const PIString & name) {
uint index = tabs.size() + 1;
for (uint i = 0; i < tabs.size(); ++i) {
if (tabs[i].name == name) {
index = i;
break;
}
}
return setTab(index);
}
bool PIConsole::setTabBindKey(uint index, char bind_key) {
if (index >= tabs.size())
return false;
tabs[index].key = bind_key;
return true;
}
bool PIConsole::setTabBindKey(const PIString & name, char bind_key) {
uint index =tabs.size() + 1;
for (uint i = 0; i < tabs.size(); ++i) {
if (tabs[i].name == name) {
index = i;
break;
}
}
return setTabBindKey(index, bind_key);
}
void PIConsole::key_event(PIKbdListener::KeyEvent key, void * t) {
PIConsole * p = (PIConsole * )t;
int ct = p->cur_tab;
if (key.key == PIKbdListener::LeftArrow) {
do {
ct--;
if (ct < 0) return;
} while (p->tabs[ct].key == 0);
p->setTab(ct);
return;
}
if (key.key == PIKbdListener::RightArrow) {
do {
ct++;
if (ct >= p->tabs.size_s()) return;
} while (p->tabs[ct].key == 0);
p->setTab(ct);
return;
}
for (uint i = 0; i < p->tabsCount(); ++i) {
if (p->tabs[i].key == key.key) {
p->setTab(i);
return;
}
}
if (p->ret_func != 0) p->ret_func(key, t);
p->keyPressed(key, t);
}
int PIConsole::couts(const PIString & v) {
return printf("%s", v.data());
}
int PIConsole::couts(const char * v) {
return printf("%s", v);
}
void PIConsole::clearVariables(bool clearScreen) {
if (isRunning()) lock();
if (clearScreen && isRunning()) {
toUpperLeft();
clearScreenLower();
}
columns().clear();
if (isRunning()) unlock();
}
void PIConsole::stop(bool clear) {
PIThread::stop(true);
if (clear) clearScreen();
moveTo(0, max_y + 4);
showCursor();
couts(fstr(Normal));
#ifdef WINDOWS
SetConsoleMode(PRIVATE->hOut, PRIVATE->smode);
SetConsoleTextAttribute(PRIVATE->hOut, PRIVATE->dattr);
#endif
fflush(0);
}
PIString PIConsole::fstr(FormatFlags f) {
num_format = systime_format = 0;
if (f[PIConsole::Dec]) num_format = 0;
if (f[PIConsole::Hex]) num_format = 1;
if (f[PIConsole::Oct]) num_format = 2;
if (f[PIConsole::Bin]) num_format = 4;
if (f[PIConsole::Scientific]) num_format = 3;
if (f[PIConsole::SystemTimeSplit]) systime_format = 0;
if (f[PIConsole::SystemTimeSeconds]) systime_format = 1;
#ifdef WINDOWS
WORD attr = 0;
if (f[PIConsole::Inverse]) {
if (f[PIConsole::Red]) attr |= BACKGROUND_RED;
if (f[PIConsole::Green]) attr |= BACKGROUND_GREEN;
if (f[PIConsole::Blue]) attr |= BACKGROUND_BLUE;
if (f[PIConsole::Yellow]) attr |= (BACKGROUND_RED | BACKGROUND_GREEN);
if (f[PIConsole::Magenta]) attr |= (BACKGROUND_RED | BACKGROUND_BLUE);
if (f[PIConsole::Cyan]) attr |= (BACKGROUND_GREEN | BACKGROUND_BLUE);
if (f[PIConsole::White]) attr |= (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE);
if (f[PIConsole::BackRed]) attr |= FOREGROUND_RED;
if (f[PIConsole::BackGreen]) attr |= FOREGROUND_GREEN;
if (f[PIConsole::BackBlue]) attr |= FOREGROUND_BLUE;
if (f[PIConsole::BackYellow]) attr |= (FOREGROUND_RED | FOREGROUND_GREEN);
if (f[PIConsole::BackMagenta]) attr |= (FOREGROUND_RED | FOREGROUND_BLUE);
if (f[PIConsole::BackCyan]) attr |= (FOREGROUND_GREEN | FOREGROUND_BLUE);
if (f[PIConsole::BackWhite]) attr |= (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
if ((attr & BACKGROUND_RED) + (attr & BACKGROUND_GREEN) + (attr & BACKGROUND_BLUE) == 0)
attr |= FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
} else {
if (f[PIConsole::Red]) attr |= FOREGROUND_RED;
if (f[PIConsole::Green]) attr |= FOREGROUND_GREEN;
if (f[PIConsole::Blue]) attr |= FOREGROUND_BLUE;
if (f[PIConsole::Yellow]) attr |= (FOREGROUND_RED | FOREGROUND_GREEN);
if (f[PIConsole::Magenta]) attr |= (FOREGROUND_RED | FOREGROUND_BLUE);
if (f[PIConsole::Cyan]) attr |= (FOREGROUND_GREEN | FOREGROUND_BLUE);
if (f[PIConsole::White]) attr |= (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
if (f[PIConsole::BackRed]) attr |= BACKGROUND_RED;
if (f[PIConsole::BackGreen]) attr |= BACKGROUND_GREEN;
if (f[PIConsole::BackBlue]) attr |= BACKGROUND_BLUE;
if (f[PIConsole::BackYellow]) attr |= (BACKGROUND_RED | BACKGROUND_GREEN);
if (f[PIConsole::BackMagenta]) attr |= (BACKGROUND_RED | BACKGROUND_BLUE);
if (f[PIConsole::BackCyan]) attr |= (BACKGROUND_GREEN | BACKGROUND_BLUE);
if (f[PIConsole::BackWhite]) attr |= (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE);
if ((attr & FOREGROUND_RED) + (attr & FOREGROUND_GREEN) + (attr & FOREGROUND_BLUE) == 0)
attr |= FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
}
if (f[PIConsole::Bold]) attr |= FOREGROUND_INTENSITY;
if (f[PIConsole::Underline]) attr |= COMMON_LVB_UNDERSCORE;
SetConsoleTextAttribute(PRIVATE->hOut, attr);
return PIString();
#else
PIString ts("\e[0");
if (f[PIConsole::Bold]) ts += ";1";
if (f[PIConsole::Faint]) ts += ";2";
if (f[PIConsole::Italic]) ts += ";3";
if (f[PIConsole::Underline]) ts += ";4";
if (f[PIConsole::Blink]) ts += ";5";
if (f[PIConsole::Inverse]) ts += ";7";
if (f[PIConsole::Black]) ts += ";30";
if (f[PIConsole::Red]) ts += ";31";
if (f[PIConsole::Green]) ts += ";32";
if (f[PIConsole::Yellow]) ts += ";33";
if (f[PIConsole::Blue]) ts += ";34";
if (f[PIConsole::Magenta]) ts += ";35";
if (f[PIConsole::Cyan]) ts += ";36";
if (f[PIConsole::White]) ts += ";37";
if (f[PIConsole::BackBlack]) ts += ";40";
if (f[PIConsole::BackRed]) ts += ";41";
if (f[PIConsole::BackGreen]) ts += ";42";
if (f[PIConsole::BackYellow]) ts += ";43";
if (f[PIConsole::BackBlue]) ts += ";44";
if (f[PIConsole::BackMagenta]) ts += ";45";
if (f[PIConsole::BackCyan]) ts += ";46";
if (f[PIConsole::BackWhite]) ts += ";47";
return ts + "m";
#endif
}
inline int PIConsole::couts(const bool v) {return (v ? printf("true") : printf("false"));}
inline int PIConsole::couts(const char v) {return printf("%c", v);}
inline int PIConsole::couts(const short v) {
switch (num_format) {case (1): return printf("0x%.4hX", v); break; case (2): return printf("%o", v); break; case (4): return printf("%s", toBin(&v, 2)); break; default: return printf("%hd", v); break;}
}
inline int PIConsole::couts(const int v) {
switch (num_format) {case (1): return printf("0x%.8X", v); break; case (2): return printf("%o", v); break; case (4): return printf("%s", toBin(&v, 4)); break; default: return printf("%d", v); break;}
}
inline int PIConsole::couts(const long v) {
switch (num_format) {case (1): return printf("0x%.16lX", v); break; case (2): return printf("%lo", v); break; case (4): return printf("%s", toBin(&v, sizeof(v))); break; default: return printf("%ld", v); break;}
}
inline int PIConsole::couts(const llong v) {
switch (num_format) {case (1): return printf("0x%.16llX", v); break; case (2): return printf("%llo", v); break; case (4): return printf("%s", toBin(&v, sizeof(v))); break; default: return printf("%lld", v); break;}
}
inline int PIConsole::couts(const uchar v) {
switch (num_format) {case (1): return printf("0x%.2X", v); break; case (2): return printf("%o", v); break; case (4): return printf("%s", toBin(&v, 1)); break; default: return printf("%u", v); break;}
}
inline int PIConsole::couts(const ushort v) {
switch (num_format) {case (1): return printf("0x%.4hX", v); break; case (2): return printf("%o", v); break; case (4): return printf("%s", toBin(&v, 2)); break; default: return printf("%hu", v); break;}
}
inline int PIConsole::couts(const uint v) {
switch (num_format) {case (1): return printf("0x%.8X", v); break; case (2): return printf("%o", v); break; case (4): return printf("%s", toBin(&v, 4)); break; default: return printf("%u", v); break;}
}
inline int PIConsole::couts(const ulong v) {
switch (num_format) {case (1): return printf("0x%.16lX", v); break; case (2): return printf("%lo", v); break; case (4): return printf("%s", toBin(&v, sizeof(v))); break; default: return printf("%lu", v); break;}
}
inline int PIConsole::couts(const ullong v) {
switch (num_format) {case (1): return printf("0x%.16llX", v); break; case (2): return printf("%llo", v); break; case (4): return printf("%s", toBin(&v, sizeof(v))); break; default: return printf("%llu", v); break;}
}
inline int PIConsole::couts(const float v) {
switch (num_format) {case (3): return printf("%e", v); break; default: return printf("%.5g", v); break;}
}
inline int PIConsole::couts(const double v) {
switch (num_format) {case (3): return printf("%le", v); break; default: return printf("%.5lg", v); break;}
}
inline int PIConsole::couts(const PISystemTime & v) {
switch (systime_format) {case (1): return printf("%.6lg", v.toSeconds()); break;
default: return couts(v.seconds) + printf(" s, ") + couts(v.nanoseconds) + printf(" ns"); break;}
}
void PIConsole::toUpperLeft() {
#ifdef WINDOWS
SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->ulcoord);
#else
printf("\e[H");
#endif
}
void PIConsole::moveRight(int n) {
#ifdef WINDOWS
SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->getWinCoord(n));
#else
if (n > 0) printf("\e[%dC", n);
#endif
}
void PIConsole::moveLeft(int n) {
#ifdef WINDOWS
SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->getWinCoord(-n));
#else
if (n > 0) printf("\e[%dD", n);
#endif
}
void PIConsole::moveTo(int x, int y) {
#ifdef WINDOWS
PRIVATE->ccoord.X = x;
PRIVATE->ccoord.Y = PRIVATE->ulcoord.Y + y;
SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->ccoord);
#else
printf("\e[%d;%dH", y, x);
#endif
}
void PIConsole::clearScreen() {
#ifdef WINDOWS
couts(fstr(Normal));
toUpperLeft();
FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width * (height + 1), PRIVATE->ulcoord, &PRIVATE->written);
FillConsoleOutputCharacter(PRIVATE->hOut, ' ', width * (height + 1), PRIVATE->ulcoord, &PRIVATE->written);
#else
couts(fstr(Normal)); printf("\e[H\e[J");
#endif
}
void PIConsole::clearScreenLower() {
#ifdef WINDOWS
couts(fstr(Normal));
PRIVATE->getWinCurCoord();
FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width * height - width * PRIVATE->ccoord.Y + PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written);
FillConsoleOutputCharacter(PRIVATE->hOut, ' ', width * height - width * PRIVATE->ccoord.Y + PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written);
#else
couts(fstr(Normal)); printf("\e[J");
#endif
}
void PIConsole::clearLine() {
#ifdef WINDOWS
PRIVATE->getWinCurCoord();
FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width - PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written);
FillConsoleOutputCharacter(PRIVATE->hOut, ' ', width - PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written);
#else
printf("\e[K");
#endif
}
void PIConsole::newLine() {
#ifdef WINDOWS
PRIVATE->getWinCurCoord();
PRIVATE->ccoord.X = 0; PRIVATE->ccoord.Y++;
SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->ccoord);
#else
printf("\eE");
#endif
}
void PIConsole::hideCursor() {
#ifdef WINDOWS
PRIVATE->curinfo.bVisible = false;
SetConsoleCursorInfo(PRIVATE->hOut, &PRIVATE->curinfo);
#else
printf("\e[?25l");
#endif
}
void PIConsole::showCursor() {
#ifdef WINDOWS
PRIVATE->curinfo.bVisible = true; SetConsoleCursorInfo(PRIVATE->hOut, &PRIVATE->curinfo);
#else
printf("\e[?25h");
#endif
}
void PIConsole::begin() {
#ifdef WINDOWS
SetConsoleMode(PRIVATE->hOut, ENABLE_WRAP_AT_EOL_OUTPUT);
#endif
max_y = 0;
PICout::__mutex__().lock();
clearScreen();
hideCursor();
fillLabels();
PICout::__mutex__().unlock();
}
void PIConsole::run() {
if (pause_) return;
uint cx, clen = 0;
int j;
#ifdef WINDOWS
GetConsoleScreenBufferInfo(PRIVATE->hOut, &PRIVATE->sbi);
width = PRIVATE->sbi.srWindow.Right - PRIVATE->sbi.srWindow.Left;
height = PRIVATE->sbi.srWindow.Bottom - PRIVATE->sbi.srWindow.Top;
#else
# ifdef FREERTOS
width = 80;
height = 24;
# else
winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
width = ws.ws_col;
height = ws.ws_row;
# endif
#endif
//fflush(0); return;
PICout::__mutex__().lock();
if (pwidth != width || pheight != height) {
clearScreen();
fillLabels();
}
pwidth = width;
pheight = height;
col_cnt = columns().size();
col_wid = (col_cnt > 0) ? width / col_cnt : width;
for (uint i = 0; i < col_cnt; ++i) {
PIVector<Variable> & cvars(tabs[cur_tab].columns[i].variables);
cx = col_wid * i;
toUpperLeft();
if (max_y < cvars.size()) max_y = cvars.size();
j = 0;
piForeachC (Variable & tv_, cvars) {
if (j > height - 3) continue;
j++;
moveRight(cx);
if (tv_.type == 15) {
newLine();
continue;
}
moveRight(tv_.offset);
const void * ptr = 0;
if (tv_.remote) {
if (tv_.type == 0) {
rstr.clear();
rba = tv_.rdata;
rba >> rstr;
rstr.trim();
ptr = &rstr;
} else
ptr = tv_.rdata.data();
} else
ptr = tv_.ptr;
switch (tv_.type) {
case 0: clen = printValue(ptr != 0 ? *(const PIString*)ptr : PIString(), tv_.format); break;
case 1: clen = printValue(ptr != 0 ? *(const bool*)ptr : false, tv_.format); break;
case 2: clen = printValue(ptr != 0 ? *(const int*)ptr : 0, tv_.format); break;
case 3: clen = printValue(ptr != 0 ? *(const long*)ptr : 0l, tv_.format); break;
case 4: clen = printValue(ptr != 0 ? *(const char*)ptr : char(0), tv_.format); break;
case 5: clen = printValue(ptr != 0 ? *(const float*)ptr : 0.f, tv_.format); break;
case 6: clen = printValue(ptr != 0 ? *(const double*)ptr : 0., tv_.format); break;
case 7: clen = printValue(ptr != 0 ? *(const short*)ptr : short(0), tv_.format); break;
case 8: clen = printValue(ptr != 0 ? *(const uint*)ptr : 0u, tv_.format); break;
case 9: clen = printValue(ptr != 0 ? *(const ulong*)ptr : 0ul, tv_.format); break;
case 10: clen = printValue(ptr != 0 ? *(const ushort*)ptr : ushort(0), tv_.format); break;
case 11: clen = printValue(ptr != 0 ? *(const uchar*)ptr : uchar(0), tv_.format); break;
case 12: clen = printValue(ptr != 0 ? *(const llong*)ptr : 0l, tv_.format); break;
case 13: clen = printValue(ptr != 0 ? *(const ullong*)ptr: 0ull, tv_.format); break;
case 20: clen = printValue(ptr != 0 ? *(const PISystemTime*)ptr: PISystemTime(), tv_.format); break;
case 14: clen = printValue(bitsValue(ptr, tv_.bitFrom, tv_.bitCount), tv_.format); break;
}
if (clen + tv_.offset < (uint)col_wid) {
PIString ts = PIString(
#if defined(QNX) || defined(FREE_BSD)
col_wid - clen - tv_.offset - 1, ' ');
#else
col_wid - clen - tv_.offset, ' ');
#endif
printf("%s", ts.data());
}
newLine();
}
}
#ifdef WINDOWS
moveTo(0, max_y + 1);
#else
moveTo(0, max_y + 2);
#endif
fflush(0);
PICout::__mutex__().unlock();
}
void PIConsole::fillLabels() {
if (!isRunning()) return;
uint cx, cy, mx = 0, dx;
#ifdef WINDOWS
GetConsoleScreenBufferInfo(PRIVATE->hOut, &PRIVATE->sbi);
width = PRIVATE->sbi.srWindow.Right - PRIVATE->sbi.srWindow.Left;
height = PRIVATE->sbi.srWindow.Bottom - PRIVATE->sbi.srWindow.Top;
#else
# ifdef FREERTOS
width = 80;
height = 24;
# else
winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
width = ws.ws_col;
height = ws.ws_row;
# endif
#endif
max_y = 0;
col_cnt = columns().size();
col_wid = (col_cnt > 0) ? width / col_cnt : width;
for (uint i = 0; i < col_cnt; ++i) {
Column & ccol(tabs[cur_tab].columns[i]);
PIVector<Variable> & cvars(ccol.variables);
if (ccol.alignment != Nothing) {
mx = 0;
piForeachC (Variable & j, cvars)
if (!j.isEmpty())
if (mx < j.name.size())
mx = j.name.size();
mx += 2;
}
cx = col_wid * i;
cy = 1;
toUpperLeft();
for (uint j = 0; j < cvars.size(); ++j) {
if (int(j) > height - 3) continue;
if (max_y < j) max_y = j;
moveRight(cx);
Variable & tv_(cvars[j]);
cvars[j].nx = cx;
cvars[j].ny = cy;
if (tv_.name.isEmpty()) {
cvars[j].offset = 0;
clearLine();
newLine();
cy++;
continue;
}
clearLine();
//piCout << tv_.name << tv_.type << tv_.ptr;
if (tv_.type == 15) {
cvars[j].offset = cvars[j].name.length();
cvars[j].nx += cvars[j].offset;
printLine(tv_.name, cx, tv_.format);
newLine();
cy++;
continue;
}
if (!tv_.isEmpty()) {
switch (ccol.alignment) {
case Nothing:
cvars[j].offset = (tv_.name + ": ").length();
cvars[j].nx += cvars[j].offset;
printValue(tv_.name + ": ", tv_.format);
break;
case Left:
cvars[j].offset = mx;
cvars[j].nx += cvars[j].offset;
printValue(tv_.name + ": ", tv_.format);
break;
case Right:
cvars[j].offset = mx;
cvars[j].nx += cvars[j].offset;
dx = mx - (tv_.name + ": ").length();
moveRight(dx);
printValue(tv_.name + ": ", tv_.format);
moveLeft(dx);
break;
}
}
newLine();
cy++;
}
}
#ifdef WINDOWS
moveTo(0, max_y + 1);
#else
moveTo(0, max_y + 2);
#endif
if (!tabs[cur_tab].status.isEmpty()) {
printValue(tabs[cur_tab].status);
newLine();
}
status();
}
void PIConsole::status() {
Tab * ctab;
for (uint i = 0; i < tabsCount(); ++i) {
ctab = &tabs[i];
if (ctab->key == 0) continue;
printValue(ctab->key, PIConsole::White | PIConsole::Bold);
if (i == cur_tab)
printValue(ctab->name + " ", PIConsole::BackYellow | PIConsole::Black);
else
printValue(ctab->name + " ", PIConsole::Cyan | PIConsole::Inverse);
printValue(" ");
}
newLine();
}
int PIConsole::bitsValue(const void * src, int offset, int count) const {
int ret = 0, stbyte = offset / 8, cbit = offset - stbyte * 8;
char cbyte = reinterpret_cast<const char * >(src)[stbyte];
for (int i = 0; i < count; i++) {
ret |= ((cbyte >> cbit & 1) << i);
cbit++;
if (cbit == 8) {
cbit = 0;
stbyte++;
cbyte = reinterpret_cast<const char * >(src)[stbyte];
}
}
return ret;
}
const char * PIConsole::toBin(const void * d, int s) {
binstr.clear();
uchar cc, b;
for (int i = 0; i < s; ++i) {
cc = ((const uchar *)d)[i];
b = 1;
for (int j = 0; j < 8; ++j) {
binstr << (cc & b ? "1" : "0");
b <<= 1;
}
if (i < s - 1) binstr << " ";
}
binstr.reverse();
return binstr.data();
}
#define ADD_VAR_BODY vid++; tv.id = vid; tv.name = name; tv.bitFrom = tv.bitCount = 0; tv.format = format; tv.remote = false; checkColumn(col);
void PIConsole::addString(const PIString & name, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 15; tv.size = 0; tv.ptr = 0; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const PIString * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 0; tv.size = 0; tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const bool * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 1; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const int * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 2; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const long * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 3; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const char * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 4; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const float * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 5; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const double * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 6; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const short * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 7; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const uint * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 8; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const ulong * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 9; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const ushort * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 10; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const uchar * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 11; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const llong * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 12; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const ullong * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 13; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
void PIConsole::addVariable(const PIString & name, const PISystemTime * ptr, int col, FormatFlags format) {
ADD_VAR_BODY tv.type = 20; tv.size = sizeof(*ptr); tv.ptr = ptr; column(col).push_back(tv);}
/** \brief Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
* \details This function add to column "column" next lines:
* * "<name> diagnostics"
* * "Received count": \a PIDiagnostics::receiveCount
* * "Invalid count": \a PIDiagnostics::wrongCount
* * "Sended count": \a PIDiagnostics::sendCount
* * "Immediate Frequency, Hz": \a PIDiagnostics::immediateFrequency
* * "Integral Frequency, Hz": \a PIDiagnostics::integralFrequency
* * "Receive speed": \a PIDiagnostics::receiveSpeed
* * "Send speed": \a PIDiagnostics::sendSpeed
* * "Quality": \a PIDiagnostics::quality
* */
void PIConsole::addVariable(const PIString & name, const PIDiagnostics * ptr, int col, FormatFlags format) {
addString(name + " diagnostics", col, format | PIConsole::Bold);
// addVariable("Received count", ptr->receiveCount_ptr(), col, format);
// addVariable("Invalid count", ptr->wrongCount_ptr(), col, format);
// addVariable("Sended count", ptr->sendCount_ptr(), col, format);
// addVariable("Immediate Frequency, Hz", ptr->immediateFrequency_ptr(), col, format);
// addVariable("Integral Frequency, Hz", ptr->integralFrequency_ptr(), col, format);
// addVariable("Receive speed", ptr->receiveSpeed_ptr(), col, format);
// addVariable("Send speed", ptr->sendSpeed_ptr(), col, format);
// addVariable("Quality", ptr->quality_ptr(), col, format);
}
void PIConsole::addVariable(const PIString & name, const PISystemMonitor * ptr, int col, FormatFlags format) {
addString("monitor " + name, col, format | PIConsole::Bold);
//addVariable("PID", &(ptr->statistic().ID), col, format);
//addVariable("state", &(ptr->statistic().state), col, format);
//addVariable("threads", &(ptr->statistic().threads), col, format);
//addVariable("priority", &(ptr->statistic().priority), col, format);
//addVariable("memory physical", &(ptr->statistic().physical_memsize_readable), col, format);
//addVariable("memory shared", &(ptr->statistic().share_memsize_readable), col, format);
//addVariable("cpu load kernel", &(ptr->statistic().cpu_load_system), col, format);
//addVariable("cpu load user", &(ptr->statistic().cpu_load_user), col, format);
}
void PIConsole::addBitVariable(const PIString & name, const void * ptr, int fromBit, int bitCount, int col, FormatFlags format) {
vid++; tv.id = vid; tv.size = sizeof(ullong); tv.name = name; tv.bitFrom = fromBit; tv.bitCount = bitCount; tv.type = 14; tv.ptr = ptr; tv.format = format;
checkColumn(col); column(col).push_back(tv);}
void PIConsole::addEmptyLine(int col, uint count) {
tv.id = 0; tv.size = 0; tv.name = ""; tv.type = 0; tv.ptr = 0; tv.format = Normal;
for (uint i = 0; i < count; ++i) {
checkColumn(col);
column(col).push_back(tv);
}
}
PIString PIConsole::getString(int x, int y) {
bool run = isRunning();
if (run) PIThread::stop(true);
listener->setActive(false);
msleep(50);
#ifdef WINDOWS
moveTo(x - 1, y - 1);
#else
moveTo(x, y);
#endif
showCursor();
PIByteArray ba(4096);
#ifdef CC_VC
int ret = scanf_s(" %s", ba.data());
#else
int ret = scanf(" %s", ba.data());
#endif
listener->setActive(true);
if (run) start();
if (ret >= 1) return PIString(ba);
else return PIString();
}
PIString PIConsole::getString(const PIString & name) {
piForeachC (Column & i, tabs[cur_tab].columns)
piForeachC (Variable & j, i.variables)
if (j.name == name)
return getString(j.nx + 1, j.ny);
return PIString();
}
#define PRINT_VAR_BODY couts(fstr(format)); int ret = couts(value); couts(fstr(PIConsole::Dec)); return ret;
inline void PIConsole::printLine(const PIString & value, int dx, FormatFlags format) {
int i = width - value.length() - dx;
#if defined(QNX) || defined(FREE_BSD)
--i;
#endif
PIString ts = fstr(format);
couts(ts);
if (i >= 0) ts = value + PIString(i, ' ');
else ts = value.left(value.size() + i);
couts(ts);
couts(fstr(Dec));
}
inline int PIConsole::printValue(const PIString & value, FormatFlags format) {
couts(fstr(format));
int ret = couts(value);
fstr(PIConsole::Dec);
return ret;
}
inline int PIConsole::printValue(const char * value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const bool value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const int value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const long value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const llong value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const float value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const double value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const char value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const short value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const uchar value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const ushort value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const uint value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const ulong value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const ullong value, FormatFlags format) {PRINT_VAR_BODY}
inline int PIConsole::printValue(const PISystemTime & value, FormatFlags format) {PRINT_VAR_BODY}
void PIConsole::startServer(const PIString & name) {
stopPeer();
server_mode = true;
peer = new PIPeer("_rcs_:" + name);
CONNECT2(void, const PIString & , const PIByteArray &, peer, dataReceivedEvent, this, peerReceived);
CONNECT1(void, const PIString & , peer, peerDisconnectedEvent, this, peerDisconnectedEvent);
peer_timer->start(50.);
serverSendInfo();
}
void PIConsole::stopPeer() {
remote_clients.clear();
peer_timer->stop();
if (peer != 0) delete peer;
peer = 0;
state = Disconnected;
}
PIStringList PIConsole::clients() const {
PIStringList sl;
if (peer == 0) return sl;
piForeachC (PIPeer::PeerInfo & i, peer->allPeers()) {
if (i.name.left(6) != "_rcc_:") continue;
sl << i.name.right(i.name.length() - 6);
}
return sl;
}
void PIConsole::listenServers() {
stopPeer();
server_mode = false;
server_name.clear();
randomize();
peer = new PIPeer("_rcc_:" + PIDateTime::current().toString("hhmmssddMMyy_") + PIString::fromNumber(randomi()));
CONNECT2(void, const PIString & , const PIByteArray &, peer, dataReceivedEvent, this, peerReceived);
peer_timer->start(100.);
}
PIStringList PIConsole::availableServers() const {
PIStringList sl;
if (peer == 0) return sl;
piForeachC (PIPeer::PeerInfo & i, peer->allPeers()) {
if (i.name.left(6) != "_rcs_:") continue;
sl << i.name.right(i.name.length() - 6);
}
return sl;
}
void PIConsole::connectToServer(const PIString & name) {
if (peer == 0) listenServers();
server_name = name;
}
void PIConsole::disconnect() {
stopPeer();
}
void PIConsole::serverSendInfo() {
if (peer == 0) return;
PIByteArray ba;
ba << int(0xAA);
peer->sendToAll(ba);
}
void PIConsole::serverSendData() {
if (peer == 0) return;
PIByteArray ba;
PIVector<VariableContent> content;
piForeach (Tab & t, tabs)
piForeach (Column & c, t.columns)
piForeach (Variable & v, c.variables)
if (!v.isEmpty() && v.id > 0) {
VariableContent vc;
vc.id = v.id;
v.writeData(vc.rdata);
content << vc;
}
piForeach (RemoteClient & rc, remote_clients) {
ba.clear();
switch (rc.state) {
case FetchingData:
ba << int(0xCC) << tabs;
//piCout << "server send const data" << rc.name << ba.size_s();
break;
case Committing:
ba << int(0xDD);
break;
case Connected:
ba << int(0xEE) << content;
//piCout << "send data" << ba.size();
break;
default: break;
}
if (!ba.isEmpty())
peer->send(rc.name, ba);
}
}
PIConsole::RemoteClient & PIConsole::remoteClient(const PIString & fname) {
piForeach (RemoteClient & i, remote_clients)
if (i.name == fname)
return i;
remote_clients << RemoteClient(fname);
return remote_clients.back();
}
void PIConsole::peerReceived(const PIString & from, const PIByteArray & data) {
int type;
PIByteArray ba(data);
ba >> type;
//piCout << "rec packet from" << from << "type" << PICoutManipulators::Hex << type;
if (server_mode) {
if (from.left(5) != "_rcc_") return;
//PIString rcn = from.right(from.length() - 6);
RemoteClient & rc(remoteClient(from));
switch (type) {
case 0xBB: // fetch const data request
//piCout << "fetch data request from" << from << rc.state;
if (rc.state != Connected)
rc.state = FetchingData;
break;
case 0xCC: // const data commit
//piCout << "commit from" << from;
if (rc.state != Connected)
rc.state = Connected;
break;
default: break;
}
} else {
PIVector<VariableContent> content;
PIMap<int, Variable * > vids;
if (from.left(5) != "_rcs_") return;
//PIString rcn = from.right(from.length() - 6);
switch (type) {
case 0xAA: // new server
//piCout << "new server" << rcn;
break;
case 0xCC: // const data
//piCout << "received const data";
state = Committing;
ba >> tabs;
cur_tab = tabs.isEmpty() ? -1 : 0;
piForeach (Tab & t, tabs)
piForeach (Column & c, t.columns)
piForeach (Variable & v, c.variables)
v.remote = true;
break;
case 0xDD: // const data commit
//piCout << "received commit";
state = Connected;
break;
case 0xEE: // dynamic data
//piCout << "received data" << ba.size_s();
piForeach (Tab & t, tabs)
piForeach (Column & c, t.columns)
piForeach (Variable & v, c.variables)
if (!v.isEmpty() && v.id > 0)
vids[v.id] = &v;
ba >> content;
piForeach (VariableContent & vc, content) {
if (vc.id <= 0) continue;
Variable * v = vids.at(vc.id);
if (v == 0) continue;
//piCout << "read" << v->name << vc.rdata.size_s();
v->rdata = vc.rdata;
}
break;
default: break;
}
}
}
void PIConsole::peerTimer(void * data, int delim) {
if (peer == 0) return;
//piCout << "timer" << delim;
if (server_mode) {
if (delim == 20)
serverSendInfo();
else
serverSendData();
} else {
if (delim != 1 || server_name.isEmpty()) return;
const PIPeer::PeerInfo * p = peer->getPeerByName("_rcs_:" + server_name);
if (p == 0) return;
PIByteArray ba;
switch (state) {
case Disconnected:
peer_tm.reset();
ba << int(0xBB);
//piCout << "send to" << server_name << "fetch request disc";
peer->send(p, ba);
state = FetchingData;
break;
case FetchingData:
if (peer_tm.elapsed_s() < 3.)
return;
peer_tm.reset();
ba << int(0xBB);
//piCout << "send to" << server_name << "fetch request fd";
peer->send(p, ba);
break;
case Committing:
peer_tm.reset();
ba << int(0xCC);
//piCout << "send to" << server_name << "committing";
state = Connected;
peer->send(p, ba);
break;
default: break;
};
}
}
void PIConsole::peerDisconnectedEvent(const PIString & name) {
for (int i = 0; i < remote_clients.size_s(); ++i)
if (remote_clients[i].name == name) {
remote_clients.remove(i);
--i;
}
}

View File

@@ -480,7 +480,7 @@ void PIScreen::mouse_event(PIKbdListener::MouseEvent me) {
PIVector<PIScreenTile * > tl = prepareMouse(&me); PIVector<PIScreenTile * > tl = prepareMouse(&me);
if (tl.isEmpty()) return; if (tl.isEmpty()) return;
piForeachR (PIScreenTile * t, tl) piForeachR (PIScreenTile * t, tl)
if (t->mouseEvent(me)) piBreak; if (t->mouseEvent(me)) break;
} }
@@ -488,7 +488,7 @@ void PIScreen::wheel_event(PIKbdListener::WheelEvent we) {
PIVector<PIScreenTile * > tl = prepareMouse(&we); PIVector<PIScreenTile * > tl = prepareMouse(&we);
if (tl.isEmpty()) return; if (tl.isEmpty()) return;
piForeachR (PIScreenTile * t, tl) piForeachR (PIScreenTile * t, tl)
if (t->wheelEvent(we)) piBreak; if (t->wheelEvent(we)) break;
} }

View File

@@ -805,7 +805,7 @@ bool PITerminal::initialize() {
if (e.startsWith("TERM=")) { if (e.startsWith("TERM=")) {
PRIVATE->term_type = termType(e.mid(5).trim().toLowerCase()); PRIVATE->term_type = termType(e.mid(5).trim().toLowerCase());
//piCout << PRIVATE->term_type; //piCout << PRIVATE->term_type;
piBreak; break;
} }
pid_t fr = forkpty(&(PRIVATE->fd), pty, 0, &ws); pid_t fr = forkpty(&(PRIVATE->fd), pty, 0, &ws);
//piCoutObj << fr << PRIVATE->fd << pty; //piCoutObj << fr << PRIVATE->fd << pty;

View File

@@ -36,7 +36,7 @@
template <typename T> template <typename T>
class PIP_EXPORT PIFFTW_Private class PIFFTW_Private
{ {
public: public:
explicit PIFFTW_Private() { explicit PIFFTW_Private() {

View File

@@ -23,16 +23,26 @@
#ifndef PICCLOUDCLIENT_H #ifndef PICCLOUDCLIENT_H
#define PICCLOUDCLIENT_H #define PICCLOUDCLIENT_H
#include "pip_cloud_export.h"
#include "piiodevice.h" #include "piiodevice.h"
class PIEthernet;
class PIP_EXPORT PICloudClient {
class PIP_CLOUD_EXPORT PICloudClient : public PIIODevice
{
PIIODEVICE(PICloudClient)
public: public:
//! //!
explicit PICloudClient(); explicit PICloudClient();
virtual ~PICloudClient();
protected:
bool openDevice();
bool closeDevice();
private: private:
PIEthernet * eth;
}; };
#endif // PICCLOUDCLIENT_H #endif // PICCLOUDCLIENT_H

View File

@@ -23,10 +23,11 @@
#ifndef PICCLOUDSERVER_H #ifndef PICCLOUDSERVER_H
#define PICCLOUDSERVER_H #define PICCLOUDSERVER_H
#include "pip_cloud_export.h"
#include "piiodevice.h" #include "piiodevice.h"
class PIP_EXPORT PICloudServer { class PIP_CLOUD_EXPORT PICloudServer {
public: public:
//! //!
explicit PICloudServer(); explicit PICloudServer();

View File

@@ -23,9 +23,10 @@
#ifndef PICCLOUDTCP_H #ifndef PICCLOUDTCP_H
#define PICCLOUDTCP_H #define PICCLOUDTCP_H
#include "pip_cloud_export.h"
#include "pistring.h" #include "pistring.h"
class PIP_EXPORT PICloudTCP { class PIP_CLOUD_EXPORT PICloudTCP {
public: public:
//! //!
PICloudTCP(); PICloudTCP();

View File

@@ -30,7 +30,7 @@ class PIVariant;
namespace PICodeInfo { namespace PICodeInfo {
enum PIP_EXPORT TypeFlag { enum TypeFlag {
NoFlag, NoFlag,
Const = 0x01, Const = 0x01,
Static = 0x02, Static = 0x02,
@@ -153,10 +153,10 @@ inline PICout operator <<(PICout s, const PICodeInfo::EnumInfo & v) {
return s; return s;
} }
extern PIMap<PIString, PICodeInfo::ClassInfo * > * classesInfo; extern PIP_EXPORT PIMap<PIString, PICodeInfo::ClassInfo * > * classesInfo;
extern PIMap<PIString, PICodeInfo::EnumInfo * > * enumsInfo; extern PIP_EXPORT PIMap<PIString, PICodeInfo::EnumInfo * > * enumsInfo;
extern PIMap<PIString, PICodeInfo::AccessValueFunction> * accessValueFunctions; extern PIP_EXPORT PIMap<PIString, PICodeInfo::AccessValueFunction> * accessValueFunctions;
extern PIMap<PIString, PICodeInfo::AccessTypeFunction> * accessTypeFunctions; extern PIP_EXPORT PIMap<PIString, PICodeInfo::AccessTypeFunction> * accessTypeFunctions;
inline PIByteArray getMemberValue(const void * p, const char * class_name, const char * member_name) { inline PIByteArray getMemberValue(const void * p, const char * class_name, const char * member_name) {
if (!p || !class_name || !member_name || !accessValueFunctions) return PIByteArray(); if (!p || !class_name || !member_name || !accessValueFunctions) return PIByteArray();
@@ -172,11 +172,11 @@ inline const char * getMemberType(const char * class_name, const char * member_n
return af(member_name); return af(member_name);
} }
PIVariant getMemberAsVariant(const void * p, const char * class_name, const char * member_name); PIP_EXPORT PIVariant getMemberAsVariant(const void * p, const char * class_name, const char * member_name);
} }
class __PICodeInfoInitializer__ { class PIP_EXPORT __PICodeInfoInitializer__ {
public: public:
__PICodeInfoInitializer__() { __PICodeInfoInitializer__() {
if (_inited_) return; if (_inited_) return;

View File

@@ -24,7 +24,7 @@
PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const { PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
PIStringList arg_vals; PIStringList arg_vals;
while (!args_.isEmpty()) { while (!args_.isEmpty()) {
int ci = args_.find(","), bi = args_.find("("); int ci = args_.find(','), bi = args_.find('(');
if (ci < 0) { if (ci < 0) {
arg_vals << args_; arg_vals << args_;
break; break;
@@ -33,7 +33,7 @@ PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
if (bi >= 0 && bi < ci) { if (bi >= 0 && bi < ci) {
ca = args_.left(args_.takeLeft(bi).toInt()); ca = args_.left(args_.takeLeft(bi).toInt());
ci -= ca.size_s(); bi -= ca.size_s(); ci -= ca.size_s(); bi -= ca.size_s();
ca += "(" + args_.takeRange("(", ")") + ")"; ca += '(' + args_.takeRange('(', ')') + ')';
} else { } else {
ca = args_.takeLeft(ci); ca = args_.takeLeft(ci);
} }
@@ -41,7 +41,7 @@ PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
args_.trim(); args_.takeLeft(1); args_.trim(); args_.trim(); args_.takeLeft(1); args_.trim();
} }
if (args.size() != arg_vals.size()) { if (args.size() != arg_vals.size()) {
piCout << ("Error: in expansion of macro \"" + name + "(" + args.join(", ") + ")\": expect") piCout << ("Error: in expansion of macro \"" + name + '(' + args.join(", ") + ")\": expect")
<< args.size() << "arguments but takes" << arg_vals.size() << "!"; << args.size() << "arguments but takes" << arg_vals.size() << "!";
if (ok != 0) *ok = false; if (ok != 0) *ok = false;
return PIString(); return PIString();
@@ -57,7 +57,7 @@ PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
if (ind + an.size_s() < ret.size_s()) nc = ret.mid(ind + an.size_s(),1)[0]; if (ind + an.size_s() < ret.size_s()) nc = ret.mid(ind + an.size_s(),1)[0];
if (ppc != '#' && pc == '#' && !_isCChar(nc)) { // to chars if (ppc != '#' && pc == '#' && !_isCChar(nc)) { // to chars
ind--; ind--;
ret.replace(ind, an.size_s() + 1, "\"" + av + "\""); ret.replace(ind, an.size_s() + 1, '\"' + av + '\"');
ind -= an.size_s() - av.size_s() - 1; ind -= an.size_s() - av.size_s() - 1;
continue; continue;
} }
@@ -66,7 +66,7 @@ PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
ind -= an.size_s() - av.size_s(); ind -= an.size_s() - av.size_s();
} }
} }
ret.replaceAll("##", ""); ret.replaceAll(PIStringAscii("##"), "");
if (ok != 0) *ok = true; if (ok != 0) *ok = true;
return ret; return ret;
} }
@@ -99,42 +99,42 @@ void PICodeParser::parseFile(const PIString & file, bool follow_includes) {
} }
piCout << "\n\nDefines:"; piCout << "\n\nDefines:";
piForeachC (Define & m, defines) piForeachC (Define & m, defines)
piCout << "define" << m.first << m.second; piCout << PIStringAscii("define") << m.first << m.second;
piCout << "\n\nMacros:"; piCout << "\n\nMacros:";
piForeachC (Macro & m, macros) piForeachC (Macro & m, macros)
piCout << "Macro:" << m.name << m.args << m.value; piCout << "Macro:" << m.name << m.args << m.value;
piCout << "\n\nClasses:"; piCout << "\n\nClasses:";
piCout << "\n\nEnums:"; piCout << "\n\nEnums:";
piForeachC (Enum & c, enums) { piForeachC (Enum & c, enums) {
piCout << "enum" << c.name << c.meta; piCout << PIStringAscii("enum") << c.name << c.meta;
piForeachC (EnumeratorInfo & e, c.members) piForeachC (EnumeratorInfo & e, c.members)
piCout << " " << e.name << "=" << e.value << e.meta; piCout << " " << e.name << '=' << e.value << e.meta;
} }
piCout << "\n\nTypedefs:"; piCout << "\n\nTypedefs:";
piForeachC (Typedef & c, typedefs) piForeachC (Typedef & c, typedefs)
piCout << "typedef" << c;*/ piCout << PIStringAscii("typedef") << c;*/
} }
void PICodeParser::parseFiles(const PIStringList & files, bool follow_includes) { void PICodeParser::parseFiles(const PIStringList & files, bool follow_includes) {
clear(); clear();
piForeachC (PIString & f, files) piForeachC (PIString & f, files)
parseFileInternal(f, follow_includes); parseFileInternal(f, follow_includes);
/*piCout << "\n\nDefines:"; /*piCout << "\n\nDefines:";
piForeachC (Define & m, defines) piForeachC (Define & m, defines)
piCout << "define" << m.first << m.second; piCout << PIStringAscii("define") << m.first << m.second;
piCout << "\n\nMacros:"; piCout << "\n\nMacros:";
piForeachC (Macro & m, macros) piForeachC (Macro & m, macros)
piCout << "Macro:" << m.name << m.args << m.value; piCout << "Macro:" << m.name << m.args << m.value;
piCout << "\n\nClasses:"; piCout << "\n\nClasses:";
piForeachC (Entity * c, entities) piForeachC (Entity * c, entities)
piCout << "class" << c->name << c->parents; piCout << PIStringAscii("class") << c->name << c->parents;
piCout << "\n\nEnums:"; piCout << "\n\nEnums:";
piForeachC (Enum & c, enums) piForeachC (Enum & c, enums)
piCout << "enum" << c.name << c.members; piCout << PIStringAscii("enum") << c.name << c.members;
piCout << "\n\nTypedefs:"; piCout << "\n\nTypedefs:";
piForeachC (Typedef & c, typedefs) piForeachC (Typedef & c, typedefs)
piCout << "typedef" << c;*/ piCout << PIStringAscii("typedef") << c;*/
} }
@@ -153,7 +153,7 @@ bool PICodeParser::parseFileInternal(const PIString & file, bool follow_includes
PIFile f(file, PIIODevice::ReadOnly); PIFile f(file, PIIODevice::ReadOnly);
int ii = 0; int ii = 0;
while (!f.isOpened() && ii < (includes.size_s() - 1)) { while (!f.isOpened() && ii < (includes.size_s() - 1)) {
f.setPath(includes[++ii] + "/" + file); f.setPath(includes[++ii] + '/' + file);
//piCout << "try" << f.path(); //piCout << "try" << f.path();
f.open(PIIODevice::ReadOnly); f.open(PIIODevice::ReadOnly);
} }
@@ -186,7 +186,10 @@ void PICodeParser::clear() {
evaluator.clearCustomVariables(); evaluator.clearCustomVariables();
cur_def_vis = Global; cur_def_vis = Global;
anon_num = 0; anon_num = 0;
defines << Define("PICODE", "") << custom_defines; PIStringList defs = PIStringAscii(PICODE_DEFINES).split(",");
piForeachC (PIString & d, defs)
defines << Define(d, "");
defines << Define(PIStringAscii("PICODE"), "") << custom_defines;
} }
@@ -197,9 +200,9 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
PIString pfc, line, ccmn, tmp; PIString pfc, line, ccmn, tmp;
PIMap<PIString, PIString> cchars; PIMap<PIString, PIString> cchars;
/// Remove comments, join multiline "*" and replace "*" to $n (cchars) /// Remove comments, join multiline '*' and replace '*' to $n (cchars)
fc.replaceAll("\r\n", "\n"); fc.replaceAll("\r\n", '\n');
fc.replaceAll("\r", "\n"); fc.replaceAll('\r', '\n');
for (int i = 0; i < fc.size_s() - 1; ++i) { for (int i = 0; i < fc.size_s() - 1; ++i) {
if (fc[i].unicode16Code() >= 255) continue; if (fc[i].unicode16Code() >= 255) continue;
if (i > 0) pc = c; if (i > 0) pc = c;
@@ -256,7 +259,7 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
if (ind + m.name.size_s() < pfc.size_s()) nc = pfc.mid(ind + m.name.size_s(),1)[0]; if (ind + m.name.size_s() < pfc.size_s()) nc = pfc.mid(ind + m.name.size_s(),1)[0];
if (_isCChar(pc) || _isCChar(nc) || nc.isDigit()) continue; if (_isCChar(pc) || _isCChar(nc) || nc.isDigit()) continue;
PIString ret, range; bool ok(false); PIString ret, range; bool ok(false);
range = pfc.mid(ind + m.name.size_s()).takeRange("(", ")"); range = pfc.mid(ind + m.name.size_s()).takeRange('(', ')');
ret = m.expand(range, &ok); ret = m.expand(range, &ok);
if (!ok) return false; if (!ok) return false;
int rlen = pfc.find(range, ind + m.name.size_s()) + range.size_s() + 1 - ind; int rlen = pfc.find(range, ind + m.name.size_s()) + range.size_s() + 1 - ind;
@@ -274,46 +277,46 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
int nl = pfc.size_s(); int nl = pfc.size_s();
if (pl == nl) break; if (pl == nl) break;
pl = nl; pl = nl;
if (pfc.left(9) == "namespace") { if (pfc.left(9) == PIStringAscii("namespace")) {
pfc.cutLeft(pfc.find("{") + 1); pfc.cutLeft(pfc.find('{') + 1);
continue; continue;
} }
if (pfc.left(8) == "template") { if (pfc.left(8) == PIStringAscii("template")) {
pfc.cutLeft(8); pfc.cutLeft(8);
pfc.takeRange("<", ">"); pfc.takeRange('<', '>');
bool def = !isDeclaration(pfc, 0, &end); bool def = !isDeclaration(pfc, 0, &end);
pfc.cutLeft(end); pfc.cutLeft(end);
if (def) pfc.takeRange("{", "}"); if (def) pfc.takeRange('{', '}');
else pfc.takeSymbol(); else pfc.takeSymbol();
continue; continue;
} }
if (pfc.left(5) == "class" || pfc.left(6) == "struct" || pfc.left(5) == "union") { if (pfc.left(5) == PIStringAscii("class") || pfc.left(6) == PIStringAscii("struct") || pfc.left(5) == PIStringAscii("union")) {
int dind = pfc.find("{", 0), find = pfc.find(";", 0); int dind = pfc.find('{', 0), find = pfc.find(';', 0);
if (dind < 0 && find < 0) {pfc.cutLeft(6); continue;} if (dind < 0 && find < 0) {pfc.cutLeft(6); continue;}
if (dind < 0 || find < dind) {pfc.cutLeft(6); continue;} if (dind < 0 || find < dind) {pfc.cutLeft(6); continue;}
ccmn = pfc.left(dind) + "{\n" + pfc.mid(dind).takeRange('{', '}') + "\n}\n"; ccmn = pfc.left(dind) + PIStringAscii("{\n") + pfc.mid(dind).takeRange('{', '}') + PIStringAscii("\n}\n");
pfc.remove(0, ccmn.size()); pfc.remove(0, ccmn.size());
parseClass(0, ccmn); parseClass(0, ccmn);
continue; continue;
} }
if (pfc.left(4) == "enum") { if (pfc.left(4) == PIStringAscii("enum")) {
pfc.cutLeft(4); pfc.cutLeft(4);
tmp = pfc.takeCWord(); tmp = pfc.takeCWord();
pfc.trim(); pfc.trim();
MetaMap meta = maybeMeta(pfc); MetaMap meta = maybeMeta(pfc);
parseEnum(0, cur_namespace + tmp, pfc.takeRange("{", "}"), meta); parseEnum(0, cur_namespace + tmp, pfc.takeRange('{', '}'), meta);
pfc.takeSymbol(); pfc.takeSymbol();
continue; continue;
} }
if (pfc.left(7) == "typedef") { if (pfc.left(7) == PIStringAscii("typedef")) {
pfc.cutLeft(7); pfc.cutLeft(7);
typedefs << parseTypedef(pfc.takeLeft(pfc.find(";"))); typedefs << parseTypedef(pfc.takeLeft(pfc.find(';')));
if (typedefs.back().first.isEmpty()) typedefs.pop_back(); if (typedefs.back().first.isEmpty()) typedefs.pop_back();
else root_.typedefs << typedefs.back(); else root_.typedefs << typedefs.back();
pfc.takeSymbol(); pfc.takeSymbol();
continue; continue;
} }
int sci = pfc.find(";", 0), obi = pfc.find("{", 0); int sci = pfc.find(';', 0), obi = pfc.find('{', 0);
if (sci < 0 && obi < 0) { if (sci < 0 && obi < 0) {
pfc.takeLeft(1); pfc.takeLeft(1);
continue; continue;
@@ -323,7 +326,7 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
str = pfc.takeLeft(sci + 1); str = pfc.takeLeft(sci + 1);
} else { } else {
str = pfc.takeLeft(obi); str = pfc.takeLeft(obi);
pfc.cutLeft(pfc.takeRange("{", "}").toInt()); pfc.cutLeft(pfc.takeRange('{', '}').toInt());
} }
parseMember(&root_, str); parseMember(&root_, str);
} }
@@ -333,22 +336,22 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
PICodeParser::Entity * PICodeParser::parseClassDeclaration(const PIString & fc) { PICodeParser::Entity * PICodeParser::parseClassDeclaration(const PIString & fc) {
PIString cd = fc.trimmed().removeAll('\n').replaceAll("\t", " ").replaceAll(" ", " "), pn; PIString cd = fc.trimmed().removeAll('\n').replaceAll('\t', ' ').replaceAll(PIStringAscii(" "), ' '), pn;
MetaMap meta; MetaMap meta;
int ind = cd.find("$M"); int ind = cd.find(PIStringAscii("$M"));
if (ind >= 0) { if (ind >= 0) {
meta = tmp_meta.value(cd.takeMid(ind, 5)); meta = tmp_meta.value(cd.takeMid(ind, 5));
cd.replaceAll(" ", " "); cd.replaceAll(PIStringAscii(" "), ' ');
} }
//piCout << "found class <****\n" << cd << "\n****>"; //piCout << "found class <****\n" << cd << "\n****>";
ind = cd.find(":"); ind = cd.find(':');
PIVector<Entity * > parents; PIVector<Entity * > parents;
if (ind > 0) { if (ind > 0) {
PIStringList pl = cd.takeMid(ind + 1).trim().split(","); PIStringList pl = cd.takeMid(ind + 1).trim().split(',');
cd.cutRight(1); cd.cutRight(1);
Entity * pe = 0; Entity * pe = 0;
piForeachC (PIString & p, pl) { piForeachC (PIString & p, pl) {
if (p.contains(" ")) pn = p.mid(p.find(" ") + 1); if (p.contains(' ')) pn = p.mid(p.find(' ') + 1);
else pn = p; else pn = p;
pe = findEntityByName(pn); pe = findEntityByName(pn);
if (pe == 0) ;//{piCout << "Error: can`t find" << pn;} if (pe == 0) ;//{piCout << "Error: can`t find" << pn;}
@@ -356,11 +359,11 @@ PICodeParser::Entity * PICodeParser::parseClassDeclaration(const PIString & fc)
} }
} }
PIString typename_ = cd.left(6).trim(); PIString typename_ = cd.left(6).trim();
bool is_class = typename_ == "class"; bool is_class = typename_ == PIStringAscii("class");
cur_def_vis = (is_class ? Private : Public); cur_def_vis = (is_class ? Private : Public);
PIString cn = cd.mid(6).trim(); PIString cn = cd.mid(6).trim();
bool has_name = !cn.isEmpty(); bool has_name = !cn.isEmpty();
if (cn.isEmpty()) cn = "<unnamed_" + PIString::fromNumber(anon_num++) + ">"; if (cn.isEmpty()) cn = PIStringAscii("<unnamed_") + PIString::fromNumber(anon_num++) + '>';
//piCout << "found " << typename_ << cn; //piCout << "found " << typename_ << cn;
if (cn.isEmpty()) return 0; if (cn.isEmpty()) return 0;
Entity * e = new Entity(); Entity * e = new Entity();
@@ -377,7 +380,7 @@ PICodeParser::Entity * PICodeParser::parseClassDeclaration(const PIString & fc)
PIString PICodeParser::parseClass(Entity * parent, PIString & fc) { PIString PICodeParser::parseClass(Entity * parent, PIString & fc) {
Visibility prev_vis = cur_def_vis; Visibility prev_vis = cur_def_vis;
int dind = fc.find("{"), find = fc.find(";"), end = 0; int dind = fc.find('{'), find = fc.find(';'), end = 0;
if (dind < 0 && find < 0) return PIString(); if (dind < 0 && find < 0) return PIString();
if (dind < 0 || find < dind) return fc.left(find); if (dind < 0 || find < dind) return fc.left(find);
//piCout << "parse class <****\n" << fc.left(20) << "\n****>"; //piCout << "parse class <****\n" << fc.left(20) << "\n****>";
@@ -390,43 +393,43 @@ PIString PICodeParser::parseClass(Entity * parent, PIString & fc) {
int ps = -1; int ps = -1;
bool def = false; bool def = false;
PIString prev_namespace = cur_namespace, stmp; PIString prev_namespace = cur_namespace, stmp;
cur_namespace = ce->name + "::"; cur_namespace = ce->name + PIStringAscii("::");
//piCout << "parse class" << ce->name << "namespace" << cur_namespace; //piCout << "parse class" << ce->name << "namespace" << cur_namespace;
//piCout << "\nparse class" << ce->name << "namespace" << cur_namespace; //piCout << "\nparse class" << ce->name << "namespace" << cur_namespace;
while (!fc.isEmpty()) { while (!fc.isEmpty()) {
PIString cw = fc.takeCWord(), tmp; PIString cw = fc.takeCWord(), tmp;
//piCout << "\ntaked word" << cw; //piCout << "\ntaked word" << cw;
if (cw == "public") {cur_def_vis = Public; fc.cutLeft(1); continue;} if (cw == PIStringAscii("public" )) {cur_def_vis = Public; fc.cutLeft(1); continue;}
if (cw == "protected") {cur_def_vis = Protected; fc.cutLeft(1); continue;} if (cw == PIStringAscii("protected")) {cur_def_vis = Protected; fc.cutLeft(1); continue;}
if (cw == "private") {cur_def_vis = Private; fc.cutLeft(1); continue;} if (cw == PIStringAscii("private" )) {cur_def_vis = Private; fc.cutLeft(1); continue;}
if (cw == "class" || cw == "struct" || cw == "union") { if (cw == PIStringAscii("class") || cw == PIStringAscii("struct") || cw == PIStringAscii("union")) {
if (isDeclaration(fc, 0, &end)) { if (isDeclaration(fc, 0, &end)) {
fc.cutLeft(end); fc.cutLeft(end);
fc.takeSymbol(); fc.takeSymbol();
continue; continue;
} }
tmp = fc.takeLeft(fc.find("{")); tmp = fc.takeLeft(fc.find('{'));
stmp = fc.takeRange("{", "}"); stmp = fc.takeRange('{', '}');
fc.takeSymbol(); fc.takeSymbol();
stmp = cw + " " + tmp + "{" + stmp + "}"; stmp = cw + ' ' + tmp + '{' + stmp + '}';
parseClass(ce, stmp); parseClass(ce, stmp);
continue; continue;
} }
if (cw == "enum") { if (cw == PIStringAscii("enum")) {
tmp = fc.takeCWord(); tmp = fc.takeCWord();
fc.trim(); fc.trim();
MetaMap meta = maybeMeta(fc); MetaMap meta = maybeMeta(fc);
parseEnum(ce, cur_namespace + tmp, fc.takeRange("{", "}"), meta); parseEnum(ce, cur_namespace + tmp, fc.takeRange('{', '}'), meta);
fc.takeSymbol(); fc.takeSymbol();
continue; continue;
} }
if (cw == "friend") {fc.cutLeft(fc.find(";") + 1); continue;} if (cw == PIStringAscii("friend")) {fc.cutLeft(fc.find(';') + 1); continue;}
if (cw == "typedef") {ce->typedefs << parseTypedef(fc.takeLeft(fc.find(";"))); typedefs << ce->typedefs.back(); typedefs.back().first.insert(0, cur_namespace); if (ce->typedefs.back().first.isEmpty()) ce->typedefs.pop_back(); fc.takeSymbol(); continue;} if (cw == PIStringAscii("typedef")) {ce->typedefs << parseTypedef(fc.takeLeft(fc.find(';'))); typedefs << ce->typedefs.back(); typedefs.back().first.insert(0, cur_namespace); if (ce->typedefs.back().first.isEmpty()) ce->typedefs.pop_back(); fc.takeSymbol(); continue;}
if (cw == "template") { if (cw == PIStringAscii("template")) {
fc.takeRange("<", ">"); fc.takeRange('<', '>');
def = !isDeclaration(fc, 0, &end); def = !isDeclaration(fc, 0, &end);
fc.cutLeft(end); fc.cutLeft(end);
if (def) fc.takeRange("{", "}"); if (def) fc.takeRange('{', '}');
else fc.takeSymbol(); else fc.takeSymbol();
continue; continue;
} }
@@ -434,7 +437,7 @@ PIString PICodeParser::parseClass(Entity * parent, PIString & fc) {
tmp = (cw + fc.takeLeft(end)).trim(); tmp = (cw + fc.takeLeft(end)).trim();
if (!tmp.isEmpty()) if (!tmp.isEmpty())
parseMember(ce, tmp); parseMember(ce, tmp);
if (def) fc.takeRange("{", "}"); if (def) fc.takeRange('{', '}');
else fc.takeSymbol(); else fc.takeSymbol();
if (ps == fc.size_s()) {fc.cutLeft(1);} if (ps == fc.size_s()) {fc.cutLeft(1);}
ps = fc.size_s(); ps = fc.size_s();
@@ -448,13 +451,13 @@ PIString PICodeParser::parseClass(Entity * parent, PIString & fc) {
PICodeParser::MetaMap PICodeParser::parseMeta(PIString & fc) { PICodeParser::MetaMap PICodeParser::parseMeta(PIString & fc) {
PICodeParser::MetaMap ret; PICodeParser::MetaMap ret;
if (fc.isEmpty()) return ret; if (fc.isEmpty()) return ret;
PIStringList ml = fc.split(","); PIStringList ml = fc.split(',');
piForeachC (PIString & m, ml) { piForeachC (PIString & m, ml) {
int i = m.find("="); int i = m.find('=');
if (i < 0) continue; if (i < 0) continue;
PIString mv = m.mid(i + 1).trim(); PIString mv = m.mid(i + 1).trim();
if (mv.startsWith("\"")) mv.cutLeft(1); if (mv.startsWith('\"')) mv.cutLeft(1);
if (mv.endsWith("\"")) mv.cutRight(1); if (mv.endsWith('\"')) mv.cutRight(1);
ret[m.left(i).trim()] = mv; ret[m.left(i).trim()] = mv;
} }
//piCout << ms << ret; //piCout << ms << ret;
@@ -463,20 +466,22 @@ PICodeParser::MetaMap PICodeParser::parseMeta(PIString & fc) {
bool PICodeParser::parseEnum(Entity * parent, const PIString & name, PIString fc, const MetaMap & meta) { bool PICodeParser::parseEnum(Entity * parent, const PIString & name, PIString fc, const MetaMap & meta) {
//piCout << "enum" << name << fc; static const PIString s_ss = PIStringAscii(" ");
static const PIString s_M = PIStringAscii("$M");
//piCout << PIStringAscii("enum") << name << fc;
Enum e(name); Enum e(name);
e.meta = meta; e.meta = meta;
PIStringList vl(fc.split(",")); PIStringList vl(fc.split(','));
PIString vn; PIString vn;
int cv = -1, ind = 0; int cv = -1, ind = 0;
piForeach (PIString & v, vl) { piForeach (PIString & v, vl) {
MetaMap meta; MetaMap meta;
int mi = v.find("$M"); int mi = v.find(s_M);
if (mi >= 0) { if (mi >= 0) {
meta = tmp_meta.value(v.takeMid(mi, 5)); meta = tmp_meta.value(v.takeMid(mi, 5));
v.replaceAll(" ", " "); v.replaceAll(s_ss, ' ');
} }
vn = v; ind = v.find("="); vn = v; ind = v.find('=');
if (ind > 0) {cv = v.right(v.size_s() - ind - 1).toInt(); vn = v.left(ind);} if (ind > 0) {cv = v.right(v.size_s() - ind - 1).toInt(); vn = v.left(ind);}
if (ind < 0) ++cv; if (ind < 0) ++cv;
e.members << EnumeratorInfo(vn.trim(), cv, meta); e.members << EnumeratorInfo(vn.trim(), cv, meta);
@@ -492,15 +497,15 @@ bool PICodeParser::parseEnum(Entity * parent, const PIString & name, PIString fc
PICodeParser::Typedef PICodeParser::parseTypedef(PIString fc) { PICodeParser::Typedef PICodeParser::parseTypedef(PIString fc) {
//piCout << "parse typedef" << fc; //piCout << "parse typedef" << fc;
Typedef td; Typedef td;
fc.replaceAll("\t", " "); fc.replaceAll('\t', ' ');
if (fc.contains("(")) { if (fc.contains('(')) {
int start = fc.find("("), end = fc.find(")"); int start = fc.find('('), end = fc.find(')');
td.first = fc.takeMid(start + 1, end - start - 1).trim(); td.first = fc.takeMid(start + 1, end - start - 1).trim();
if (td.first.left(1) == "*") {td.first.cutLeft(1).trim(); fc.insert(start + 1, "*");} if (td.first.left(1) == PIChar('*')) {td.first.cutLeft(1).trim(); fc.insert(start + 1, '*');}
td.second = fc.trim(); td.second = fc.trim();
} else { } else {
td.first = fc.takeMid(fc.findLast(" ")).trim(); td.first = fc.takeMid(fc.findLast(' ')).trim();
td.second = fc.trim(); td.second = fc.trim();
} }
//piCout << "found typedef" << td; //piCout << "found typedef" << td;
@@ -509,34 +514,53 @@ PICodeParser::Typedef PICodeParser::parseTypedef(PIString fc) {
bool PICodeParser::parseMember(Entity * parent, PIString & fc) { bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
static const PIString s_operator = PIStringAscii("operator");
static const PIString s_ss = PIStringAscii(" ");
static const PIString s_cs = PIStringAscii(", ");
static const PIString s_sb = PIStringAscii(" (");
static const PIString s_sM = PIStringAscii(" $M");
static const PIString s_M = PIStringAscii("$M");
static const PIString s_T = PIStringAscii("$T");
static const PIString s_inline_s = PIStringAscii("inline ");
static const PIString s_static_s = PIStringAscii("static ");
static const PIString s_virtual_s = PIStringAscii("virtual ");
static const PIString s_void = PIStringAscii("void");
static const PIString s_using = PIStringAscii("using");
static const PIString s_s5 = PIStringAscii(" ");
static const PIString s_s_const_s = PIStringAscii(" const ");
static const PIString s_s_static_s = PIStringAscii(" static ");
static const PIString s_s_mutable_s = PIStringAscii(" mutable ");
static const PIString s_s_volatile_s = PIStringAscii(" volatile ");
static const PIString s_s_extern_s = PIStringAscii(" extern ");
if (fc.trim().isEmpty()) return true; if (fc.trim().isEmpty()) return true;
if (fc.find("operator") >= 0) return true; if (fc.find(s_operator) >= 0) return true;
tmp_temp.clear(); tmp_temp.clear();
//piCout << "parse member" << fc; //piCout << "parse member" << fc;
int ts = fc.find("<"), te = 0; int ts = fc.find('<'), te = 0;
PIString ctemp, crepl; PIString ctemp, crepl;
while (ts >= 0) { while (ts >= 0) {
ctemp = fc.mid(ts).takeRange("<", ">"); ctemp = fc.mid(ts).takeRange('<', '>');
if (ctemp.isEmpty()) {te = ts + 1; ts = fc.find("<", te); continue;} if (ctemp.isEmpty()) {te = ts + 1; ts = fc.find('<', te); continue;}
crepl = "$T" + PIString::fromNumber(tmp_temp.size_s()).expandLeftTo(3, "0"); crepl = s_T + PIString::fromNumber(tmp_temp.size_s()).expandLeftTo(3, '0');
fc.replace(ts, ctemp.size_s() + 2, crepl); fc.replace(ts, ctemp.size_s() + 2, crepl);
tmp_temp[crepl] = "<" + ctemp + ">"; tmp_temp[crepl] = '<' + ctemp + '>';
ts = fc.find("<", te); ts = fc.find('<', te);
} }
fc.replaceAll("\n", " ").replaceAll("\t", " ").replaceAll(" ", " ").replaceAll(", ", ",").replaceAll(" (", "(").replaceAll(" $M", "$M"); fc.replaceAll('\n', ' ').replaceAll('\t', ' ').replaceAll(s_ss, ' ').replaceAll(s_cs, ',').replaceAll(s_sb, '(').replaceAll(s_sM, s_M);
//piCout << "parse member" << fc; //piCout << "parse member" << fc;
PIStringList tl, al; PIStringList tl, al;
Member me; Member me;
//piCout << fc; //piCout << fc;
if (fc.contains("(")) { if (fc.contains('(')) {
MetaMap meta; MetaMap meta;
int ind = fc.find("$M"); int ind = fc.find(s_M);
if (ind >= 0) { if (ind >= 0) {
meta = tmp_meta.value(fc.takeMid(ind, 5)); meta = tmp_meta.value(fc.takeMid(ind, 5));
fc.replaceAll(" ", " ").replaceAll(" (", "("); fc.replaceAll(s_ss, ' ').replaceAll(s_sb, '(');
} }
fc.cutRight(fc.size_s() - fc.findLast(")") - 1); fc.cutRight(fc.size_s() - fc.findLast(')') - 1);
te = fc.find("("); te = fc.find('(');
//piCout << fc; //piCout << fc;
for (ts = te - 1; ts >= 0; --ts) for (ts = te - 1; ts >= 0; --ts)
if (!_isCChar(fc[ts]) && !(fc[ts].isDigit())) break; if (!_isCChar(fc[ts]) && !(fc[ts].isDigit())) break;
@@ -544,37 +568,37 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
me.meta = meta; me.meta = meta;
me.name = fc.takeMid(ts + 1, te - ts - 1); me.name = fc.takeMid(ts + 1, te - ts - 1);
if (me.name == parent->name) return true; if (me.name == parent->name) return true;
me.arguments_full = fc.takeMid(ts + 2).cutRight(1).split(","); me.arguments_full = fc.takeMid(ts + 2).cutRight(1).split(',');
me.type = fc.cutRight(1).trim(); me.type = fc.cutRight(1).trim();
me.visibility = cur_def_vis; me.visibility = cur_def_vis;
if (me.type.find("inline ") >= 0) { if (me.type.find(s_inline_s) >= 0) {
me.attributes |= Inline; me.attributes |= Inline;
me.type.removeAll("inline "); me.type.removeAll(s_inline_s);
} }
if (me.type.find("static ") >= 0) { if (me.type.find(s_static_s) >= 0) {
me.attributes |= Static; me.attributes |= Static;
me.type.removeAll("static "); me.type.removeAll(s_static_s);
} }
if (me.type.find("virtual ") >= 0) { if (me.type.find(s_virtual_s) >= 0) {
me.attributes |= Virtual; me.attributes |= Virtual;
me.type.removeAll("virtual "); me.type.removeAll(s_virtual_s);
} }
normalizeEntityNamespace(me.type); normalizeEntityNamespace(me.type);
int i = 0; int i = 0;
//piCout << me.arguments_full; //piCout << me.arguments_full;
piForeach (PIString & a, me.arguments_full) piForeach (PIString & a, me.arguments_full)
if ((i = a.find("=")) > 0) if ((i = a.find('=')) > 0)
a.cutRight(a.size_s() - i).trim(); a.cutRight(a.size_s() - i).trim();
for (int j = 0; j < me.arguments_full.size_s(); ++j) for (int j = 0; j < me.arguments_full.size_s(); ++j)
if (me.arguments_full[j] == "void") { if (me.arguments_full[j] == s_void) {
me.arguments_full.remove(j); me.arguments_full.remove(j);
--j; --j;
} }
me.arguments_type = me.arguments_full; me.arguments_type = me.arguments_full;
piForeach (PIString & a, me.arguments_type) { piForeach (PIString & a, me.arguments_type) {
crepl.clear(); crepl.clear();
if (a.contains("[")) if (a.contains('['))
crepl = a.takeMid(a.find("["), a.findLast("]") - a.find("[") + 1); crepl = a.takeMid(a.find('['), a.findLast(']') - a.find('[') + 1);
for (ts = a.size_s() - 1; ts >= 0; --ts) for (ts = a.size_s() - 1; ts >= 0; --ts)
if (!_isCChar(a[ts]) && !(a[ts].isDigit())) break; if (!_isCChar(a[ts]) && !(a[ts].isDigit())) break;
a.cutRight(a.size_s() - ts - 1); a.cutRight(a.size_s() - ts - 1);
@@ -586,18 +610,18 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
//piCout << "func" << me.type << me.name << me.arguments_full << me.arguments_type; //piCout << "func" << me.type << me.name << me.arguments_full << me.arguments_type;
parent->functions << me; parent->functions << me;
} else { } else {
if (fc.endsWith(";")) fc.cutRight(1); if (fc.endsWith(';')) fc.cutRight(1);
if (fc.startsWith("using") || !(fc.contains(' ') || fc.contains('\t') || fc.contains('\n'))) return true; if (fc.startsWith(s_using) || !(fc.contains(' ') || fc.contains('\t') || fc.contains('\n'))) return true;
int bits = extractMemberBits(fc); int bits = extractMemberBits(fc);
tl = fc.split(","); tl = fc.split(',');
//piCout << "member" << fc << tl; //piCout << "member" << fc << tl;
//piCout << "member after eb" << fc << ", bits =" << bits; //piCout << "member after eb" << fc << ", bits =" << bits;
if (tl.isEmpty()) return true; if (tl.isEmpty()) return true;
bool vn = true; bool vn = true;
ctemp = tl.front().trim(); ctemp = tl.front().trim();
PIString meta_t; PIString meta_t;
if (ctemp.contains("$M")) if (ctemp.contains(s_M))
meta_t = ctemp.takeMid(ctemp.find("$M")); meta_t = ctemp.takeMid(ctemp.find(s_M));
for (ts = ctemp.size_s() - 1; ts > 0; --ts) { for (ts = ctemp.size_s() - 1; ts > 0; --ts) {
if (vn) {if (!_isCChar(ctemp[ts]) && !ctemp[ts].isDigit() && ctemp[ts] != '[' && ctemp[ts] != ']') vn = false;} if (vn) {if (!_isCChar(ctemp[ts]) && !ctemp[ts].isDigit() && ctemp[ts] != '[' && ctemp[ts] != ']') vn = false;}
else {if (_isCChar(ctemp[ts]) || ctemp[ts].isDigit()) break;} else {if (_isCChar(ctemp[ts]) || ctemp[ts].isDigit()) break;}
@@ -606,26 +630,26 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
me.visibility = cur_def_vis; me.visibility = cur_def_vis;
ctemp += meta_t; ctemp += meta_t;
restoreTmpTemp(&me); restoreTmpTemp(&me);
PIString type = " " + me.type; PIString type = s_s5 + me.type;
if (type.find(" const ") >= 0) { if (type.find(s_s_const_s) >= 0) {
me.attributes |= Const; me.attributes |= Const;
type.replaceAll(" const ", " "); type.replaceAll(s_s_const_s, ' ');
} }
if (type.find(" static ") >= 0) { if (type.find(s_s_static_s) >= 0) {
me.attributes |= Static; me.attributes |= Static;
type.replaceAll(" static ", " "); type.replaceAll(s_s_static_s, ' ');
} }
if (type.find(" mutable ") >= 0) { if (type.find(s_s_mutable_s) >= 0) {
me.attributes |= Mutable; me.attributes |= Mutable;
type.replaceAll(" mutable ", " "); type.replaceAll(s_s_mutable_s, ' ');
} }
if (type.find(" volatile ") >= 0) { if (type.find(s_s_volatile_s) >= 0) {
me.attributes |= Volatile; me.attributes |= Volatile;
type.replaceAll(" volatile ", " "); type.replaceAll(s_s_volatile_s, ' ');
} }
if (type.find(" extern ") >= 0) { if (type.find(s_s_extern_s) >= 0) {
me.attributes |= Extern; me.attributes |= Extern;
type.replaceAll(" extern ", " "); type.replaceAll(s_s_extern_s, ' ');
} }
type.trim(); type.trim();
normalizeEntityNamespace(type); normalizeEntityNamespace(type);
@@ -637,15 +661,15 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
me.type = type; me.type = type;
restoreTmpMeta(&me); restoreTmpMeta(&me);
if (me.name.isEmpty()) continue; if (me.name.isEmpty()) continue;
if (me.name.contains("[")) if (me.name.contains('['))
crepl = me.name.takeMid(me.name.find("["), me.name.findLast("]") - me.name.find("[") + 1); crepl = me.name.takeMid(me.name.find('['), me.name.findLast(']') - me.name.find('[') + 1);
while (!me.name.isEmpty()) { while (!me.name.isEmpty()) {
if (me.name.front() == "*" || me.name.front() == "&") { if (me.name.front() == PIChar('*') || me.name.front() == PIChar('&')) {
me.type += me.name.takeLeft(1); me.type += me.name.takeLeft(1);
me.name.trim(); me.name.trim();
} else break; } else break;
} }
me.is_type_ptr = (me.type.right(1) == "]" || me.type.right(1) == "*"); me.is_type_ptr = (me.type.right(1) == PIChar(']') || me.type.right(1) == PIChar('*'));
me.type += crepl; me.type += crepl;
me.bits = bits; me.bits = bits;
while (!crepl.isEmpty()) { while (!crepl.isEmpty()) {
@@ -664,7 +688,7 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
int PICodeParser::extractMemberBits(PIString & fc) { int PICodeParser::extractMemberBits(PIString & fc) {
int i = fc.findLast(":"); int i = fc.findLast(':');
if (i <= 0) return -1; if (i <= 0) return -1;
if (fc[i - 1].toAscii() == ':') return -1; if (fc[i - 1].toAscii() == ':') return -1;
PIString bs = fc.takeMid(i).mid(1).trim(); PIString bs = fc.takeMid(i).mid(1).trim();
@@ -674,6 +698,14 @@ int PICodeParser::extractMemberBits(PIString & fc) {
void PICodeParser::normalizeEntityNamespace(PIString & n) { void PICodeParser::normalizeEntityNamespace(PIString & n) {
static const PIString s_const_s = PIStringAscii("const ");
static const PIString s_static_s = PIStringAscii("static ");
static const PIString s_mutable_s = PIStringAscii("mutable ");
static const PIString s_volatile_s = PIStringAscii("volatile ");
static const PIString s_s_const_s = PIStringAscii(" const ");
static const PIString s_s_static_s = PIStringAscii(" static ");
static const PIString s_s_mutable_s = PIStringAscii(" mutable ");
static const PIString s_s_volatile_s = PIStringAscii(" volatile ");
PIString suff, pref; PIString suff, pref;
for (int i = n.size_s() - 1; i > 0; --i) for (int i = n.size_s() - 1; i > 0; --i)
if (_isCChar(n[i]) || n[i].isDigit()) { if (_isCChar(n[i]) || n[i].isDigit()) {
@@ -681,11 +713,11 @@ void PICodeParser::normalizeEntityNamespace(PIString & n) {
n.cutRight(suff.size_s()); n.cutRight(suff.size_s());
break; break;
} }
n.push_front(" "); n.push_front(' ');
if (n.find(" static ") >= 0) {n.replaceAll(" static ", ""); pref += "static ";} if (n.find(s_s_const_s) >= 0) {n.replaceAll(s_s_const_s, ""); pref += s_const_s;}
if (n.find(" const ") >= 0) {n.replaceAll(" const ", ""); pref += "const ";} if (n.find(s_s_static_s) >= 0) {n.replaceAll(s_s_static_s, ""); pref += s_static_s;}
if (n.find(" mutable ") >= 0) {n.replaceAll(" mutable ", ""); pref += "mutable ";} if (n.find(s_s_mutable_s) >= 0) {n.replaceAll(s_s_mutable_s, ""); pref += s_mutable_s;}
if (n.find(" volatile ") >= 0) {n.replaceAll(" volatile ", ""); pref += "volatile ";} if (n.find(s_s_volatile_s) >= 0) {n.replaceAll(s_s_volatile_s, ""); pref += s_volatile_s;}
n.trim(); n.trim();
int f = 0; int f = 0;
piForeachC (Entity * e, entities) { piForeachC (Entity * e, entities) {
@@ -694,27 +726,29 @@ void PICodeParser::normalizeEntityNamespace(PIString & n) {
return; return;
} }
if ((f = e->name.find(n)) >= 0) if ((f = e->name.find(n)) >= 0)
if (e->name.mid(f - 1, 1) == ":") if (e->name.at(f - 1) == PIChar(':'))
if (e->name.find(cur_namespace) >= 0) { if (e->name.find(cur_namespace) >= 0) {
n = pref + e->name + suff; n = pref + e->name + suff;
return; return;
} }
} }
piForeachC (Enum & e, enums) piForeachC (Enum & e, enums) {
if ((f = e.name.find(n)) >= 0) if ((f = e.name.find(n)) >= 0)
if (e.name.mid(f - 1, 1) == ":") if (e.name.at(f - 1) == PIChar(':'))
if (e.name.find(cur_namespace) >= 0) { if (e.name.find(cur_namespace) >= 0) {
//piCout << "change" << n << "to" << e.name + suff; //piCout << "change" << n << "to" << e.name + suff;
n = pref + e.name + suff; n = pref + e.name + suff;
return; return;
}
} }
piForeachC (Typedef & e, typedefs) piForeachC (Typedef & e, typedefs) {
if ((f = e.first.find(n)) >= 0) if ((f = e.first.find(n)) >= 0)
if (e.first.mid(f - 1, 1) == ":") if (e.first.at(f - 1) == PIChar(':'))
if (e.first.find(cur_namespace) >= 0) { if (e.first.find(cur_namespace) >= 0) {
//piCout << "change" << n << "to" << e.name + suff; //piCout << "change" << n << "to" << e.name + suff;
n = pref + e.first + suff; n = pref + e.first + suff;
return; return;
}
} }
n = (pref + n + suff).trim(); n = (pref + n + suff).trim();
} }
@@ -723,20 +757,20 @@ void PICodeParser::normalizeEntityNamespace(PIString & n) {
void PICodeParser::restoreTmpTemp(Member * e) { void PICodeParser::restoreTmpTemp(Member * e) {
int i = 0; int i = 0;
piForeach (PIString & a, e->arguments_full) { piForeach (PIString & a, e->arguments_full) {
while ((i = a.find("$T")) >= 0) while ((i = a.find(PIStringAscii("$T"))) >= 0)
a.replace(i, 5, tmp_temp[a.mid(i, 5)]); a.replace(i, 5, tmp_temp[a.mid(i, 5)]);
} }
piForeach (PIString & a, e->arguments_type) { piForeach (PIString & a, e->arguments_type) {
while ((i = a.find("$T")) >= 0) while ((i = a.find(PIStringAscii("$T"))) >= 0)
a.replace(i, 5, tmp_temp[a.mid(i, 5)]); a.replace(i, 5, tmp_temp[a.mid(i, 5)]);
} }
while ((i = e->type.find("$T")) >= 0) while ((i = e->type.find(PIStringAscii("$T"))) >= 0)
e->type.replace(i, 5, tmp_temp[e->type.mid(i, 5)]); e->type.replace(i, 5, tmp_temp[e->type.mid(i, 5)]);
} }
void PICodeParser::restoreTmpMeta(PICodeParser::Member * e) { void PICodeParser::restoreTmpMeta(PICodeParser::Member * e) {
int i = e->name.find("$M"); int i = e->name.find(PIStringAscii("$M"));
if (i < 0) return; if (i < 0) return;
e->meta = tmp_meta[e->name.takeMid(i, 5)]; e->meta = tmp_meta[e->name.takeMid(i, 5)];
} }
@@ -744,7 +778,7 @@ void PICodeParser::restoreTmpMeta(PICodeParser::Member * e) {
PICodeParser::MetaMap PICodeParser::maybeMeta(PIString & fc) { PICodeParser::MetaMap PICodeParser::maybeMeta(PIString & fc) {
PICodeParser::MetaMap ret; PICodeParser::MetaMap ret;
if (fc.left(2) == "$M") { if (fc.left(2) == PIStringAscii("$M")) {
ret = tmp_meta.value(fc.takeLeft(5)); ret = tmp_meta.value(fc.takeLeft(5));
fc.trim(); fc.trim();
} }
@@ -754,10 +788,10 @@ PICodeParser::MetaMap PICodeParser::maybeMeta(PIString & fc) {
bool PICodeParser::macroCondition(const PIString & mif, PIString mifcond) { bool PICodeParser::macroCondition(const PIString & mif, PIString mifcond) {
//piCout << "macroCondition" << mif << mifcond; //piCout << "macroCondition" << mif << mifcond;
if (mif == "ifdef") return isDefineExists(mifcond); if (mif == PIStringAscii("ifdef")) return isDefineExists(mifcond);
if (mif == "ifndef") return !isDefineExists(mifcond); if (mif == PIStringAscii("ifndef")) return !isDefineExists(mifcond);
if (mif == "if" || mif == "elif") { if (mif == PIStringAscii("if") || mif == PIStringAscii("elif")) {
mifcond.removeAll(" ").removeAll("\t"); mifcond.removeAll(' ').removeAll('\t');
return procMacrosCond(mifcond) > 0.; return procMacrosCond(mifcond) > 0.;
} }
return false; return false;
@@ -770,7 +804,7 @@ double PICodeParser::procMacrosCond(PIString fc) {
int oper = 0, ps = -1; int oper = 0, ps = -1;
char cc, nc; char cc, nc;
PIString ce; PIString ce;
fc.removeAll("defined"); fc.removeAll(PIStringAscii("defined"));
//piCout << "procMacrosCond" << fc; //piCout << "procMacrosCond" << fc;
while (!fc.isEmpty()) { while (!fc.isEmpty()) {
cc = fc[0].toAscii(); cc = fc[0].toAscii();
@@ -825,17 +859,17 @@ double PICodeParser::defineValue(const PIString & dn) {
void PICodeParser::replaceMeta(PIString & dn) { void PICodeParser::replaceMeta(PIString & dn) {
tmp_meta.clear(); tmp_meta.clear();
if (dn.isEmpty()) return; if (dn.isEmpty()) return;
int s = dn.find("PIMETA"); int s = dn.find(PIStringAscii("PIMETA"));
while (s >= 0) { while (s >= 0) {
int ms = 0, ml = 0; int ms = 0, ml = 0;
ms = dn.findRange('(', ')', '\\', s + 6, &ml); ms = dn.findRange('(', ')', '\\', s + 6, &ml);
if (ms < 0) return; if (ms < 0) return;
PIString meta = dn.mid(ms, ml).trim(); PIString meta = dn.mid(ms, ml).trim();
PIString rm = "$M" + PIString::fromNumber(tmp_meta.size_s()).expandLeftTo(3, "0"); PIString rm = PIStringAscii("$M") + PIString::fromNumber(tmp_meta.size_s()).expandLeftTo(3, '0');
dn.replace(s, ms + ml + 1 - s, rm); dn.replace(s, ms + ml + 1 - s, rm);
//piCout << "FOUND META \"" << meta << "\""; //piCout << "FOUND META \"" << meta << '\"';
tmp_meta[rm] = parseMeta(meta); tmp_meta[rm] = parseMeta(meta);
s = dn.find("PIMETA"); s = dn.find(PIStringAscii("PIMETA"));
} }
} }
@@ -849,7 +883,7 @@ PICodeParser::Entity * PICodeParser::findEntityByName(const PIString & en) {
bool PICodeParser::isDeclaration(const PIString & fc, int start, int * end) { bool PICodeParser::isDeclaration(const PIString & fc, int start, int * end) {
int dind = fc.find("{", start), find = fc.find(";", start); int dind = fc.find('{', start), find = fc.find(';', start);
//piCout << "isDeclaration" << dind << find << fc.left(10); //piCout << "isDeclaration" << dind << find << fc.left(10);
if (dind < 0 && find < 0) {if (end) *end = -1; return true;} if (dind < 0 && find < 0) {if (end) *end = -1; return true;}
if (dind < 0 || find < dind) {if (end) *end = find; return true;} if (dind < 0 || find < dind) {if (end) *end = find; return true;}
@@ -861,17 +895,17 @@ bool PICodeParser::isDeclaration(const PIString & fc, int start, int * end) {
bool PICodeParser::isMainFile(const PIString & fc) { bool PICodeParser::isMainFile(const PIString & fc) {
int si = 0; int si = 0;
while (si >= 0) { while (si >= 0) {
int csi = fc.find(" main", si); int csi = fc.find(PIStringAscii(" main"), si);
if (csi < 0) csi = fc.find("\tmain", si); if (csi < 0) csi = fc.find(PIStringAscii("\tmain"), si);
if (csi < 0) csi = fc.find("\nmain", si); if (csi < 0) csi = fc.find(PIStringAscii("\nmain"), si);
if (csi < 0) return false; if (csi < 0) return false;
si = csi; si = csi;
int fi = fc.find("(", si + 5); int fi = fc.find('(', si + 5);
if (fi < 0) return false; if (fi < 0) return false;
if (fi - si < 10) { if (fi - si < 10) {
PIString ms(fc.mid(si, fi - si + 1)); PIString ms(fc.mid(si, fi - si + 1));
ms.removeAll(" ").removeAll("\t").removeAll("\n"); ms.removeAll(' ').removeAll('\t').removeAll('\n');
if (ms == "main(") return true; if (ms == PIStringAscii("main(")) return true;
} }
si += 5; si += 5;
} }
@@ -885,17 +919,17 @@ PIString PICodeParser::procMacros(PIString fc) {
bool grab = false, skip = false, cond_ok = false; bool grab = false, skip = false, cond_ok = false;
PIString pfc, nfc, line, mif, mifcond; PIString pfc, nfc, line, mif, mifcond;
//piCout << "procMacros\n<******" << fc << "\n******>"; //piCout << "procMacros\n<******" << fc << "\n******>";
fc += "\n"; fc += '\n';
while (!fc.isEmpty()) { while (!fc.isEmpty()) {
line = fc.takeLine().trimmed(); line = fc.takeLine().trimmed();
if (line.left(1) == "#") { if (line.left(1) == PIChar('#')) {
mifcond = line.mid(1); mifcond = line.mid(1);
mif = mifcond.takeCWord(); mif = mifcond.takeCWord();
//piCout << mif; //piCout << mif;
//piCout << "mif mifcond" << mif << mifcond << ifcnt; //piCout << "mif mifcond" << mif << mifcond << ifcnt;
if (skip || grab) { if (skip || grab) {
if (mif.left(2) == "if") ifcnt++; if (mif.left(2) == PIStringAscii("if")) ifcnt++;
if (mif.left(5) == "endif") { if (mif.left(5) == PIStringAscii("endif")) {
if (ifcnt > 0) ifcnt--; if (ifcnt > 0) ifcnt--;
else { else {
//piCout << "main endif" << skip << grab; //piCout << "main endif" << skip << grab;
@@ -904,7 +938,7 @@ PIString PICodeParser::procMacros(PIString fc) {
continue; continue;
} }
} }
if (mif.left(4) == "elif" && ifcnt == 0) { if (mif.left(4) == PIStringAscii("elif") && ifcnt == 0) {
//piCout << "main elif" << skip << grab << cond_ok; //piCout << "main elif" << skip << grab << cond_ok;
if (cond_ok) { if (cond_ok) {
if (grab) { if (grab) {
@@ -922,17 +956,17 @@ PIString PICodeParser::procMacros(PIString fc) {
} }
continue; continue;
} }
if (mif.left(4) == "else" && ifcnt == 0) { if (mif.left(4) == PIStringAscii("else") && ifcnt == 0) {
//piCout << "main else" << skip << grab; //piCout << "main else" << skip << grab;
if (grab) pfc << procMacros(nfc); if (grab) pfc << procMacros(nfc);
if (skip && !cond_ok) {skip = false; grab = true;} if (skip && !cond_ok) {skip = false; grab = true;}
else {skip = true; grab = false;} else {skip = true; grab = false;}
continue; continue;
} }
if (grab) nfc << line << "\n"; if (grab) nfc << line << '\n';
continue; continue;
} }
if (mif.left(2) == "if") { if (mif.left(2) == PIStringAscii("if")) {
//piCout << "main if"; //piCout << "main if";
skip = grab = cond_ok = false; skip = grab = cond_ok = false;
if (macroCondition(mif, mifcond.trimmed())) grab = cond_ok = true; if (macroCondition(mif, mifcond.trimmed())) grab = cond_ok = true;
@@ -944,8 +978,8 @@ PIString PICodeParser::procMacros(PIString fc) {
//return false; /// WARNING: now skip errors //return false; /// WARNING: now skip errors
} }
} else { } else {
if (grab) nfc << line << "\n"; if (grab) nfc << line << '\n';
else if (!skip) pfc << line << "\n"; else if (!skip) pfc << line << '\n';
} }
} }
return pfc; return pfc;
@@ -956,21 +990,21 @@ bool PICodeParser::parseDirective(PIString d) {
if (d.isEmpty()) return true; if (d.isEmpty()) return true;
PIString dname = d.takeCWord(); PIString dname = d.takeCWord();
//piCout << "parseDirective" << d; //piCout << "parseDirective" << d;
if (dname == "include") { if (dname == PIStringAscii("include")) {
d.replaceAll("<", "\"").replaceAll(">", "\""); d.replaceAll('<', '\"').replaceAll('>', '\"');
PIString cf = cur_file, ifc = d.takeRange("\"", "\""); PIString cf = cur_file, ifc = d.takeRange('\"', '\"');
if (with_includes) { if (with_includes) {
bool ret = parseFileInternal(ifc, with_includes); bool ret = parseFileInternal(ifc, with_includes);
cur_file = cf; cur_file = cf;
return ret; return ret;
} }
} }
if (dname == "define") { if (dname == PIStringAscii("define")) {
PIString mname = d.takeCWord(); PIString mname = d.takeCWord();
//piCout << mname; //piCout << mname;
if (mname == "PIMETA") return true; if (mname == PIStringAscii("PIMETA")) return true;
if (d.left(1) == "(") { // macro if (d.left(1) == PIChar('(')) { // macro
PIStringList args = d.takeRange("(", ")").split(",").trim(); PIStringList args = d.takeRange('(', ')').split(',').trim();
macros << Macro(mname, d.trim(), args); macros << Macro(mname, d.trim(), args);
} else { // define } else { // define
d.trim(); d.trim();
@@ -979,7 +1013,7 @@ bool PICodeParser::parseDirective(PIString d) {
} }
return true; return true;
} }
if (dname == "undef") { if (dname == PIStringAscii("undef")) {
PIString mname = d.takeCWord(); PIString mname = d.takeCWord();
for (int i = 0; i < defines.size_s(); ++i) for (int i = 0; i < defines.size_s(); ++i)
if (defines[i].first == mname) {defines.remove(i); --i;} if (defines[i].first == mname) {defines.remove(i); --i;}

View File

@@ -33,8 +33,8 @@ class PIP_EXPORT PICodeParser {
public: public:
PICodeParser(); PICodeParser();
enum PIP_EXPORT Visibility {Global, Public, Protected, Private}; enum Visibility {Global, Public, Protected, Private};
enum PIP_EXPORT Attribute { enum Attribute {
NoAttributes = 0x0, NoAttributes = 0x0,
Const = 0x01, Const = 0x01,
Static = 0x02, Static = 0x02,

View File

@@ -23,10 +23,11 @@
#ifndef PICOMPRESS_H #ifndef PICOMPRESS_H
#define PICOMPRESS_H #define PICOMPRESS_H
#include "pip_compress_export.h"
#include "pibytearray.h" #include "pibytearray.h"
PIByteArray piCompress(const PIByteArray & ba, int level = 6); PIP_COMPRESS_EXPORT PIByteArray piCompress(const PIByteArray & ba, int level = 6);
PIByteArray piDecompress(const PIByteArray & zba); PIP_COMPRESS_EXPORT PIByteArray piDecompress(const PIByteArray & zba);
#endif // PICOMPRESS_H #endif // PICOMPRESS_H

View File

@@ -1,64 +0,0 @@
/*
PIP - Platform Independent Primitives
Stephan Fomenko
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIP_TESTS_EXECUTOR_H
#define PIP_TESTS_EXECUTOR_H
#include "piblockingdequeue.h"
#include <atomic>
/**
* @brief Thread pools address two different problems: they usually provide improved performance when executing large
* numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and
* managing the resources, including threads, consumed when executing a collection of tasks.
*/
class PIThreadPoolExecutor {
public:
explicit PIThreadPoolExecutor(size_t corePoolSize = 1, PIBlockingDequeue<std::function<void()> >* taskQueue_ = new PIBlockingDequeue<std::function<void()> >());
virtual ~PIThreadPoolExecutor();
/**
* @brief Executes the given task sometime in the future. The task execute in an existing pooled thread. If the task
* cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been
* reached.
*
* @param runnable not empty function for thread pool execution
*/
void execute(const std::function<void()>& runnable);
void shutdownNow();
/**
* @brief Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be
* accepted. Invocation has no additional effect if already shut down. This method does not wait for previously
* submitted tasks to complete execution. Use awaitTermination to do that.
*/
void shutdown();
bool isShutdown() const;
bool awaitTermination(int timeoutMs);
private:
std::atomic_bool isShutdown_;
PIBlockingDequeue<std::function<void()> >* taskQueue;
PIVector<PIThread*> threadPool;
};
#endif //PIP_TESTS_EXECUTOR_H

View File

@@ -1,51 +0,0 @@
/*
PIP - Platform Independent Primitives
Stephan Fomenko
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PICONDITIONLOCK_H
#define PICONDITIONLOCK_H
#include "pibase.h"
/**
* @brief Continued
*/
class PIP_EXPORT PIConditionLock {
public:
NO_COPY_CLASS(PIConditionLock)
explicit PIConditionLock();
~PIConditionLock();
//! \brief lock
void lock();
//! \brief unlock
void unlock();
//! \brief tryLock
bool tryLock();
void * handle();
private:
PRIVATE_DECLARATION
};
#endif // PICONDITIONLOCK_H

View File

@@ -1,461 +0,0 @@
/*! \file piconsole.h
* \brief Console output class
*/
/*
PIP - Platform Independent Primitives
Console output/input
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PICONSOLE_H
#define PICONSOLE_H
#include "pikbdlistener.h"
class PIProtocol;
class PIDiagnostics;
class PISystemMonitor;
class PIPeer;
class PITimer;
class PIP_EXPORT PIConsole: public PIThread
{
PIOBJECT_SUBCLASS(PIConsole, PIThread)
public:
//! Constructs %PIConsole with key handler "slot" and if "startNow" start it
explicit PIConsole(bool startNow = true, PIKbdListener::KBFunc slot = 0);
~PIConsole();
//! Variables output format
enum Format {
Normal /** Default console format */ = 0x01,
Bold /** Bold text */ = 0x02,
Faint = 0x04,
Italic = 0x08,
Underline /** Underlined text */ = 0x10,
Blink /** Blinked text */ = 0x20,
Inverse /** Swap text and background colors */ = 0x40,
Black /** Black text */ = 0x100,
Red /** Red text */ = 0x200,
Green /** Green text */ = 0x400,
Yellow /** Yellow text */ = 0x800,
Blue /** Blue text */ = 0x1000,
Magenta /** Magenta text */ = 0x2000,
Cyan /** Cyan text */ = 0x4000,
White /** White text */ = 0x8000,
BackBlack /** Black background */ = 0x10000,
BackRed /** Red background */ = 0x20000,
BackGreen /** Green background */ = 0x40000,
BackYellow /** Yellow background */ = 0x80000,
BackBlue /** Blue background */ = 0x100000,
BackMagenta /** Magenta background */ = 0x200000,
BackCyan /** Cyan background */ = 0x400000,
BackWhite /** White background */ = 0x800000,
Dec /** Decimal base for integers */ = 0x1000000,
Hex /** Hexadecimal base for integers */ = 0x2000000,
Oct /** Octal base for integers */ = 0x4000000,
Bin /** Binary base for integers */ = 0x8000000,
Scientific /** Scientific representation of floats */ = 0x10000000,
SystemTimeSplit /** PISystemTime split representation (* s, * ns) */ = 0x20000000,
SystemTimeSeconds /** PISystemTime seconds representation (*.* s) */ = 0x40000000
};
//! Column labels alignment
enum Alignment {
Nothing /** No alignment */ ,
Left /** Labels align left and variables align left */ ,
Right /** Labels align right and variables align left */
};
typedef PIFlags<PIConsole::Format> FormatFlags;
//! Add to current tab to column "column" string "name" with format "format"
void addString(const PIString & name, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const PIString * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const char * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const bool * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const short * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const int * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const long * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const llong * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const uchar * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const ushort * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const uint * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const ulong * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const ullong * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const float * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const double * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const PISystemTime * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
void addVariable(const PIString & name, const PIDiagnostics * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
void addVariable(const PIString & name, const PISystemMonitor * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" bits field with label "name", pointer "ptr" and format "format"
void addBitVariable(const PIString & name, const void * ptr, int fromBit, int bitsCount, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" "count" empty lines
void addEmptyLine(int column = 1, uint count = 1);
PIString getString(int x, int y);
short getShort(int x, int y) {return getString(x, y).toShort();}
int getInt(int x, int y) {return getString(x, y).toInt();}
float getFloat(int x, int y) {return getString(x, y).toFloat();}
double getDouble(int x, int y) {return getString(x, y).toDouble();}
PIString getString(const PIString & name);
short getShort(const PIString & name) {return getString(name).toShort();}
int getInt(const PIString & name) {return getString(name).toInt();}
float getFloat(const PIString & name) {return getString(name).toFloat();}
double getDouble(const PIString & name) {return getString(name).toDouble();}
//! Returns tabs count
uint tabsCount() const {return tabs.size();}
//! Returns current tab name
PIString currentTab() const {return tabs[cur_tab].name;}
//! Returns current tab index
int currentTabIndex() const {return cur_tab;}
//! Add new tab with name "name", bind key "bind_key" and returns this tab index
int addTab(const PIString & name, char bind_key = 0);
//! Remove tab with index "index"
void removeTab(uint index);
//! Remove tab with name "name"
void removeTab(const PIString & name);
//! Clear content of tab with index "index"
void clearTab(uint index);
//! Clear content of tab with name "name"
void clearTab(const PIString & name);
//! Set current tab to tab with index "index", returns if tab exists
bool setTab(uint index);
//! Set current tab to tab with name "name", returns if tab exists
bool setTab(const PIString & name);
//! Set tab with index "index" bind key to "bind_key", returns if tab exists
bool setTabBindKey(uint index, char bind_key);
//! Set tab with name "name" bind key to "bind_key", returns if tab exists
bool setTabBindKey(const PIString & name, char bind_key);
//! Remove all tabs and if "clearScreen" clear the screen
void clearTabs(bool clearScreen = true) {if (clearScreen && isRunning()) {toUpperLeft(); clearScreenLower();} tabs.clear();}
//! Set custom status text of current tab to "str"
void addCustomStatus(const PIString & str) {tabs[cur_tab].status = str;}
//! Clear custom status text of current tab
void clearCustomStatus() {tabs[cur_tab].status.clear();}
//! Returns default alignment
Alignment defaultAlignment() const {return def_align;}
//! Set default alignment to "align"
void setDefaultAlignment(Alignment align) {def_align = align;}
//! Set column "col" alignment to "align"
void setColumnAlignment(int col, Alignment align) {if (col < 0 || col >= columns().size_s()) return; column(col).alignment = align;}
//! Set all columns of all tabs alignment to "align"
void setColumnAlignmentToAll(Alignment align) {piForeach (Tab & i, tabs) piForeach (Column & j, i.columns) j.alignment = align; fillLabels();}
//! Directly call function from \a PIKbdListener
void enableExitCapture(char key = 'Q') {listener->enableExitCapture(key);}
//! Directly call function from \a PIKbdListener
void disableExitCapture() {listener->disableExitCapture();}
//! Directly call function from \a PIKbdListener
bool exitCaptured() const {return listener->exitCaptured();}
//! Directly call function from \a PIKbdListener
char exitKey() const {return listener->exitKey();}
int windowWidth() const {return width;}
int windowHeight() const {return height;}
PIString fstr(FormatFlags f);
void update();
void pause(bool yes) {pause_ = yes;}
// Server functions
void startServer(const PIString & name);
void stopPeer();
bool isServerStarted() const {return peer != 0;}
PIStringList clients() const;
// Client functions
void listenServers();
PIStringList availableServers() const;
PIString selectedServer() const {return server_name;}
void connectToServer(const PIString & name);
void disconnect();
bool isConnected() const {return state == Connected;}
void toUpperLeft();
void moveRight(int n = 1);
void moveLeft(int n = 1);
void moveTo(int x = 0, int y = 0);
void clearScreen();
void clearScreenLower();
void clearLine();
void newLine();
void hideCursor();
void showCursor();
EVENT_HANDLER0(void, clearVariables) {clearVariables(true);}
EVENT_HANDLER1(void, clearVariables, bool, clearScreen);
EVENT_HANDLER0(void, waitForFinish) {WAIT_FOR_EXIT}
EVENT_HANDLER0(void, start) {start(false);}
EVENT_HANDLER1(void, start, bool, wait) {PIThread::start(40); if (wait) waitForFinish();}
EVENT_HANDLER0(void, stop) {stop(false);}
EVENT_HANDLER1(void, stop, bool, clear);
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void * , data)
//! \handlers
//! \{
//! \fn void waitForFinish()
//! \brief block until finished (exit key will be pressed)
//! \fn void clearVariables(bool clearScreen = true)
//! \brief Remove all columns at current tab and if "clearScreen" clear the screen
//! \fn void start(bool wait = false)
//! \brief Start console output and if "wait" block until finished (exit key will be pressed)
//! \fn void stop(bool clear = false)
//! \brief Stop console output and if "clear" clear the screen
//! \}
//! \events
//! \{
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
//! \brief Raise on key "key" pressed, "data" is pointer to %PIConsole object
//! \}
private:
void begin();
void run();
void fillLabels();
void status();
void checkColumn(uint col) {while (columns().size() < col) columns().push_back(Column(def_align));}
int bitsValue(const void * src, int offset, int count) const;
const char * toBin(const void * d, int s);
inline void printLine(const PIString & str, int dx = 0, FormatFlags format = PIConsole::Normal);
inline int printValue(const PIString & str, FormatFlags format = PIConsole::Normal);
inline int printValue(const char * str, FormatFlags format = PIConsole::Normal);
inline int printValue(const bool value, FormatFlags format = PIConsole::Normal);
inline int printValue(const int value, FormatFlags format = PIConsole::Normal);
inline int printValue(const long value, FormatFlags format = PIConsole::Normal);
inline int printValue(const llong value, FormatFlags format = PIConsole::Normal);
inline int printValue(const float value, FormatFlags format = PIConsole::Normal);
inline int printValue(const double value, FormatFlags format = PIConsole::Normal);
inline int printValue(const char value, FormatFlags format = PIConsole::Normal);
inline int printValue(const short value, FormatFlags format = PIConsole::Normal);
inline int printValue(const uchar value, FormatFlags format = PIConsole::Normal);
inline int printValue(const ushort value, FormatFlags format = PIConsole::Normal);
inline int printValue(const uint value, FormatFlags format = PIConsole::Normal);
inline int printValue(const ulong value, FormatFlags format = PIConsole::Normal);
inline int printValue(const ullong value, FormatFlags format = PIConsole::Normal);
inline int printValue(const PISystemTime & value, FormatFlags format = PIConsole::Normal);
static void key_event(PIKbdListener::KeyEvent key, void * t);
struct Variable {
Variable() {nx = ny = type = offset = bitFrom = bitCount = size = 0; format = Normal; remote = false; ptr = 0; id = 1;}
Variable(const Variable & src) {remote = src.remote; name = src.name; format = src.format; type = src.type; offset = src.offset; size = src.size;
bitFrom = src.bitFrom; bitCount = src.bitCount; ptr = src.ptr; nx = src.nx; ny = src.ny; rdata = src.rdata; id = src.id;}
bool isEmpty() const {return (remote ? false : ptr == 0);}
const void * data() {return (remote ? rdata.data() : ptr);}
void writeData(PIByteArray & ba) {
if (remote) ba << rdata;
else {
if (type == 0) ba << (*(PIString * )ptr);
else ba << PIByteArray::RawData(ptr, size);
}
}
PIString name;
FormatFlags format;
int nx;
int ny;
int type;
int offset;
int bitFrom;
int bitCount;
int size;
int id;
bool remote;
const void * ptr;
PIByteArray rdata;
void operator =(const Variable & src) {remote = src.remote; name = src.name; format = src.format; type = src.type; offset = src.offset; size = src.size;
bitFrom = src.bitFrom; bitCount = src.bitCount; ptr = src.ptr; nx = src.nx; ny = src.ny; rdata = src.rdata; id = src.id;}
};
struct VariableContent {
int id;
PIByteArray rdata;
};
struct Column {
Column(Alignment align = PIConsole::Right) {variables.reserve(32); alignment = align;}
PIVector<Variable> variables;
Alignment alignment;
uint size() const {return variables.size();}
Variable & operator [](int index) {return variables[index];}
const Variable & operator [](int index) const {return variables[index];}
void push_back(const Variable & v) {variables.push_back(v);}
void operator =(const Column & src) {variables = src.variables; alignment = src.alignment;}
};
struct Tab {
Tab(PIString n = "", char k = 0) {columns.reserve(8); name = n; key = k;}
PIVector<Column> columns;
PIString name;
PIString status;
char key;
};
enum ConnectedState {Disconnected, FetchingData, Committing, Connected};
friend PIByteArray & operator <<(PIByteArray & ba, const PIConsole::VariableContent & v);
friend PIByteArray & operator >>(PIByteArray & ba, PIConsole::VariableContent & v);
friend PIByteArray & operator <<(PIByteArray & ba, const PIConsole::Variable & v);
friend PIByteArray & operator >>(PIByteArray & ba, PIConsole::Variable & v);
friend PIByteArray & operator <<(PIByteArray & ba, const PIConsole::Column & v);
friend PIByteArray & operator >>(PIByteArray & ba, PIConsole::Column & v);
friend PIByteArray & operator <<(PIByteArray & ba, const PIConsole::Tab & v);
friend PIByteArray & operator >>(PIByteArray & ba, PIConsole::Tab & v);
PIVector<Column> & columns() {return tabs[cur_tab].columns;}
Column & column(int index) {return tabs[cur_tab].columns[index - 1];}
int couts(const PIString & v);
int couts(const char * v);
int couts(const bool v);
int couts(const char v);
int couts(const short v);
int couts(const int v);
int couts(const long v);
int couts(const llong v);
int couts(const uchar v);
int couts(const ushort v);
int couts(const uint v);
int couts(const ulong v);
int couts(const ullong v);
int couts(const float v);
int couts(const double v);
int couts(const PISystemTime & v);
struct RemoteClient;
void serverSendInfo();
void serverSendData();
RemoteClient & remoteClient(const PIString & fname);
EVENT_HANDLER2(void, peerReceived, const PIString &, from, const PIByteArray &, data);
EVENT_HANDLER2(void, peerTimer, void * , data, int, delim);
EVENT_HANDLER1(void, peerDisconnectedEvent, const PIString &, name);
PRIVATE_DECLARATION
PIVector<Tab> tabs;
PIString binstr, rstr;
PIByteArray rba;
Variable tv;
PIKbdListener * listener;
Alignment def_align;
PIKbdListener::KBFunc ret_func;
int width, height, pwidth, pheight, col_wid, num_format, systime_format;
uint max_y;
int vid;
uint cur_tab, col_cnt;
PIPeer * peer;
PITimer * peer_timer;
PITimeMeasurer peer_tm;
PIString server_name;
bool server_mode, pause_;
ConnectedState state;
struct RemoteClient {
RemoteClient(const PIString & n = "") {name = n; state = Disconnected;}
PIString name;
ConnectedState state;
};
PIVector<RemoteClient> remote_clients;
};
inline PIByteArray & operator <<(PIByteArray & ba, const PIConsole::VariableContent & v) {ba << v.id << v.rdata; return ba;}
inline PIByteArray & operator >>(PIByteArray & ba, PIConsole::VariableContent & v) {ba >> v.id; ba >> v.rdata; return ba;}
inline PIByteArray & operator <<(PIByteArray & ba, const PIConsole::Variable & v) {ba << v.name << v.id << (int)v.format << v.type << v.size << v.bitFrom << v.bitCount; return ba;}
inline PIByteArray & operator >>(PIByteArray & ba, PIConsole::Variable & v) {ba >> v.name >> v.id >> (int & )v.format >> v.type >> v.size >> v.bitFrom >> v.bitCount; return ba;}
inline PIByteArray & operator <<(PIByteArray & ba, const PIConsole::Column & v) {ba << (int)v.alignment << v.variables; return ba;}
inline PIByteArray & operator >>(PIByteArray & ba, PIConsole::Column & v) {int a; ba >> a >> v.variables; v.alignment = (PIConsole::Alignment)a; return ba;}
inline PIByteArray & operator <<(PIByteArray & ba, const PIConsole::Tab & v) {ba << v.name << v.status << (uchar)v.key << v.columns; return ba;}
inline PIByteArray & operator >>(PIByteArray & ba, PIConsole::Tab & v) {ba >> v.name >> v.status >> (uchar&)v.key >> v.columns; return ba;}
#endif // PICONSOLE_H

View File

@@ -21,7 +21,6 @@
#define PICONSOLEMODULE_H #define PICONSOLEMODULE_H
#include "pikbdlistener.h" #include "pikbdlistener.h"
#include "piconsole.h"
#include "piscreen.h" #include "piscreen.h"
#include "piscreentiles.h" #include "piscreentiles.h"

View File

@@ -77,7 +77,7 @@ public:
typedef PIFlags<KeyModifier> KeyModifiers; typedef PIFlags<KeyModifier> KeyModifiers;
//! This struct contains information about pressed keyboard key //! This struct contains information about pressed keyboard key
struct KeyEvent { struct PIP_EXPORT KeyEvent {
KeyEvent(int k = 0, KeyModifiers m = 0) {key = k; modifiers = m;} KeyEvent(int k = 0, KeyModifiers m = 0) {key = k; modifiers = m;}
//! Pressed key. It can be simple \b char or special key (see PIKbdListener::SpecialKey) //! Pressed key. It can be simple \b char or special key (see PIKbdListener::SpecialKey)
@@ -106,7 +106,7 @@ public:
typedef PIFlags<MouseButton> MouseButtons; typedef PIFlags<MouseButton> MouseButtons;
//! This struct contains information about mouse action //! This struct contains information about mouse action
struct MouseEvent { struct PIP_EXPORT MouseEvent {
MouseEvent(MouseAction a = MouseButtonPress, MouseButtons b = 0, KeyModifiers m = 0) {x = y = 0; action = a; buttons = b; modifiers = m;} MouseEvent(MouseAction a = MouseButtonPress, MouseButtons b = 0, KeyModifiers m = 0) {x = y = 0; action = a; buttons = b; modifiers = m;}
//! Event X coordinate in view-space, from 0 //! Event X coordinate in view-space, from 0
@@ -126,7 +126,7 @@ public:
}; };
//! This struct contains information about mouse wheel action //! This struct contains information about mouse wheel action
struct WheelEvent: public MouseEvent { struct PIP_EXPORT WheelEvent: public MouseEvent {
WheelEvent(): MouseEvent() {direction = false;} WheelEvent(): MouseEvent() {direction = false;}
//! Wheel direction, /b true - up, /b fasle - down //! Wheel direction, /b true - up, /b fasle - down
@@ -207,7 +207,7 @@ private:
void end(); void end();
#ifndef WINDOWS #ifndef WINDOWS
struct EscSeq { struct PIP_EXPORT EscSeq {
const char * seq; const char * seq;
int key; int key;
int mod; int mod;
@@ -228,7 +228,7 @@ private:
static const EscSeq esc_seq[]; static const EscSeq esc_seq[];
#endif #endif
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_EXPORT)
KBFunc ret_func; KBFunc ret_func;
int exit_key; int exit_key;
bool exit_enabled, is_active; bool exit_enabled, is_active;

View File

@@ -23,11 +23,12 @@
#ifndef PISCREEN_H #ifndef PISCREEN_H
#define PISCREEN_H #define PISCREEN_H
#include "pip_console_export.h"
#include "piscreentile.h" #include "piscreentile.h"
#include "piscreendrawer.h" #include "piscreendrawer.h"
class PIP_EXPORT PIScreen: public PIThread, public PIScreenTypes::PIScreenBase class PIP_CONSOLE_EXPORT PIScreen: public PIThread, public PIScreenTypes::PIScreenBase
{ {
PIOBJECT_SUBCLASS(PIScreen, PIThread) PIOBJECT_SUBCLASS(PIScreen, PIThread)
class SystemConsole; class SystemConsole;
@@ -100,7 +101,7 @@ public:
//! \} //! \}
private: private:
class SystemConsole { class PIP_CONSOLE_EXPORT SystemConsole {
public: public:
SystemConsole(); SystemConsole();
~SystemConsole(); ~SystemConsole();
@@ -124,7 +125,7 @@ private:
#else #else
PIString formatString(const PIScreenTypes::Cell & c); PIString formatString(const PIScreenTypes::Cell & c);
#endif #endif
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_CONSOLE_EXPORT)
int width, height, pwidth, pheight; int width, height, pwidth, pheight;
int mouse_x, mouse_y; int mouse_x, mouse_y;
PIVector<PIVector<PIScreenTypes::Cell> > cells, pcells; PIVector<PIVector<PIScreenTypes::Cell> > cells, pcells;

View File

@@ -25,16 +25,17 @@
#ifndef PISCREENCONSOLE_H #ifndef PISCREENCONSOLE_H
#define PISCREENCONSOLE_H #define PISCREENCONSOLE_H
#include "pip_console_export.h"
#include "piscreentiles.h" #include "piscreentiles.h"
/// NOTE: incomplete class /// NOTE: incomplete class
/// TODO: write TileVars /// TODO: write TileVars
class PIP_EXPORT TileVars: public PIScreenTile { class PIP_CONSOLE_EXPORT TileVars: public PIScreenTile {
public: public:
TileVars(const PIString & n = PIString()); TileVars(const PIString & n = PIString());
protected: protected:
struct Variable { struct PIP_CONSOLE_EXPORT Variable {
Variable() {nx = ny = type = offset = bitFrom = bitCount = size = 0; format = PIScreenTypes::CellFormat(); ptr = 0;} Variable() {nx = ny = type = offset = bitFrom = bitCount = size = 0; format = PIScreenTypes::CellFormat(); ptr = 0;}
bool isEmpty() const {return (ptr == 0);} bool isEmpty() const {return (ptr == 0);}
PIString name; PIString name;
@@ -68,7 +69,7 @@ protected:
class PIP_EXPORT PIScreenConsoleTile : public PIScreenTile class PIP_CONSOLE_EXPORT PIScreenConsoleTile : public PIScreenTile
{ {
public: public:
PIScreenConsoleTile(); PIScreenConsoleTile();

View File

@@ -23,10 +23,11 @@
#ifndef PISCREENDRAWER_H #ifndef PISCREENDRAWER_H
#define PISCREENDRAWER_H #define PISCREENDRAWER_H
#include "pip_console_export.h"
#include "piscreentypes.h" #include "piscreentypes.h"
#include "pistring.h" #include "pistring.h"
class PIP_EXPORT PIScreenDrawer class PIP_CONSOLE_EXPORT PIScreenDrawer
{ {
friend class PIScreen; friend class PIScreen;
PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell> > & c); PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell> > & c);

View File

@@ -23,12 +23,13 @@
#ifndef PISCREENTILE_H #ifndef PISCREENTILE_H
#define PISCREENTILE_H #define PISCREENTILE_H
#include "pip_console_export.h"
#include "piscreentypes.h" #include "piscreentypes.h"
#include "pikbdlistener.h" #include "pikbdlistener.h"
class PIScreenDrawer; class PIScreenDrawer;
class PIP_EXPORT PIScreenTile: public PIObject { class PIP_CONSOLE_EXPORT PIScreenTile: public PIObject {
friend class PIScreen; friend class PIScreen;
PIOBJECT_SUBCLASS(PIScreenTile, PIObject) PIOBJECT_SUBCLASS(PIScreenTile, PIObject)
public: public:

View File

@@ -23,10 +23,11 @@
#ifndef PISCREENTILES_H #ifndef PISCREENTILES_H
#define PISCREENTILES_H #define PISCREENTILES_H
#include "pip_console_export.h"
#include "piscreentile.h" #include "piscreentile.h"
class PIP_EXPORT TileSimple: public PIScreenTile { class PIP_CONSOLE_EXPORT TileSimple: public PIScreenTile {
PIOBJECT_SUBCLASS(TileSimple, PIScreenTile) PIOBJECT_SUBCLASS(TileSimple, PIScreenTile)
public: public:
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row; typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
@@ -43,7 +44,7 @@ protected:
class TileList; class TileList;
class PIP_EXPORT TileScrollBar: public PIScreenTile { class PIP_CONSOLE_EXPORT TileScrollBar: public PIScreenTile {
PIOBJECT_SUBCLASS(TileScrollBar, PIScreenTile) PIOBJECT_SUBCLASS(TileScrollBar, PIScreenTile)
friend class TileList; friend class TileList;
public: public:
@@ -66,7 +67,7 @@ protected:
}; };
class PIP_EXPORT TileList: public PIScreenTile { class PIP_CONSOLE_EXPORT TileList: public PIScreenTile {
PIOBJECT_SUBCLASS(TileList, PIScreenTile) PIOBJECT_SUBCLASS(TileList, PIScreenTile)
public: public:
TileList(const PIString & n = PIString()); TileList(const PIString & n = PIString());
@@ -98,7 +99,7 @@ protected:
}; };
class PIP_EXPORT TileButton: public PIScreenTile { class PIP_CONSOLE_EXPORT TileButton: public PIScreenTile {
PIOBJECT_SUBCLASS(TileButton, PIScreenTile) PIOBJECT_SUBCLASS(TileButton, PIScreenTile)
public: public:
TileButton(const PIString & n = PIString()); TileButton(const PIString & n = PIString());
@@ -118,7 +119,7 @@ protected:
class PIP_EXPORT TileButtons: public PIScreenTile { class PIP_CONSOLE_EXPORT TileButtons: public PIScreenTile {
PIOBJECT_SUBCLASS(TileButtons, PIScreenTile) PIOBJECT_SUBCLASS(TileButtons, PIScreenTile)
public: public:
TileButtons(const PIString & n = PIString()); TileButtons(const PIString & n = PIString());
@@ -143,7 +144,7 @@ protected:
}; };
class PIP_EXPORT TileCheck: public PIScreenTile { class PIP_CONSOLE_EXPORT TileCheck: public PIScreenTile {
PIOBJECT_SUBCLASS(TileCheck, PIScreenTile) PIOBJECT_SUBCLASS(TileCheck, PIScreenTile)
public: public:
TileCheck(const PIString & n = PIString()); TileCheck(const PIString & n = PIString());
@@ -162,7 +163,7 @@ protected:
}; };
class PIP_EXPORT TileProgress: public PIScreenTile { class PIP_CONSOLE_EXPORT TileProgress: public PIScreenTile {
PIOBJECT_SUBCLASS(TileProgress, PIScreenTile) PIOBJECT_SUBCLASS(TileProgress, PIScreenTile)
public: public:
TileProgress(const PIString & n = PIString()); TileProgress(const PIString & n = PIString());
@@ -178,7 +179,7 @@ protected:
}; };
class PIP_EXPORT TilePICout: public TileList { class PIP_CONSOLE_EXPORT TilePICout: public TileList {
PIOBJECT_SUBCLASS(TilePICout, PIScreenTile) PIOBJECT_SUBCLASS(TilePICout, PIScreenTile)
public: public:
TilePICout(const PIString & n = PIString()); TilePICout(const PIString & n = PIString());
@@ -191,7 +192,7 @@ protected:
}; };
class PIP_EXPORT TileInput: public PIScreenTile { class PIP_CONSOLE_EXPORT TileInput: public PIScreenTile {
PIOBJECT_SUBCLASS(TileInput, PIScreenTile) PIOBJECT_SUBCLASS(TileInput, PIScreenTile)
public: public:
TileInput(const PIString & n = PIString()); TileInput(const PIString & n = PIString());

View File

@@ -23,6 +23,7 @@
#ifndef PISCREENTYPES_H #ifndef PISCREENTYPES_H
#define PISCREENTYPES_H #define PISCREENTYPES_H
#include "pip_console_export.h"
#include "pivariant.h" #include "pivariant.h"
class PIScreenTile; class PIScreenTile;
@@ -30,7 +31,7 @@ class PIScreenTile;
namespace PIScreenTypes { namespace PIScreenTypes {
//! Color for chars or background //! Color for chars or background
enum PIP_EXPORT Color { enum Color {
Default /** Default */, Default /** Default */,
Black /** Black */, Black /** Black */,
Red /** Red */, Red /** Red */,
@@ -44,7 +45,7 @@ namespace PIScreenTypes {
}; };
//! Flags for chars //! Flags for chars
enum PIP_EXPORT CharFlag { enum CharFlag {
Bold /** Bold or bright */ = 0x1, Bold /** Bold or bright */ = 0x1,
Blink /** Blink text */ = 0x2, Blink /** Blink text */ = 0x2,
Underline /** Underline text */ = 0x4, Underline /** Underline text */ = 0x4,
@@ -52,14 +53,14 @@ namespace PIScreenTypes {
}; };
//! Alignment //! Alignment
enum PIP_EXPORT Alignment { enum Alignment {
Left /** Left */ , Left /** Left */ ,
Center /** Center */ , Center /** Center */ ,
Right /** Right */ Right /** Right */
}; };
//! Size policy //! Size policy
enum PIP_EXPORT SizePolicy { enum SizePolicy {
Fixed /** Fixed size */ , Fixed /** Fixed size */ ,
Preferred /** Preferred size */ , Preferred /** Preferred size */ ,
Expanding /** Maximum available size */ , Expanding /** Maximum available size */ ,
@@ -67,13 +68,13 @@ namespace PIScreenTypes {
}; };
//! Direction //! Direction
enum PIP_EXPORT Direction { enum Direction {
Horizontal /** Horizontal */ , Horizontal /** Horizontal */ ,
Vertical /** Vertical */ Vertical /** Vertical */
}; };
//! Focus flags //! Focus flags
enum PIP_EXPORT FocusFlag { enum FocusFlag {
CanHasFocus /** Tile can has focus */ = 0x1, CanHasFocus /** Tile can has focus */ = 0x1,
NextByTab /** Focus passed to next tile by tab key */ = 0x2, NextByTab /** Focus passed to next tile by tab key */ = 0x2,
NextByArrowsHorizontal /** Focus passed to next tile by arrow keys left or right */ = 0x4, NextByArrowsHorizontal /** Focus passed to next tile by arrow keys left or right */ = 0x4,
@@ -87,7 +88,7 @@ namespace PIScreenTypes {
typedef PIFlags<CharFlag> CharFlags; typedef PIFlags<CharFlag> CharFlags;
typedef PIFlags<FocusFlag> FocusFlags; typedef PIFlags<FocusFlag> FocusFlags;
union PIP_EXPORT CellFormat { union PIP_CONSOLE_EXPORT CellFormat {
CellFormat(ushort f = 0) {raw_format = f;} CellFormat(ushort f = 0) {raw_format = f;}
CellFormat(Color col_char, Color col_back = Default, CharFlags flags_ = 0) { CellFormat(Color col_char, Color col_back = Default, CharFlags flags_ = 0) {
color_char = col_char; color_char = col_char;
@@ -104,7 +105,7 @@ namespace PIScreenTypes {
bool operator !=(const CellFormat & c) const {return raw_format != c.raw_format;} bool operator !=(const CellFormat & c) const {return raw_format != c.raw_format;}
}; };
struct PIP_EXPORT Cell { struct PIP_CONSOLE_EXPORT Cell {
Cell(PIChar c = PIChar(' '), CellFormat f = CellFormat()) {symbol = c; format = f;} Cell(PIChar c = PIChar(' '), CellFormat f = CellFormat()) {symbol = c; format = f;}
CellFormat format; CellFormat format;
PIChar symbol; PIChar symbol;
@@ -120,13 +121,13 @@ namespace PIScreenTypes {
} }
}; };
struct PIP_EXPORT TileEvent { struct PIP_CONSOLE_EXPORT TileEvent {
TileEvent(int t = -1, const PIVariant & d = PIVariant()): type(t), data(d) {} TileEvent(int t = -1, const PIVariant & d = PIVariant()): type(t), data(d) {}
int type; int type;
PIVariant data; PIVariant data;
}; };
class PIScreenBase { class PIP_CONSOLE_EXPORT PIScreenBase {
public: public:
PIScreenBase() {} PIScreenBase() {}
virtual ~PIScreenBase() {} virtual ~PIScreenBase() {}

View File

@@ -23,11 +23,12 @@
#ifndef PITERMINAL_H #ifndef PITERMINAL_H
#define PITERMINAL_H #define PITERMINAL_H
#include "pip_console_export.h"
#include "pikbdlistener.h" #include "pikbdlistener.h"
#include "piscreentypes.h" #include "piscreentypes.h"
class PIP_EXPORT PITerminal: public PIThread class PIP_CONSOLE_EXPORT PITerminal: public PIThread
{ {
PIOBJECT_SUBCLASS(PITerminal, PIThread) PIOBJECT_SUBCLASS(PITerminal, PIThread)
public: public:
@@ -63,7 +64,7 @@ private:
int termType(const PIString & t); int termType(const PIString & t);
#endif #endif
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_CONSOLE_EXPORT)
int dsize_x, dsize_y; int dsize_x, dsize_y;
int size_x, size_y, cursor_x, cursor_y; int size_x, size_y, cursor_x, cursor_y;
bool cursor_blink, cursor_visible; bool cursor_blink, cursor_visible;

View File

@@ -28,147 +28,347 @@
* \fn PIVector::PIVector(); * \fn PIVector::PIVector();
* Contructs an empty vector * Contructs an empty vector
* \fn PIVector::PIVector(ullong size, const Type & value = Type()); * \fn PIVector::PIVector(size_t size, const T & value = T());
* \brief Contructs vector with size "size" filled elements "value" * \brief Contructs vector with size "size" filled elements "value"
* \details Example: \snippet picontainers.cpp PIVector::PIVector * \details Example: \snippet picontainers.cpp PIVector::PIVector
* \fn const Type & PIVector::at(ullong index) const; * \fn const T & PIVector::at(size_t index) const;
* \brief Read-only access to element by index "index" * \brief Read-only access to element by index "index"
* \details Example: \snippet picontainers.cpp PIVector::at_c * \details Example: \snippet picontainers.cpp PIVector::at_c
* \sa \a operator[] * \sa \a operator[]
* \fn Type & PIVector::at(ullong index); * \fn T & PIVector::at(size_t index);
* \brief Full access to element by index "index" * \brief Full access to element by index "index"
* \details Example: \snippet picontainers.cpp PIVector::at * \details Example: \snippet picontainers.cpp PIVector::at
* \sa \a operator[] * \sa \a operator[]
* \fn const Type * PIVector::data(ullong index = 0) const; * \fn const T * PIVector::data(size_t index = 0) const;
* \brief Read-only pointer to element by index "index" * \brief Read-only pointer to element by index "index"
* \details Example: \snippet picontainers.cpp PIVector::data_c * \details Example: \snippet picontainers.cpp PIVector::data_c
* \fn Type * PIVector::data(ullong index = 0); * \fn T * PIVector::data(size_t index = 0);
* \brief Pointer to element by index "index" * \brief Pointer to element by index "index"
* \details Example: \snippet picontainers.cpp PIVector::data * \details Example: \snippet picontainers.cpp PIVector::data
* \fn ullong PIVector::size() const; * \fn size_t PIVector::size() const;
* \brief Elements count * \brief Elements count
* \fn int PIVector::size_s() const; * \fn ssize_t PIVector::size_s() const;
* \brief Elements count * \brief Elements count
* \fn bool PIVector::isEmpty() const; * \fn bool PIVector::isEmpty() const;
* \brief Return \c "true" if vector is empty, i.e. size = 0 * \brief Return \c "true" if vector is empty, i.e. size = 0
* \fn bool PIVector::has(const Type & t) const; * \fn bool PIVector::has(const T & t) const;
* \fn bool PIVector::contains(const Type & v) const; * \fn bool PIVector::contains(const T & v) const;
* \brief Return \c "true" if vector has at least one element equal "t" * \brief Return \c "true" if vector has at least one element equal "t"
* \fn int PIVector::etries(const Type & t) const; * \fn int PIVector::etries(const T & t) const;
* \brief Return how many times element "t" appears in vector * \brief Return how many times element "t" appears in vector
* \fn static int PIVector::compare_func(const Type * t0, const Type * t1); * \fn ssize_t PIVector::indexOf(const T & t) const;
* \brief Standard compare function for type "Type". Return 0 if t0 = t1, -1 if t0 < t1 and 1 if t0 > t1. * \brief Return index of first element equal "t" or -1 if there is no such element
* \fn void PIVector::resize(ullong size, const Type & new_type = Type()); * \fn ssize_t PIVector::lastIndexOf(const T & t) const;
* \brief Return index of last element equal "t" or -1 if there is no such element
* \fn static int PIVector::compare_func(const T * t0, const T * t1);
* \brief Standard compare function for type "T". Return 0 if t0 = t1, -1 if t0 < t1 and 1 if t0 > t1.
* \fn void PIVector::resize(size_t size, const T & new_type = T());
* \brief Resize vector to size "size" * \brief Resize vector to size "size"
* \details Elements removed from end of vector if new size < old size, or added new elements = "new_type" if new size > old size.\n * \details Elements removed from end of vector if new size < old size, or added new elements = "new_type" if new size > old size.\n
* Example: \snippet picontainers.cpp PIVector::resize * Example: \snippet picontainers.cpp PIVector::resize
* \sa \a size(), \a clear() * \sa \a size(), \a clear()
* \fn PIVector<T> & PIVector::enlarge(ullong size); * \fn PIVector & PIVector::enlarge(size_t size);
* \brief Increase vector size with "size" elements * \brief Increase vector size with "size" elements
* \fn void PIVector::clear(); * \fn void PIVector::clear();
* \brief Clear vector. Equivalent to call <tt>"resize(0)"</tt> * \brief Clear vector. Equivalent to call <tt>"resize(0)"</tt>
* \fn PIVector<T> & PIVector::sort(CompareFunc compare = compare_func); * \fn PIVector & PIVector::sort(CompareFunc compare = compare_func);
* \brief Sort vector using quick sort algorithm and standard compare function * \brief Sort vector using quick sort algorithm and standard compare function
* \details Example: \snippet picontainers.cpp PIVector::sort_0 * \details Example: \snippet picontainers.cpp PIVector::sort_0
* With custom compare function: \snippet picontainers.cpp PIVector::sort_1 * With custom compare function: \snippet picontainers.cpp PIVector::sort_1
* \fn PIVector<T> & PIVector::fill(const Type & t); * \fn PIVector & PIVector::fill(const T & t);
* \brief Fill vector with elements "t" leave size is unchanged and return reference to vector * \brief Fill vector with elements "t" leave size is unchanged and return reference to vector
* \details Example: \snippet picontainers.cpp PIVector::fill * \details Example: \snippet picontainers.cpp PIVector::fill
* \fn Type & PIVector::back(); * \fn PIVector & PIVector::assign(const T & t = T());
* \brief Synonym of \a fill(t)
* \fn PIVector & PIVector::assign(size_t new_size, const T & t);
* \brief Resize to "new_size", then fill with "t"
* \fn T & PIVector::back();
* \brief Last element of the vector * \brief Last element of the vector
* \fn const Type & PIVector::back() const; * \fn const T & PIVector::back() const;
* \brief Last element of the vector * \brief Last element of the vector
* \fn Type & PIVector::front(); * \fn T & PIVector::front();
* \brief First element of the vector * \brief First element of the vector
* \fn const Type & PIVector::front() const; * \fn const T & PIVector::front() const;
* \brief First element of the vector * \brief First element of the vector
* \fn PIVector<T> & PIVector::push_back(const Type & t); * \fn PIVector & PIVector::push_back(const T & t);
* \brief Add new element "t" at the end of vector and return reference to vector * \brief Add new element "t" at the end of vector and return reference to vector
* \fn PIVector<T> & PIVector::push_front(const Type & t); * \fn PIVector & PIVector::push_front(const T & t);
* \brief Add new element "t" at the beginning of vector and return reference to vector * \brief Add new element "t" at the beginning of vector and return reference to vector
* \fn PIVector<T> & PIVector::pop_back(); * \fn PIVector & PIVector::pop_back();
* \brief Remove one element from the end of vector and return reference to vector * \brief Remove one element from the end of vector and return reference to vector
* \fn PIVector<T> & PIVector::pop_front(); * \fn PIVector & PIVector::pop_front();
* \brief Remove one element from the beginning of vector and return reference to vector * \brief Remove one element from the beginning of vector and return reference to vector
* \fn Type PIVector::take_back(); * \fn T PIVector::take_back();
* \brief Remove one element from the end of vector and return it * \brief Remove one element from the end of vector and return it
* \fn Type PIVector::take_front(); * \fn T PIVector::take_front();
* \brief Remove one element from the beginning of vector and return it * \brief Remove one element from the beginning of vector and return it
* \fn PIVector<T> & PIVector::remove(uint index); * \fn PIVector & PIVector::remove(size_t index);
* \brief Remove one element by index "index" and return reference to vector * \brief Remove one element by index "index" and return reference to vector
* \details Example: \snippet picontainers.cpp PIVector::remove_0 * \details Example: \snippet picontainers.cpp PIVector::remove_0
* \sa \a removeOne(), \a removeAll() * \sa \a removeOne(), \a removeAll()
* \fn PIVector<T> & PIVector::remove(uint index, uint count); * \fn PIVector & PIVector::remove(size_t index, size_t count);
* \brief Remove "count" elements by first index "index" and return reference to vector * \brief Remove "count" elements by first index "index" and return reference to vector
* \details Example: \snippet picontainers.cpp PIVector::remove_1 * \details Example: \snippet picontainers.cpp PIVector::remove_1
* \sa \a removeOne(), \a removeAll() * \sa \a removeOne(), \a removeAll()
* \fn PIVector<T> & PIVector::removeOne(const Type & v); * \fn PIVector & PIVector::removeOne(const T & v);
* \brief Remove no more than one element equal "v" and return reference to vector * \brief Remove no more than one element equal "v" and return reference to vector
* \details Example: \snippet picontainers.cpp PIVector::removeOne * \details Example: \snippet picontainers.cpp PIVector::removeOne
* \sa \a remove(), \a removeAll() * \sa \a remove(), \a removeAll()
* \fn PIVector<T> & PIVector::removeAll(const Type & v); * \fn PIVector & PIVector::removeAll(const T & v);
* \brief Remove all elements equal "v" and return reference to vector * \brief Remove all elements equal "v" and return reference to vector
* \details Example: \snippet picontainers.cpp PIVector::removeAll * \details Example: \snippet picontainers.cpp PIVector::removeAll
* \sa \a remove(), \a removeOne() * \sa \a remove(), \a removeOne()
* \fn PIVector<T> & PIVector::insert(uint pos, const Type & t); * \fn PIVector & PIVector::insert(size_t pos, const T & t);
* \brief Insert element "t" after index "pos" and return reference to vector * \brief Insert element "t" after index "pos" and return reference to vector
* \details Example: \snippet picontainers.cpp PIVector::insert_0 * \details Example: \snippet picontainers.cpp PIVector::insert_0
* \fn PIVector<T> & PIVector::insert(uint pos, const PIVector<T> & t); * \fn PIVector & PIVector::insert(size_t pos, const PIVector & t);
* \brief Insert other vector "t" after index "pos" and return reference to vector * \brief Insert other vector "t" after index "pos" and return reference to vector
* \details Example: \snippet picontainers.cpp PIVector::insert_1 * \details Example: \snippet picontainers.cpp PIVector::insert_1
* \fn Type & PIVector::operator [](uint index); * \fn T & PIVector::operator [](size_t index);
* \brief Full access to element by index "index" * \brief Full access to element by index "index"
* \details Example: \snippet picontainers.cpp PIVector::() * \details Example: \snippet picontainers.cpp PIVector::()
* \sa \a at() * \sa \a at()
* \fn const Type & PIVector::operator [](uint index) const; * \fn const T & PIVector::operator [](size_t index) const;
* \brief Read-only access to element by index "index" * \brief Read-only access to element by index "index"
* \details Example: \snippet picontainers.cpp PIVector::()_c * \details Example: \snippet picontainers.cpp PIVector::()_c
* \sa \a at() * \sa \a at()
* \fn PIVector<T> & PIVector::operator <<(const Type & t); * \fn PIVector & PIVector::operator <<(const T & t);
* \brief Add new element "t" at the end of vector and return reference to vector * \brief Add new element "t" at the end of vector and return reference to vector
* \fn PIVector<T> & PIVector::operator <<(const PIVector<T> & t); * \fn PIVector & PIVector::operator <<(const PIVector & t);
* \brief Add vector "t" at the end of vector and return reference to vector * \brief Add vector "t" at the end of vector and return reference to vector
* \fn bool PIVector::operator ==(const PIVector<T> & t); * \fn bool PIVector::operator ==(const PIVector & t);
* \brief Compare with vector "t" * \brief Compare with vector "t"
* \fn bool PIVector::operator !=(const PIVector<T> & t); * \fn bool PIVector::operator !=(const PIVector & t);
* \brief Compare with vector "t" * \brief Compare with vector "t"
* */ * */
/** \class PIMap
* \brief Associative array
* \details This class used to store Key = Value array of any
* type of data. \a value() returns value for key and leave map
* unchaged in any case. \a operator [] create entry in map if
* there is no entry for given key. You can retrieve all
* keys by method \a keys() and all values by methos \a values().
* To iterate all entries use class PIMapIterator, or methods
* \a makeIterator() and \a makeReverseIterator().
* \fn PIMap::PIMap();
* \brief Contructs an empty map
* \fn PIMap::PIMap(const PIMap & other);
* \brief Contructs a copy of "other"
* \fn PIMap & PIMap::operator =(const PIMap & other);
* \brief Copy operator
* \fn PIMap::PIMap(const PIMap & other);
* \brief Contructs a copy of "other"
* \fn PIMapIterator PIMap::makeIterator() const
* \brief Returns PIMapIterator for this map
* \fn PIMapIterator PIMap::makeReverseIterator() const
* \brief Returns reverse PIMapIterator for this map
* \fn size_t PIMap::size() const
* \brief Returns entries count
* \fn int PIMap::size_s() const
* \brief Returns entries count
* \fn size_t PIMap::length() const
* \brief Returns entries count
* \fn bool PIMap::isEmpty() const
* \brief Returns if map is empty
* \fn T & PIMap::operator [](const Key & key)
* \brief Returns value for key "key". If there is no key in map, create one.
* \fn const T PIMap::operator [](const Key & key) const
* \brief Returns value for key "key". If there is no key in map, returns default T().
* \fn T & PIMap::at(const Key & key)
* \brief Equivalent to operator []
* \fn const T PIMap::at(const Key & key) const
* \brief Equivalent to operator []
* \fn PIMap & PIMap::operator <<(const PIMap & other)
* \brief Insert all etries of "other" to this map. Override existing values.
* \fn bool PIMap::operator ==(const PIMap & t) const
* \brief Compare operator
* \fn bool PIMap::operator !=(const PIMap & t) const
* \brief Compare operator
* \fn bool PIMap::contains(const Key & key) const
* \brief Returns "true" if map contains entry with key "key"
* \fn PIMap & PIMap::reserve(size_t new_size)
* \brief Reserve space for "new_size" entries
* \fn PIMap & PIMap::removeOne(const Key & key)
* \brief Remove entry with key "key"
* \fn PIMap & PIMap::remove(const Key & key)
* \brief Equivalent \a removeOne(key)
* \fn PIMap & PIMap::erase(const Key & key)
* \brief Equivalent \a removeOne(key)
* \fn PIMap & PIMap::clear()
* \brief Clear map
* \fn void PIMap::swap(PIMap & other)
* \brief Swap map with "other"
* \fn PIMap & PIMap::insert(const Key & key, const T & value)
* \brief Insert or rewrite entry with key "key" and value "value"
* \fn const T PIMap::value(const Key & key, const T & default = T())
* \brief Returns value for key "key". If there is no key in map, returns "default".
* \fn PIVector<T> PIMap::values() const
* \brief Returns all values as PIVector
* \fn Key PIMap::key(const T & value, const Key & default = Key()) const
* \brief Returns key for first founded value "value". If there is no such value in map, returns "default".
* \fn PIVector<Key> PIMap::keys() const
* \brief Returns all keys as PIVector
* */
/** \class PIMapIterator
* \brief Helper class to iterate over PIMap
* \details This class used to access keys and values in PIMap.
* You can use constructor to create iterator, or use \a PIMap::makeIterator()
* and \a PIMap::makeReverseIterator() methods.
*
* First usage variant:
* \code
* PIMap<int, PIString> m;
* m[1] = "one";
* m[2] = "two";
* m[4] = "four";
*
* auto it = m.makeIterator();
* while (it.next()) {
* piCout << it.key() << it.value();
* }
* // 1 one
* // 2 two
* // 4 four
* \endcode
*
* Using hasNext():
* \code
* while (it.hasNext()) {
* it.next();
* \endcode
*
* Using constructor:
* \code
* PIMapIterator<int, PIString> it(m);
* \endcode
*
* Write access:
* \code
* while (it.next()) {
* it.valueRef().append("_!");
* piCout << it.key() << it.value();
* }
*
* // 1 one_!
* // 2 two_!
* // 4 four_!
* \endcode
*
* Reverse iterator:
* \code
* auto it = m.makeReverseIterator();
* while (it.next()) {
* piCout << it.key() << it.value();
* }
*
* // 4 four
* // 2 two
* // 1 one
* \endcode
* \fn PIMapIterator(const PIMap & map, bool reverse = false)
* \brief Contructs iterator for "map". Current position is invalid.
* \fn const Key & PIMapIterator::key() const
* \brief Returns current entry key
* \fn const T & PIMapIterator::value() const
* \brief Returns current entry value
* \fn T & PIMapIterator::valueRef() const
* \brief Returns reference to current entry value
* \fn bool PIMapIterator::hasNext()
* \brief Returns if iterator can jump to next entry
* \fn bool PIMapIterator::next()
* \brief Jump to next entry and return if new position is valid.
* */

View File

@@ -97,141 +97,32 @@
*/ */
# define piForeachCR(i,c) # define piForeachCR(i,c)
/*!\brief Macro for break from any piForeach* loop
* \details \warning C++ ordinary "break" doesn`t work inside piForeach*
* loops! Always use "piBreak" instead!
*/
# define piBreak
#else #else
# define piBreak {_for._end = true; break;}
template <typename C>
struct _reverse_wrapper {
C & c_;
_reverse_wrapper(C & c): c_(c) {}
_reverse_wrapper(const C & c): c_(const_cast<C&>(c)) {}
typename C::reverse_iterator begin() {return c_.rbegin();}
typename C::reverse_iterator end() {return c_.rend(); }
typename C::const_reverse_iterator begin() const {return c_.rbegin();}
typename C::const_reverse_iterator end() const {return c_.rend(); }
};
template <typename C> _reverse_wrapper<C> _reverse_wrap(C & c) {return _reverse_wrapper<C>(c);}
template <typename C> _reverse_wrapper<C> _reverse_wrap(const C & c) {return _reverse_wrapper<C>(c);}
# define piForTimes(c) for(int _i##c = 0; _i##c < c; ++_i##c) # define piForTimes(c) for(int _i##c = 0; _i##c < c; ++_i##c)
#ifdef CC_GCC # define piForeach(i,c) for(i : c)
# define piForeachC(i,c) for(const i : c)
# define piForeachR(i,c) for(i : _reverse_wrap(c))
# define piForeachRC(i,c) for(const i : _reverse_wrap(c))
template<typename Type> # define piForeachCR piForeachRC
class _PIForeach {
public:
_PIForeach(Type & t): _t(t), _break(false), _end(false) {_it = _t.begin();}
typename Type::value_type _var;
typename Type::iterator _it;
Type & _t;
bool _break, _end;
inline bool isEnd() {return _it == _t.end();}
inline void operator ++() {if (_end) _it = _t.end(); else _it++; _break = false;}
};
template<typename Type>
class _PIForeachR {
public:
_PIForeachR(Type & t): _t(t), _break(false), _end(false) {_rit = _t.rbegin();}
typename Type::value_type _var;
typename Type::reverse_iterator _rit;
Type & _t;
bool _break, _end;
inline bool isEnd() {return _rit == _t.rend();}
inline void operator ++() {if (_end) _rit = _t.rend(); else _rit++; _break = false;}
};
template<typename Type>
class _PIForeachC {
public:
_PIForeachC(const Type & t): _t(t), _break(false), _end(false) {_it = _t.begin();}
typename Type::value_type _var;
typename Type::const_iterator _it;
const Type & _t;
bool _break, _end;
inline bool isEnd() {return _it == _t.end();}
inline void operator ++() {if (_end) _it = _t.end(); else _it++; _break = false;}
};
template<typename Type>
class _PIForeachCR {
public:
_PIForeachCR(const Type & t): _t(t), _break(false), _end(false) {_rit = _t.rbegin();}
typename Type::value_type _var;
typename Type::const_reverse_iterator _rit;
const Type & _t;
bool _break, _end;
inline bool isEnd() {return _rit == _t.rend();}
inline void operator ++() {if (_end) _rit = _t.rend(); else _rit++; _break = false;}
};
#define piForeach(i,c) for(_PIForeach<typeof(c)> _for(c); !_for.isEnd(); ++_for) \
for(i(*_for._it); !_for._break; _for._break = true)
#define piForeachR(i,c) for(_PIForeachR<typeof(c)> _for(c); !_for.isEnd(); ++_for) \
for(i(*_for._rit); !_for._break; _for._break = true)
#define piForeachA(i,c) for(_PIForeach<typeof(c)> _for(c); !_for.isEnd(); ++_for) \
for(typeof(_for._var) & i(*_for._it); !_for._break; _for._break = true)
#define piForeachAR(i,c) for(_PIForeachR<typeof(c)> _for(c); !_for.isEnd(); ++_for) \
for(typeof(_for._var) & i(*_for._rit); !_for._break; _for._break = true)
#define piForeachC(i,c) for(_PIForeachC<typeof(c)> _for(c); !_for.isEnd(); ++_for) \
for(const i(*_for._it); !_for._break; _for._break = true)
#define piForeachCR(i,c) for(_PIForeachCR<typeof(c)> _for(c); !_for.isEnd(); ++_for) \
for(const i(*_for._rit); !_for._break; _for._break = true)
#define piForeachCA(i,c) for(_PIForeachC<typeof(c)> _for(c); !_for.isEnd(); ++_for) \
for(const typeof(_for._var) & i(*_for._it); !_for._break; _for._break = true)
#define piForeachCAR(i,c) for(_PIForeachCR<typeof(c)> _for(c); !_for.isEnd(); ++_for) \
for(const typeof(_for._var) & i(*_for._rit); !_for._break; _for._break = true)
#define piForeachRA piForeachAR
#define piForeachAC piForeachCA
#define piForeachCRA piForeachCAR
#define piForeachARC piForeachCAR
#define piForeachACR piForeachCAR
#define piForeachRCA piForeachCAR
#define piForeachRAC piForeachCAR
#else
class _PIForeachBase {public: mutable bool _break, _end; };
template<typename Type>
class _PIForeach: public _PIForeachBase {
public:
_PIForeach(Type & t, bool i = false): _t(t), _inv(i) {_break = _end = false; if (_inv) _rit = _t.rbegin(); else _it = _t.begin();}
mutable typename Type::value_type _var;
mutable typename Type::iterator _it;
mutable typename Type::reverse_iterator _rit;
Type & _t;
bool _inv;
bool isEnd() {if (_inv) return _rit == _t.rend(); else return _it == _t.end();}
void operator ++() {if (_inv) {if (_end) _rit = _t.rend(); else _rit++;} else {if (_end) _it = _t.end(); else _it++;} _break = false;}
};
template<typename Type>
class _PIForeachC: public _PIForeachBase {
public:
_PIForeachC(const Type & t, bool i = false): _t(t), _inv(i) {_break = _end = false; if (_inv) _rit = _t.rbegin(); else _it = _t.begin();}
mutable typename Type::value_type _var;
mutable typename Type::const_iterator _it;
mutable typename Type::const_reverse_iterator _rit;
const Type & _t;
bool _inv;
bool isEnd() {if (_inv) return _rit == _t.rend(); else return _it == _t.end();}
void operator ++() {if (_inv) {if (_end) _rit = _t.rend(); else _rit++;} else {if (_end) _it = _t.end(); else _it++;} _break = false;}
};
template <typename T> inline _PIForeach<T> _PIForeachNew(T & t, bool i = false) {return _PIForeach<T>(t, i);}
template <typename T> inline _PIForeach<T> * _PIForeachCast(_PIForeachBase & c, T & ) {return static_cast<_PIForeach<T> * >(&c);}
template <typename T> inline _PIForeachC<T> _PIForeachNewC(const T & t, bool i = false) {return _PIForeachC<T>(t, i);}
template <typename T> inline _PIForeachC<T> * _PIForeachCastC(_PIForeachBase & c, const T & ) {return static_cast<_PIForeachC<T> * >(&c);}
#define piForeach(i,c) for(_PIForeachBase & _for = _PIForeachNew(c); !_PIForeachCast(_for, c)->isEnd(); ++(*_PIForeachCast(_for, c))) \
for(i = *(_PIForeachCast(_for, c)->_it); !_for._break; _for._break = true)
#define piForeachR(i,c) for(_PIForeachBase & _for = _PIForeachNew(c, true); !_PIForeachCast(_for, c)->isEnd(); ++(*_PIForeachCast(_for, c))) \
for(i = *(_PIForeachCast(_for, c)->_rit); !_for._break; _for._break = true)
#define piForeachC(i,c) for(_PIForeachBase & _for = _PIForeachNewC(c); !_PIForeachCastC(_for, c)->isEnd(); ++(*_PIForeachCastC(_for, c))) \
for(const i = *(_PIForeachCastC(_for, c)->_it); !_for._break; _for._break = true)
#define piForeachCR(i,c) for(_PIForeachBase & _for = _PIForeachNewC(c, false); !_PIForeachCastC(_for, c)->isEnd(); ++(*_PIForeachCastC(_for, c))) \
for(const i = *(_PIForeachCastC(_for, c)->_rit); !_for._break; _for._break = true)
#endif
#define piForeachRC piForeachCR
#endif // DOXYGEN #endif // DOXYGEN

View File

@@ -32,7 +32,6 @@ template <typename T>
class PIDeque { class PIDeque {
public: public:
inline PIDeque(): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { inline PIDeque(): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) {
//piCout << "PIDeque";
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
} }
inline PIDeque(const PIDeque<T> & other): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { inline PIDeque(const PIDeque<T> & other): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) {
@@ -49,8 +48,10 @@ public:
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
resize(pid_size, f); resize(pid_size, f);
} }
inline PIDeque(PIDeque<T> && other): pid_data(other.pid_data), pid_size(other.pid_size), pid_rsize(other.pid_rsize), pid_start(other.pid_start) {
other._reset();
}
inline virtual ~PIDeque() { inline virtual ~PIDeque() {
//piCout << "~PIDeque";
PIINTROSPECTION_CONTAINER_DELETE(T) PIINTROSPECTION_CONTAINER_DELETE(T)
PIINTROSPECTION_CONTAINER_FREE(T, (pid_rsize)) PIINTROSPECTION_CONTAINER_FREE(T, (pid_rsize))
deleteT(pid_data + pid_start, pid_size); deleteT(pid_data + pid_start, pid_size);
@@ -66,6 +67,11 @@ public:
return *this; return *this;
} }
inline PIDeque<T> & operator =(PIDeque<T> && other) {
swap(other);
return *this;
}
typedef T value_type; typedef T value_type;
class iterator { class iterator {
@@ -256,6 +262,23 @@ public:
elementNew(pid_data + pid_start + index, v); elementNew(pid_data + pid_start + index, v);
return *this; return *this;
} }
inline PIDeque<T> & insert(size_t index, T && v) {
bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false);
if (dir) {
alloc(pid_size + 1, true);
if (index < pid_size - 1) {
size_t os = pid_size - index - 1;
memmove((void*)(&(pid_data[index + pid_start + 1])), (const void*)(&(pid_data[index + pid_start])), os * sizeof(T));
}
} else {
alloc(pid_size + 1, false, -1);
if (index > 0)
memmove((void*)(&(pid_data[pid_start])), (const void*)(&(pid_data[pid_start + 1])), index * sizeof(T));
}
PIINTROSPECTION_CONTAINER_USED(T, 1)
elementNew(pid_data + pid_start + index, std::move(v));
return *this;
}
inline PIDeque<T> & insert(size_t index, const PIDeque<T> & other) { inline PIDeque<T> & insert(size_t index, const PIDeque<T> & other) {
if (other.isEmpty()) return *this; if (other.isEmpty()) return *this;
assert(&other != this); assert(&other != this);
@@ -336,7 +359,14 @@ public:
elementNew(pid_data + pid_start + pid_size - 1, v); elementNew(pid_data + pid_start + pid_size - 1, v);
return *this; return *this;
} }
inline PIDeque<T> & push_back(T && v) {
alloc(pid_size + 1, true);
PIINTROSPECTION_CONTAINER_USED(T, 1);
elementNew(pid_data + pid_start + pid_size - 1, std::move(v));
return *this;
}
inline PIDeque<T> & append(const T & v) {return push_back(v);} inline PIDeque<T> & append(const T & v) {return push_back(v);}
inline PIDeque<T> & append(T && v) {return push_back(std::move(v));}
inline PIDeque<T> & append(const PIDeque<T> & t) { inline PIDeque<T> & append(const PIDeque<T> & t) {
assert(&t != this); assert(&t != this);
size_t ps = pid_size; size_t ps = pid_size;
@@ -345,10 +375,13 @@ public:
return *this; return *this;
} }
inline PIDeque<T> & operator <<(const T & v) {return push_back(v);} inline PIDeque<T> & operator <<(const T & v) {return push_back(v);}
inline PIDeque<T> & operator <<(T && v) {return push_back(std::move(v));}
inline PIDeque<T> & operator <<(const PIDeque<T> & t) {return append(t);} inline PIDeque<T> & operator <<(const PIDeque<T> & t) {return append(t);}
inline PIDeque<T> & push_front(const T & v) {insert(0, v); return *this;} inline PIDeque<T> & push_front(const T & v) {insert(0, v); return *this;}
inline PIDeque<T> & push_front(T && v) {insert(0, std::move(v)); return *this;}
inline PIDeque<T> & prepend(const T & v) {return push_front(v);} inline PIDeque<T> & prepend(const T & v) {return push_front(v);}
inline PIDeque<T> & prepend(T && v) {return push_front(std::move(v));}
inline PIDeque<T> & pop_back() {if (pid_size == 0) return *this; resize(pid_size - 1); return *this;} inline PIDeque<T> & pop_back() {if (pid_size == 0) return *this; resize(pid_size - 1); return *this;}
inline PIDeque<T> & pop_front() {if (pid_size == 0) return *this; remove(0); return *this;} inline PIDeque<T> & pop_front() {if (pid_size == 0) return *this; remove(0); return *this;}
@@ -412,6 +445,7 @@ private:
} }
} }
inline void elementNew(T * to, const T & from) {new(to)T(from);} inline void elementNew(T * to, const T & from) {new(to)T(from);}
inline void elementNew(T * to, T && from) {new(to)T(std::move(from));}
inline void elementDelete(T & from) {from.~T();} inline void elementDelete(T & from) {from.~T();}
inline void dealloc() { inline void dealloc() {
if ((uchar*)pid_data != 0) free((uchar*)pid_data); if ((uchar*)pid_data != 0) free((uchar*)pid_data);
@@ -485,6 +519,7 @@ private:
template<> inline void PIDeque<T>::newT(T * dst, const T * src, size_t s) {PIINTROSPECTION_CONTAINER_USED(T, s); memcpy((void*)(dst), (const void*)(src), s * sizeof(T));} \ template<> inline void PIDeque<T>::newT(T * dst, const T * src, size_t s) {PIINTROSPECTION_CONTAINER_USED(T, s); memcpy((void*)(dst), (const void*)(src), s * sizeof(T));} \
template<> inline void PIDeque<T>::deleteT(T *, size_t sz) {PIINTROSPECTION_CONTAINER_UNUSED(T, sz);} \ template<> inline void PIDeque<T>::deleteT(T *, size_t sz) {PIINTROSPECTION_CONTAINER_UNUSED(T, sz);} \
template<> inline void PIDeque<T>::elementNew(T * to, const T & from) {(*to) = from;} \ template<> inline void PIDeque<T>::elementNew(T * to, const T & from) {(*to) = from;} \
template<> inline void PIDeque<T>::elementNew(T * to, T && from) {(*to) = std::move(from);} \
template<> inline void PIDeque<T>::elementDelete(T &) {;} \ template<> inline void PIDeque<T>::elementDelete(T &) {;} \
template<> inline PIDeque<T> & PIDeque<T>::_resizeRaw(size_t new_size) { \ template<> inline PIDeque<T> & PIDeque<T>::_resizeRaw(size_t new_size) { \
if (new_size > pid_size) { \ if (new_size > pid_size) { \

View File

@@ -67,13 +67,20 @@ void piQuickSort(T * a, ssize_t N) {
} }
} }
template <typename Key, typename T>
class PIMapIterator;
template <typename Key, typename T> template <typename Key, typename T>
class PIMap { class PIMap {
template <typename Key1, typename T1> friend PIByteArray & operator >>(PIByteArray & s, PIMap<Key1, T1> & v); template <typename Key1, typename T1> friend PIByteArray & operator >>(PIByteArray & s, PIMap<Key1, T1> & v);
template <typename Key1, typename T1> friend PIByteArray & operator <<(PIByteArray & s, const PIMap<Key1, T1> & v); template <typename Key1, typename T1> friend PIByteArray & operator <<(PIByteArray & s, const PIMap<Key1, T1> & v);
template <typename Key1, typename T1> friend class PIMapIterator;
public: public:
PIMap() {;} PIMap() {;}
PIMap(const PIMap<Key, T> & other) {*this = other;} PIMap(const PIMap<Key, T> & other) {*this = other;}
PIMap(PIMap<Key, T> && other) : pim_content(std::move(other.pim_content)), pim_index(std::move(other.pim_index)) {}
virtual ~PIMap() {;} virtual ~PIMap() {;}
PIMap<Key, T> & operator =(const PIMap<Key, T> & other) { PIMap<Key, T> & operator =(const PIMap<Key, T> & other) {
@@ -84,6 +91,11 @@ public:
return *this; return *this;
} }
PIMap<Key, T> & operator =(PIMap<Key, T> && other) {
swap(other);
return *this;
}
typedef T mapped_type; typedef T mapped_type;
typedef Key key_type; typedef Key key_type;
typedef PIPair<Key, T> value_type; typedef PIPair<Key, T> value_type;
@@ -177,6 +189,9 @@ public:
const_reverse_iterator constRbegin() const {return const_reverse_iterator(this, size() - 1);} const_reverse_iterator constRbegin() const {return const_reverse_iterator(this, size() - 1);}
const_reverse_iterator constRend() const {return const_reverse_iterator(this, -1);} const_reverse_iterator constRend() const {return const_reverse_iterator(this, -1);}
PIMapIterator<Key, T> makeIterator() const {return PIMapIterator<Key, T>(*this);}
PIMapIterator<Key, T> makeReverseIterator() const {return PIMapIterator<Key, T>(*this, true);}
size_t size() const {return pim_content.size();} size_t size() const {return pim_content.size();}
int size_s() const {return pim_content.size_s();} int size_s() const {return pim_content.size_s();}
size_t length() const {return pim_content.size();} size_t length() const {return pim_content.size();}
@@ -232,6 +247,18 @@ public:
} }
return *this; return *this;
} }
PIMap<Key, T> & insert(const Key & key, T && value) {
bool f(false);
ssize_t i = _find(key, f);
//piCout << "insert key=" << key << "found=" << f << "index=" << i << "value=" << value;
if (f) {
pim_content[pim_index[i].index] = std::move(value);
} else {
pim_content.push_back(std::move(value));
pim_index.insert(i, MapIndex(key, pim_content.size() - 1));
}
return *this;
}
const T value(const Key & key, const T & default_ = T()) const {bool f(false); ssize_t i = _find(key, f); if (!f) return default_; return pim_content[pim_index[i].index];} const T value(const Key & key, const T & default_ = T()) const {bool f(false); ssize_t i = _find(key, f); if (!f) return default_; return pim_content[pim_index[i].index];}
PIVector<T> values() const {return pim_content;} PIVector<T> values() const {return pim_content;}
Key key(const T & value_, const Key & default_ = Key()) const {for (int i = 0; i < pim_index.size_s(); ++i) if (pim_content[pim_index[i].index] == value_) return pim_index[i].key; return default_;} Key key(const T & value_, const Key & default_ = Key()) const {for (int i = 0; i < pim_index.size_s(); ++i) if (pim_content[pim_index[i].index] == value_) return pim_index[i].key; return default_;}
@@ -309,6 +336,41 @@ protected:
}; };
template <typename Key, typename T>
class PIMapIterator {
typedef PIMap<Key, T> MapType;
public:
PIMapIterator(const PIMap<Key, T> & map, bool reverse = false): m(map), pos(-1), rev(reverse) {
if (rev) pos = m.size_s();
}
const Key & key() const {return const_cast<MapType & >(m)._key(pos);}
const T & value() const {return const_cast<MapType & >(m)._value(pos);}
T & valueRef() const {return const_cast<MapType & >(m)._value(pos);}
inline bool hasNext() const {
if (rev) {
return pos > 0;
} else {
return pos < (m.size_s() - 1);
}
return false;
}
inline bool next() {
if (rev) {
--pos;
return pos >= 0;
} else {
++pos;
return pos < m.size_s();
}
return false;
}
private:
const MapType & m;
ssize_t pos;
bool rev;
};
#ifdef PIP_STD_IOSTREAM #ifdef PIP_STD_IOSTREAM
template<typename Key, typename Type> template<typename Key, typename Type>
inline std::ostream & operator <<(std::ostream & s, const PIMap<Key, Type> & v) { inline std::ostream & operator <<(std::ostream & s, const PIMap<Key, Type> & v) {

View File

@@ -30,7 +30,7 @@
class PICout; class PICout;
template<typename Type0, typename Type1> template<typename Type0, typename Type1>
class PIP_EXPORT PIPair { class PIPair {
public: public:
PIPair() {first = Type0(); second = Type1();} PIPair() {first = Type0(); second = Type1();}
PIPair(const Type0 & value0, const Type1 & value1) {first = value0; second = value1;} PIPair(const Type0 & value0, const Type1 & value1) {first = value0; second = value1;}

View File

@@ -30,18 +30,20 @@
template<typename T> template<typename T>
class PIP_EXPORT PIQueue: public PIDeque<T> { class PIQueue: public PIDeque<T> {
public: public:
PIQueue() {} PIQueue() {}
virtual ~PIQueue() {} virtual ~PIQueue() {}
PIDeque<T> & enqueue(const T & v) {PIDeque<T>::push_front(v); return *this;} PIDeque<T> & enqueue(const T & v) {PIDeque<T>::push_front(v); return *this;}
PIDeque<T> & enqueue(T && v) {PIDeque<T>::push_front(std::move(v)); return *this;}
T dequeue() {return PIDeque<T>::take_back();} T dequeue() {return PIDeque<T>::take_back();}
T & head() {return PIDeque<T>::back();} T & head() {return PIDeque<T>::back();}
const T & head() const {return PIDeque<T>::back();} const T & head() const {return PIDeque<T>::back();}
PIVector<T> toVector() { PIVector<T> toVector() {
PIVector<T> v(PIDeque<T>::size()); PIVector<T> v;
v.reserve(PIDeque<T>::size());
for (uint i = 0; i < PIDeque<T>::size(); ++i) for (uint i = 0; i < PIDeque<T>::size(); ++i)
v[i] = PIDeque<T>::at(i); v.push_back(PIDeque<T>::at(i));
return v; return v;
} }
}; };

View File

@@ -35,7 +35,7 @@
* has logarithmic complexity. * has logarithmic complexity.
*/ */
template <typename T> template <typename T>
class PIP_EXPORT PISet: public PIMap<T, uchar> { class PISet: public PIMap<T, uchar> {
typedef PIMap<T, uchar> _CSet; typedef PIMap<T, uchar> _CSet;
public: public:
@@ -75,6 +75,7 @@ public:
typedef T key_type; typedef T key_type;
PISet<T> & operator <<(const T & t) {_CSet::insert(t, 0); return *this;} PISet<T> & operator <<(const T & t) {_CSet::insert(t, 0); return *this;}
PISet<T> & operator <<(T && t) {_CSet::insert(std::move(t), 0); return *this;}
PISet<T> & operator <<(const PISet<T> & other) {(*(_CSet*)this) << *((_CSet*)&other); return *this;} PISet<T> & operator <<(const PISet<T> & other) {(*(_CSet*)this) << *((_CSet*)&other); return *this;}
//! Returns if element "t" exists in this set //! Returns if element "t" exists in this set

View File

@@ -28,15 +28,22 @@
#include "pivector.h" #include "pivector.h"
template<typename T> template<typename T>
class PIP_EXPORT PIStack: public PIVector<T> { class PIStack: public PIVector<T> {
public: public:
PIStack() {;} PIStack() {;}
virtual ~PIStack() {;} virtual ~PIStack() {;}
PIVector<T> & push(const T & v) {PIVector<T>::push_back(v); return *this;} PIVector<T> & push(const T & v) {PIVector<T>::push_back(v); return *this;}
PIVector<T> & push(T && v) {PIVector<T>::push_back(std::move(v)); return *this;}
T pop() {return PIVector<T>::take_back();} T pop() {return PIVector<T>::take_back();}
T & top() {return PIVector<T>::back();} T & top() {return PIVector<T>::back();}
const T & top() const {return PIVector<T>::back();} const T & top() const {return PIVector<T>::back();}
PIVector<T> toVector() {PIVector<T> v(PIVector<T>::size()); for (uint i = 0; i < PIVector<T>::size(); ++i) v[i] = PIVector<T>::at(i); return v;} PIVector<T> toVector() {
PIVector<T> v;
v.reserve(PIVector<T>::size());
for (uint i = 0; i < PIVector<T>::size(); ++i)
v.push_back(PIVector<T>::at(i));
return v;
}
}; };
#endif // PISTACK_H #endif // PISTACK_H

View File

@@ -48,6 +48,9 @@ public:
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
resize(piv_size, f); resize(piv_size, f);
} }
inline PIVector(PIVector<T> && other): piv_data(other.piv_data), piv_size(other.piv_size), piv_rsize(other.piv_rsize) {
other._reset();
}
inline virtual ~PIVector() { inline virtual ~PIVector() {
PIINTROSPECTION_CONTAINER_DELETE(T) PIINTROSPECTION_CONTAINER_DELETE(T)
PIINTROSPECTION_CONTAINER_FREE(T, (piv_rsize)) PIINTROSPECTION_CONTAINER_FREE(T, (piv_rsize))
@@ -65,6 +68,11 @@ public:
return *this; return *this;
} }
inline PIVector<T> & operator =(PIVector<T> && other) {
swap(other);
return *this;
}
typedef T value_type; typedef T value_type;
class iterator { class iterator {
@@ -253,6 +261,16 @@ public:
elementNew(piv_data + index, v); elementNew(piv_data + index, v);
return *this; return *this;
} }
inline PIVector<T> & insert(size_t index, T && v) {
alloc(piv_size + 1);
if (index < piv_size - 1) {
size_t os = piv_size - index - 1;
memmove((void*)(&(piv_data[index + 1])), (const void*)(&(piv_data[index])), os * sizeof(T));
}
PIINTROSPECTION_CONTAINER_USED(T, 1)
elementNew(piv_data + index, std::move(v));
return *this;
}
inline PIVector<T> & insert(size_t index, const PIVector<T> & other) { inline PIVector<T> & insert(size_t index, const PIVector<T> & other) {
if (other.isEmpty()) return *this; if (other.isEmpty()) return *this;
assert(&other != this); assert(&other != this);
@@ -320,7 +338,14 @@ public:
elementNew(piv_data + piv_size - 1, v); elementNew(piv_data + piv_size - 1, v);
return *this; return *this;
} }
inline PIVector<T> & push_back(T && v) {
alloc(piv_size + 1);
PIINTROSPECTION_CONTAINER_USED(T, 1);
elementNew(piv_data + piv_size - 1, std::move(v));
return *this;
}
inline PIVector<T> & append(const T & v) {return push_back(v);} inline PIVector<T> & append(const T & v) {return push_back(v);}
inline PIVector<T> & append(T && v) {return push_back(std::move(v));}
inline PIVector<T> & append(const PIVector<T> & other) { inline PIVector<T> & append(const PIVector<T> & other) {
assert(&other != this); assert(&other != this);
size_t ps = piv_size; size_t ps = piv_size;
@@ -329,10 +354,13 @@ public:
return *this; return *this;
} }
inline PIVector<T> & operator <<(const T & v) {return push_back(v);} inline PIVector<T> & operator <<(const T & v) {return push_back(v);}
inline PIVector<T> & operator <<(T && v) {return push_back(std::move(v));}
inline PIVector<T> & operator <<(const PIVector<T> & other) {return append(other);} inline PIVector<T> & operator <<(const PIVector<T> & other) {return append(other);}
inline PIVector<T> & push_front(const T & v) {insert(0, v); return *this;} inline PIVector<T> & push_front(const T & v) {insert(0, v); return *this;}
inline PIVector<T> & push_front(T && v) {insert(0, std::move(v)); return *this;}
inline PIVector<T> & prepend(const T & v) {return push_front(v);} inline PIVector<T> & prepend(const T & v) {return push_front(v);}
inline PIVector<T> & prepend(T && v) {return push_front(std::move(v));}
inline PIVector<T> & pop_back() { inline PIVector<T> & pop_back() {
if (piv_size == 0) if (piv_size == 0)
@@ -405,6 +433,7 @@ private:
} }
} }
inline void elementNew(T * to, const T & from) {new(to)T(from);} inline void elementNew(T * to, const T & from) {new(to)T(from);}
inline void elementNew(T * to, T && from) {new(to)T(std::move(from));}
inline void elementDelete(T & from) {from.~T();} inline void elementDelete(T & from) {from.~T();}
inline void dealloc() { inline void dealloc() {
if ((uchar*)piv_data != 0) free((uchar*)piv_data); if ((uchar*)piv_data != 0) free((uchar*)piv_data);
@@ -434,6 +463,7 @@ private:
template<> inline void PIVector<T>::newT(T * dst, const T * src, size_t s) {PIINTROSPECTION_CONTAINER_USED(T, s); memcpy((void*)(dst), (const void*)(src), s * sizeof(T));} \ template<> inline void PIVector<T>::newT(T * dst, const T * src, size_t s) {PIINTROSPECTION_CONTAINER_USED(T, s); memcpy((void*)(dst), (const void*)(src), s * sizeof(T));} \
template<> inline void PIVector<T>::deleteT(T *, size_t sz) {PIINTROSPECTION_CONTAINER_UNUSED(T, sz);} \ template<> inline void PIVector<T>::deleteT(T *, size_t sz) {PIINTROSPECTION_CONTAINER_UNUSED(T, sz);} \
template<> inline void PIVector<T>::elementNew(T * to, const T & from) {(*to) = from;} \ template<> inline void PIVector<T>::elementNew(T * to, const T & from) {(*to) = from;} \
template<> inline void PIVector<T>::elementNew(T * to, T && from) {(*to) = std::move(from);} \
template<> inline void PIVector<T>::elementDelete(T &) {;} \ template<> inline void PIVector<T>::elementDelete(T &) {;} \
template<> inline PIVector<T> & PIVector<T>::_resizeRaw(size_t new_size) { \ template<> inline PIVector<T> & PIVector<T>::_resizeRaw(size_t new_size) { \
if (new_size > piv_size) { \ if (new_size > piv_size) { \

View File

@@ -44,10 +44,10 @@ public:
cols_ = cols; cols_ = cols;
mat.resize(rows*cols, f); mat.resize(rows*cols, f);
} }
inline PIVector2D(size_t rows, size_t cols, const PIVector<T> & v) { inline PIVector2D(size_t rows, size_t cols, const PIVector<T> & v) : rows_(rows), cols_(cols), mat(v) {
mat = v; mat.resize(rows*cols);
rows_ = rows; }
cols_ = cols; inline PIVector2D(size_t rows, size_t cols, PIVector<T> && v) : rows_(rows), cols_(cols), mat(std::move(v)) {
mat.resize(rows*cols); mat.resize(rows*cols);
} }
inline PIVector2D(const PIVector<PIVector<T> > & v) { inline PIVector2D(const PIVector<PIVector<T> > & v) {
@@ -236,6 +236,7 @@ public:
PIVector<PIVector<T> > toVectors() const { PIVector<PIVector<T> > toVectors() const {
PIVector<PIVector<T> > ret; PIVector<PIVector<T> > ret;
ret.reserve(rows_);
for(size_t i = 0; i < rows_; ++i) for(size_t i = 0; i < rows_; ++i)
ret << PIVector<T>(mat.data(i*cols_), cols_); ret << PIVector<T>(mat.data(i*cols_), cols_);
return ret; return ret;

View File

@@ -192,10 +192,10 @@
// Private data macros // Private data macros
#define PRIVATE_DECLARATION \ #define PRIVATE_DECLARATION(e) \
struct __Private__; \ struct __Private__; \
friend struct __Private__; \ friend struct __Private__; \
struct __PrivateInitializer__ { \ struct e __PrivateInitializer__ { \
__PrivateInitializer__(); \ __PrivateInitializer__(); \
__PrivateInitializer__(const __PrivateInitializer__ & o); \ __PrivateInitializer__(const __PrivateInitializer__ & o); \
~__PrivateInitializer__(); \ ~__PrivateInitializer__(); \

View File

@@ -56,6 +56,10 @@ public:
//! Constructs an empty byte array //! Constructs an empty byte array
PIByteArray() {;} PIByteArray() {;}
PIByteArray(const PIByteArray & o): PIDeque<uchar>(o) {}
PIByteArray(PIByteArray && o): PIDeque<uchar>(std::move(o)) {}
//! Constructs 0-filled byte array with size "size" //! Constructs 0-filled byte array with size "size"
PIByteArray(const uint size) {resize(size);} PIByteArray(const uint size) {resize(size);}
@@ -124,6 +128,10 @@ public:
void operator =(const PIDeque<uchar> & d) {resize(d.size()); memcpy(data(), d.data(), d.size());} void operator =(const PIDeque<uchar> & d) {resize(d.size()); memcpy(data(), d.data(), d.size());}
PIByteArray & operator =(const PIByteArray & o) {if (this == &o) return *this; clear(); append(o); return *this;}
PIByteArray & operator =(PIByteArray && o) {swap(o); return *this;}
static PIByteArray fromUserInput(PIString str); static PIByteArray fromUserInput(PIString str);
static PIByteArray fromHex(PIString str); static PIByteArray fromHex(PIString str);
static PIByteArray fromBase64(const PIByteArray & base64); static PIByteArray fromBase64(const PIByteArray & base64);
@@ -138,7 +146,7 @@ inline std::ostream & operator <<(std::ostream & s, const PIByteArray & ba);
#endif #endif
//! \relatesalso PIByteArray \brief Output to PICout operator //! \relatesalso PIByteArray \brief Output to PICout operator
PICout operator <<(PICout s, const PIByteArray & ba); PIP_EXPORT PICout operator <<(PICout s, const PIByteArray & ba);
#define PBA_OPERATOR_TO int os = s.size_s(); s.enlarge(sizeof(v)); memcpy(s.data(os), &v, sizeof(v)); #define PBA_OPERATOR_TO int os = s.size_s(); s.enlarge(sizeof(v)); memcpy(s.data(os), &v, sizeof(v));
@@ -212,7 +220,7 @@ inline PIByteArray & operator >>(PIByteArray & s, ldouble & v) {assert(s.size()
//! \relatesalso PIByteArray \brief Restore operator //! \relatesalso PIByteArray \brief Restore operator
template<typename T> inline PIByteArray & operator >>(PIByteArray & s, PIFlags<T> & v) {PBA_OPERATOR_FROM return s;} template<typename T> inline PIByteArray & operator >>(PIByteArray & s, PIFlags<T> & v) {PBA_OPERATOR_FROM return s;}
//! \relatesalso PIByteArray \brief Restore operator, see \ref PIByteArray_sec1 for details //! \relatesalso PIByteArray \brief Restore operator, see \ref PIByteArray_sec1 for details
PIByteArray & operator >>(PIByteArray & s, PIByteArray & v); PIP_EXPORT PIByteArray & operator >>(PIByteArray & s, PIByteArray & v);
//! \relatesalso PIByteArray \brief Restore operator, see \ref PIByteArray_sec1 for details //! \relatesalso PIByteArray \brief Restore operator, see \ref PIByteArray_sec1 for details
inline PIByteArray & operator >>(PIByteArray & s, PIByteArray::RawData v) {assert(s.size_s() >= v.s); if (v.s > 0) memcpy((void*)(v.d), s.data(), v.s); s.remove(0, v.s); return s;} inline PIByteArray & operator >>(PIByteArray & s, PIByteArray::RawData v) {assert(s.size_s() >= v.s); if (v.s > 0) memcpy((void*)(v.d), s.data(), v.s); s.remove(0, v.s); return s;}

View File

@@ -25,9 +25,9 @@
#include "piincludes.h" #include "piincludes.h"
extern char * __syslocname__; extern PIP_EXPORT char * __syslocname__;
extern char * __sysoemname__; extern PIP_EXPORT char * __sysoemname__;
extern char * __utf8name__; extern PIP_EXPORT char * __utf8name__;
class PIP_EXPORT PIChar class PIP_EXPORT PIChar
{ {

View File

@@ -54,12 +54,18 @@ public:
int id; int id;
T data; T data;
}; };
template <typename T>
struct ChunkConst {
ChunkConst(int i, const T & d): id(i), data(d) {}
int id;
const T & data;
};
//! Returns chunk with ID "id" and value "data" for write to stream //! Returns chunk with ID "id" and value "data" for write to stream
template <typename T> static Chunk<T> chunk(int id, const T & data) {return Chunk<T>(id, data);} template <typename T> static ChunkConst<T> chunk(int id, const T & data) {return ChunkConst<T>(id, data);}
//! Add data to this chunk strean with ID "id" and value "data" //! Add data to this chunk strean with ID "id" and value "data"
template <typename T> PIChunkStream & add(int id, const T & data) {*this << Chunk<T>(id, data); return *this;} template <typename T> PIChunkStream & add(int id, const T & data) {*this << ChunkConst<T>(id, data); return *this;}
void setSource(const PIByteArray & data); void setSource(const PIByteArray & data);
void setSource(PIByteArray * data); void setSource(PIByteArray * data);
@@ -112,6 +118,7 @@ private:
PIMap<int, PIByteArray> data_map; PIMap<int, PIByteArray> data_map;
template <typename T> friend PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::Chunk<T> & c); template <typename T> friend PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::Chunk<T> & c);
template <typename T> friend PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::ChunkConst<T> & c);
}; };
template <typename T> template <typename T>
@@ -133,5 +140,24 @@ PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::Chunk<T> & c
} }
return s; return s;
} }
template <typename T>
PIChunkStream & operator <<(PIChunkStream & s, const PIChunkStream::ChunkConst<T> & c) {
PIByteArray ba;
ba << c.data;
switch (s.version_) {
case PIChunkStream::Version_1:
(*(s.data_)) << c.id << ba;
break;
case PIChunkStream::Version_2:
if (s.data_->isEmpty())
(*(s.data_)) << uchar(uchar(s.version_) | 0x80);
PIChunkStream::writeVInt(*(s.data_), c.id);
PIChunkStream::writeVInt(*(s.data_), ba.size());
s.data_->append(ba);
break;
default: break;
}
return s;
}
#endif // PICHUNKSTREAM_H #endif // PICHUNKSTREAM_H

View File

@@ -64,13 +64,13 @@ public:
static bool addToGroup(const PIString & group, const PIObject * element); static bool addToGroup(const PIString & group, const PIObject * element);
class CollectionAdder { class PIP_EXPORT CollectionAdder {
public: public:
CollectionAdder(const PIString & group, const PIObject * element, const PIString & name = PIString(), bool own = false); CollectionAdder(const PIString & group, const PIObject * element, const PIString & name = PIString(), bool own = false);
}; };
protected: protected:
struct Group { struct PIP_EXPORT Group {
Group(const PIString & name_ = PIString()) {name = name_;} Group(const PIString & name_ = PIString()) {name = name_;}
PIString name; PIString name;
PIVector<const PIObject * > elements; PIVector<const PIObject * > elements;

View File

@@ -18,9 +18,9 @@
*/ */
#include "piincludes_p.h" #include "piincludes_p.h"
#include "picout.h" #include "picout.h"
#include "piconsole.h"
#include "pibytearray.h" #include "pibytearray.h"
#include "pistack.h" #include "pistack.h"
#include "piobject.h"
#include "pistring_std.h" #include "pistring_std.h"
#ifdef WINDOWS #ifdef WINDOWS
# include <windows.h> # include <windows.h>

View File

@@ -46,7 +46,7 @@ class PIObject;
namespace PICoutManipulators { namespace PICoutManipulators {
//! \brief Enum contains special characters //! \brief Enum contains special characters
enum PIP_EXPORT PICoutSpecialChar { enum PICoutSpecialChar {
Null /*! Null-character, '\\0' */, Null /*! Null-character, '\\0' */,
NewLine /*! New line character, '\\n' */, NewLine /*! New line character, '\\n' */,
Tab /*! Tab character, '\\t' */, Tab /*! Tab character, '\\t' */,
@@ -55,7 +55,7 @@ namespace PICoutManipulators {
}; };
//! \brief Enum contains immediate action //! \brief Enum contains immediate action
enum PIP_EXPORT PICoutAction { enum PICoutAction {
Flush /*! Flush the output */, Flush /*! Flush the output */,
Backspace /*! Remove last symbol */, Backspace /*! Remove last symbol */,
ShowCursor /*! Show cursor */, ShowCursor /*! Show cursor */,
@@ -67,7 +67,7 @@ namespace PICoutManipulators {
}; };
//! \brief Enum contains control of PICout //! \brief Enum contains control of PICout
enum PIP_EXPORT PICoutControl { enum PICoutControl {
AddNone /*! No controls */ = 0x0, AddNone /*! No controls */ = 0x0,
AddSpaces /*! Spaces will be appear after each output */ = 0x1, AddSpaces /*! Spaces will be appear after each output */ = 0x1,
AddNewLine /*! New line will be appear after all output */ = 0x2, AddNewLine /*! New line will be appear after all output */ = 0x2,
@@ -78,7 +78,7 @@ namespace PICoutManipulators {
}; };
//! \brief Enum contains output format //! \brief Enum contains output format
enum PIP_EXPORT PICoutFormat { enum PICoutFormat {
Bin /*! Binary representation of integers */ = 0x01, Bin /*! Binary representation of integers */ = 0x01,
Oct /*! Octal representation of integers */ = 0x02, Oct /*! Octal representation of integers */ = 0x02,
Dec /*! Decimal representation of integers */ = 0x04, Dec /*! Decimal representation of integers */ = 0x04,
@@ -128,7 +128,7 @@ public:
~PICout(); ~PICout();
class Notifier { class PIP_EXPORT Notifier {
public: public:
static Notifier * instance(); static Notifier * instance();
static PIObject * object(); static PIObject * object();
@@ -291,7 +291,7 @@ private:
void applyFormat(PICoutManipulators::PICoutFormat f); void applyFormat(PICoutManipulators::PICoutFormat f);
static OutputDevices devs; static OutputDevices devs;
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_EXPORT)
bool fo_, cc_, fc_, act_; bool fo_, cc_, fc_, act_;
int cnb_, attr_, id_; int cnb_, attr_, id_;
PIString * buffer_; PIString * buffer_;

View File

@@ -32,7 +32,7 @@
* \snippet piincludes.cpp flags * \snippet piincludes.cpp flags
*/ */
template<typename Enum> template<typename Enum>
class PIP_EXPORT PIFlags { class PIFlags {
public: public:
//! Constructor with flags = 0 //! Constructor with flags = 0
PIFlags(): flags(0) {;} PIFlags(): flags(0) {;}

View File

@@ -19,7 +19,6 @@
#include "piincludes.h" #include "piincludes.h"
#include "piincludes_p.h" #include "piincludes_p.h"
#include "piconsole.h"
#include "pitime.h" #include "pitime.h"
#ifndef QNX #ifndef QNX
# include <clocale> # include <clocale>

View File

@@ -27,10 +27,9 @@
# include <iostream> # include <iostream>
#endif #endif
#include <atomic> #include <atomic>
#include <mutex>
typedef std::mutex PIMutex; class PIMutex;
//typedef std::lock_guard<std::mutex> PIMutexLocker; class PIMutexLocker;
class PIObject; class PIObject;
class PIString; class PIString;
class PIByteArray; class PIByteArray;
@@ -40,7 +39,7 @@ class PICout;
struct lconv; struct lconv;
extern lconv * currentLocale; extern PIP_EXPORT lconv * currentLocale;
/*! \fn errorString() /*! \fn errorString()
* \brief Return readable error description in format "code <number> - <description>" */ * \brief Return readable error description in format "code <number> - <description>" */

View File

@@ -125,7 +125,7 @@ PIInit::PIInit() {
piForeachC (PIString & i, ifpathes) { piForeachC (PIString & i, ifpathes) {
if (fileExists(i)) { if (fileExists(i)) {
sinfo->ifconfigPath = i; sinfo->ifconfigPath = i;
piBreak; break;
} }
} }
# else # else

View File

@@ -63,7 +63,7 @@ private:
explicit PIInit(); explicit PIInit();
void setFileCharset(const char *charset); void setFileCharset(const char *charset);
bool fileExists(const PIString & p); bool fileExists(const PIString & p);
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_EXPORT)
char * file_charset; char * file_charset;
}; };

View File

@@ -190,39 +190,42 @@ PIStringList PIObject::scopeList() const {
PIStringList PIObject::methodsEH() const { PIStringList PIObject::methodsEH() const {
PIMutexLocker ml(__meta_mutex()); PIMutexLocker ml(__meta_mutex());
PIStringList ret; PIStringList ret;
__MetaData & ehd(__meta_data()[classNameID()]); const __MetaData & ehd(__meta_data()[classNameID()]);
piForeachC (__EHPair & eh, ehd.eh_func) for (auto eh = ehd.eh_func.constBegin(); eh != ehd.eh_func.constEnd(); eh++)
ret << eh.second.fullFormat(); ret << eh.value().fullFormat();
return ret; return ret;
} }
bool PIObject::isMethodEHContains(const PIString & name) const { bool PIObject::isMethodEHContains(const PIString & name) const {
PIMutexLocker ml(__meta_mutex()); PIMutexLocker ml(__meta_mutex());
__MetaData & ehd(__meta_data()[classNameID()]); const __MetaData & ehd(__meta_data()[classNameID()]);
piForeachC (__EHPair & eh, ehd.eh_func) for (auto eh = ehd.eh_func.constBegin(); eh != ehd.eh_func.constEnd(); eh++) {
if (eh.second.func_name == name) if (eh.value().func_name == name)
return true; return true;
}
return false; return false;
} }
PIString PIObject::methodEHArguments(const PIString & name) const { PIString PIObject::methodEHArguments(const PIString & name) const {
PIMutexLocker ml(__meta_mutex()); PIMutexLocker ml(__meta_mutex());
__MetaData & ehd(__meta_data()[classNameID()]); const __MetaData & ehd(__meta_data()[classNameID()]);
piForeachC (__EHPair & eh, ehd.eh_func) for (auto eh = ehd.eh_func.constBegin(); eh != ehd.eh_func.constEnd(); eh++) {
if (eh.second.func_name == name) if (eh.value().func_name == name)
return eh.second.arguments(); return eh.value().arguments();
}
return PIString(); return PIString();
} }
PIString PIObject::methodEHFullFormat(const PIString & name) const { PIString PIObject::methodEHFullFormat(const PIString & name) const {
PIMutexLocker ml(__meta_mutex()); PIMutexLocker ml(__meta_mutex());
__MetaData & ehd(__meta_data()[classNameID()]); const __MetaData & ehd(__meta_data()[classNameID()]);
piForeachC (__EHPair & eh, ehd.eh_func) for (auto eh = ehd.eh_func.constBegin(); eh != ehd.eh_func.constEnd(); eh++) {
if (eh.second.func_name == name) if (eh.value().func_name == name)
return eh.second.fullFormat(); return eh.value().fullFormat();
}
return PIString(); return PIString();
} }
@@ -234,10 +237,11 @@ PIString PIObject::methodEHFromAddr(const void * addr) const {
PIVector<PIObject::__MetaFunc> PIObject::findEH(const PIString & name) const { PIVector<PIObject::__MetaFunc> PIObject::findEH(const PIString & name) const {
PIVector<__MetaFunc> ret; PIVector<__MetaFunc> ret;
__MetaData & ehd(__meta_data()[classNameID()]); const __MetaData & ehd(__meta_data()[classNameID()]);
piForeachC (__EHPair & eh, ehd.eh_func) for (auto eh = ehd.eh_func.constBegin(); eh != ehd.eh_func.constEnd(); eh++) {
if (eh.second.func_name == name) if (eh.value().func_name == name)
ret << eh.second; ret << eh.value();
}
return ret; return ret;
} }
@@ -582,11 +586,11 @@ void PIObject::dump(const PIString & line_prefix) const {
//printf("dump %d properties ok\n", properties_.size()); //printf("dump %d properties ok\n", properties_.size());
PICout(PICoutManipulators::AddNewLine) << line_prefix << " }"; PICout(PICoutManipulators::AddNewLine) << line_prefix << " }";
PICout(PICoutManipulators::AddNewLine) << line_prefix << " methods {"; PICout(PICoutManipulators::AddNewLine) << line_prefix << " methods {";
__MetaData & ehd(__meta_data()[classNameID()]); const __MetaData & ehd(__meta_data()[classNameID()]);
PICout(PICoutManipulators::AddNewLine) << line_prefix << " count: " << ehd.eh_func.size_s(); PICout(PICoutManipulators::AddNewLine) << line_prefix << " count: " << ehd.eh_func.size_s();
//printf("dump %d methods\n", ehd.eh_func.size()); //printf("dump %d methods\n", ehd.eh_func.size());
piForeachC (__EHPair & eh, ehd.eh_func) { for (auto eh = ehd.eh_func.constBegin(); eh != ehd.eh_func.constEnd(); eh++) {
PICout(PICoutManipulators::AddNewLine) << line_prefix << " " << eh.second.fullFormat(); PICout(PICoutManipulators::AddNewLine) << line_prefix << " " << eh.value().fullFormat();
} }
//printf("dump %d methods ok\n", ehd.eh_func.size()); //printf("dump %d methods ok\n", ehd.eh_func.size());
PICout(PICoutManipulators::AddNewLine) << line_prefix << " }"; PICout(PICoutManipulators::AddNewLine) << line_prefix << " }";

View File

@@ -800,7 +800,7 @@ public:
static bool isTypeOf(const void * o) {return isTypeOf<T>((PIObject*)o);} static bool isTypeOf(const void * o) {return isTypeOf<T>((PIObject*)o);}
static PIString simplifyType(const char * a); static PIString simplifyType(const char * a);
struct __MetaFunc { struct PIP_EXPORT __MetaFunc {
__MetaFunc(): addr(0), addrV(0) {;} __MetaFunc(): addr(0), addrV(0) {;}
bool isNull() const {return addr == 0;} bool isNull() const {return addr == 0;}
PIString arguments() const; PIString arguments() const;
@@ -813,7 +813,7 @@ public:
PIStringList types; PIStringList types;
PIStringList names; PIStringList names;
}; };
struct __MetaData { struct PIP_EXPORT __MetaData {
__MetaData() {scope_list << PIStringAscii("PIObject"); scope_id << PIStringAscii("PIObject").hash();} __MetaData() {scope_list << PIStringAscii("PIObject"); scope_id << PIStringAscii("PIObject").hash();}
void addScope(const PIString & s, uint shash); void addScope(const PIString & s, uint shash);
PIStringList scope_list; PIStringList scope_list;
@@ -919,7 +919,7 @@ private:
}; };
void dumpApplication(); PIP_EXPORT void dumpApplication();
bool dumpApplicationToFile(const PIString & path); PIP_EXPORT bool dumpApplicationToFile(const PIString & path);
#endif // PIOBJECT_H #endif // PIOBJECT_H

View File

@@ -32,14 +32,14 @@
* contains unique name and you can identify property by name with propertyValueByName(), propertyByName(). * contains unique name and you can identify property by name with propertyValueByName(), propertyByName().
* You can add property using addProperty(const Property&), addProperty(const PIString&, const PIVariant&, const PIString&, int). * You can add property using addProperty(const Property&), addProperty(const PIString&, const PIVariant&, const PIString&, int).
*/ */
class PIPropertyStorage { class PIP_EXPORT PIPropertyStorage {
public: public:
PIPropertyStorage() {} PIPropertyStorage() {}
/** /**
* @brief PIPropertyStorage element. * @brief PIPropertyStorage element.
*/ */
struct Property { struct PIP_EXPORT Property {
Property(const PIString & n = PIString(), const PIString & c = PIString(), const PIVariant & v = PIVariant(), int f = 0): Property(const PIString & n = PIString(), const PIString & c = PIString(), const PIVariant & v = PIVariant(), int f = 0):
name(n), comment(c), value(v), flags(f) {} name(n), comment(c), value(v), flags(f) {}

View File

@@ -173,7 +173,7 @@ PIString PIString::dtos(const double num, char format, int precision) {
PIString PIString::fromNumberBaseS(const llong value, int base, bool * ok) { PIString PIString::fromNumberBaseS(const llong value, int base, bool * ok) {
if (value == 0LL) return PIString("0"); if (value == 0LL) return PIString('0');
if (base < 2 || base > 40) {if (ok != 0) *ok = false; return PIString();} if (base < 2 || base > 40) {if (ok != 0) *ok = false; return PIString();}
if (ok != 0) *ok = true; if (ok != 0) *ok = true;
if (base == 10) return lltos(value); if (base == 10) return lltos(value);
@@ -192,7 +192,7 @@ PIString PIString::fromNumberBaseS(const llong value, int base, bool * ok) {
} }
PIString PIString::fromNumberBaseU(const ullong value, int base, bool * ok) { PIString PIString::fromNumberBaseU(const ullong value, int base, bool * ok) {
if (value == 0ULL) return PIString("0"); if (value == 0ULL) return PIString('0');
if (base < 2 || base > 40) {if (ok != 0) *ok = false; return PIString();} if (base < 2 || base > 40) {if (ok != 0) *ok = false; return PIString();}
if (ok != 0) *ok = true; if (ok != 0) *ok = true;
if (base == 10) return ulltos(value); if (base == 10) return ulltos(value);
@@ -211,9 +211,10 @@ PIString PIString::fromNumberBaseU(const ullong value, int base, bool * ok) {
llong PIString::toNumberBase(const PIString & value, int base, bool * ok) { llong PIString::toNumberBase(const PIString & value, int base, bool * ok) {
static const PIString s_0x = PIStringAscii("0x");
PIString v = value.trimmed(); PIString v = value.trimmed();
if (base < 0) { if (base < 0) {
int ind = v.find("0x"); int ind = v.find(s_0x);
if (ind == 0 || ind == 1) {v.remove(ind, 2); base = 16;} if (ind == 0 || ind == 1) {v.remove(ind, 2); base = 16;}
else base = 10; else base = 10;
} else } else
@@ -254,6 +255,7 @@ void PIString::appendFromChars(const char * c, int s, const char * codepage) {
int sz = ucnv_toUChars(cc, ucs, s, c, s, &e); int sz = ucnv_toUChars(cc, ucs, s, c, s, &e);
//printf("appendFromChars %d -> %d\n", s, sz); //printf("appendFromChars %d -> %d\n", s, sz);
//printf("PIString %d -> %d\n", c[0], ucs[0]); //printf("PIString %d -> %d\n", c[0], ucs[0]);
reserve(size_s() + sz);
for (int i = 0; i < sz; ++i) for (int i = 0; i < sz; ++i)
push_back(PIChar(ucs[i])); push_back(PIChar(ucs[i]));
delete[] ucs; delete[] ucs;
@@ -264,11 +266,9 @@ void PIString::appendFromChars(const char * c, int s, const char * codepage) {
# ifdef WINDOWS # ifdef WINDOWS
sz = MultiByteToWideChar((uint)(uintptr_t)codepage, MB_ERR_INVALID_CHARS, c, s, 0, 0); sz = MultiByteToWideChar((uint)(uintptr_t)codepage, MB_ERR_INVALID_CHARS, c, s, 0, 0);
if (sz <= 0) return; if (sz <= 0) return;
wchar_t * buffer = new wchar_t[sz]; int old_sz = size_s();
MultiByteToWideChar((uint)(uintptr_t)codepage, MB_ERR_INVALID_CHARS, c, s, buffer, sz); enlarge(sz);
for (int i = 0; i < sz; ++i) MultiByteToWideChar((uint)(uintptr_t)codepage, MB_ERR_INVALID_CHARS, c, s, (LPWSTR)PIDeque<PIChar>::data(old_sz), sz);
push_back(PIChar((ushort)buffer[i]));
delete[] buffer;
return; return;
//printf("request %d\n", sz); //printf("request %d\n", sz);
# else # else
@@ -330,9 +330,14 @@ PIString PIString::fromAscii(const char * s) {
PIString ret; PIString ret;
int l = 0; int l = 0;
while (s[l] != '\0') { while (s[l] != '\0') {
ret.push_back(PIChar(short(s[l]))); ret.push_back(PIChar(s[l]));
++l; ++l;
} }
/*while (s[l] != '\0') ++l;
PIString ret;
ret.resize(l);
for (int i = 0; i < l; ++i)
ret[i] = s[i];*/
return ret; return ret;
} }
@@ -369,6 +374,7 @@ void PIString::buildData(const char * cp) const {
UConverter * cc = ucnv_open(cp, &e); UConverter * cc = ucnv_open(cp, &e);
if (cc) { if (cc) {
char uc[8]; char uc[8];
data_.reserve(size_s());
for (int i = 0; i < size_s(); ++i) { for (int i = 0; i < size_s(); ++i) {
if (at(i).isAscii()) if (at(i).isAscii())
data_.push_back(uchar(at(i).unicode16Code())); data_.push_back(uchar(at(i).unicode16Code()));
@@ -605,16 +611,18 @@ PIString PIString::trimmed() const {
PIString & PIString::replace(int from, int count, const PIString & with) { PIString & PIString::replace(int from, int count, const PIString & with) {
if (count < length() - from) remove(from, count); count = piMini(count, length() - from);
else remove(from, length() - from); if (count == with.size_s())
uint c = with.length(); memcpy(&(at(from)), &(with.at(0)), count * sizeof(PIChar));
for (uint i = 0; i < c; ++i) insert(from + i, with[i]); else {
remove(from, count);
PIDeque<PIChar>::insert(from, with);
}
return *this; return *this;
} }
PIString & PIString::replace(const PIString & what, const PIString & with, bool * ok) { PIString & PIString::replace(const PIString & what, const PIString & with, bool * ok) {
//piCout << "replace" << what << with;
if (what.isEmpty()) { if (what.isEmpty()) {
if (ok != 0) *ok = false; if (ok != 0) *ok = false;
return *this; return *this;
@@ -628,8 +636,73 @@ PIString & PIString::replace(const PIString & what, const PIString & with, bool
PIString & PIString::replaceAll(const PIString & what, const PIString & with) { PIString & PIString::replaceAll(const PIString & what, const PIString & with) {
if (what.isEmpty() || what == with) return *this; if (what.isEmpty() || what == with) return *this;
bool ok = true; if (with.isEmpty()) removeAll(what);
while (ok) replace(what, with, &ok); else {
int l = what.length(), dl = with.length() - what.length();
for (int i = 0; i < length() - l + 1; ++i) {
bool match = true;
for (int j = 0; j < l; ++j) {
if (at(j + i) != what[j]) {
match = false;
break;
}
}
if (!match) continue;
if (dl > 0) PIDeque<PIChar>::insert(i, PIDeque<PIChar>((size_t)dl));
if (dl < 0) PIDeque<PIChar>::remove(i, -dl);
memcpy(PIDeque<PIChar>::data(i), &(with.at(0)), with.length() * sizeof(PIChar));
//i -= l;
}
}
return *this;
}
PIString & PIString::replaceAll(const PIString & what, const char with) {
if (what.isEmpty()) return *this;
int l = what.length(), dl = what.length() - 1;
for (int i = 0; i < length() - l + 1; ++i) {
bool match = true;
for (int j = 0; j < l; ++j) {
if (at(j + i) != what[j]) {
match = false;
break;
}
}
if (!match) continue;
if (dl > 0) PIDeque<PIChar>::remove(i, dl);
at(i) = PIChar(with);
//i -= l;
}
return *this;
}
PIString & PIString::replaceAll(const char what, const char with) {
int l = length();
for (int i = 0; i < l; ++i) {
if (at(i) == what)
at(i) = with;
}
return *this;
}
PIString & PIString::removeAll(const PIString & str) {
if (str.isEmpty()) return *this;
int l = str.length();
for (int i = 0; i < length() - l + 1; ++i) {
bool match = true;
for (int j = 0; j < l; ++j) {
if (at(j + i) != str[j]) {
match = false;
break;
}
}
if (!match) continue;
PIDeque<PIChar>::remove(i, l);
i -= l;
}
return *this; return *this;
} }
@@ -641,16 +714,17 @@ PIString & PIString::insert(int index, const PIString & str) {
PIString & PIString::elide(int size, float pos) { PIString & PIString::elide(int size, float pos) {
static const PIString s_dotdot = PIStringAscii("..");
if (length() <= size) return *this; if (length() <= size) return *this;
if (length() <= 2) { if (length() <= 2) {
fill("."); fill('.');
return *this; return *this;
} }
pos = piClampf(pos, 0.f, 1.f); pos = piClampf(pos, 0.f, 1.f);
int ns = size - 2; int ns = size - 2;
int ls = piRoundf(ns * pos); int ls = piRoundf(ns * pos);
remove(ls, length() - ns); remove(ls, length() - ns);
insert(ls, ".."); insert(ls, s_dotdot);
return *this; return *this;
} }
@@ -670,9 +744,9 @@ PIStringList PIString::split(const PIString & delim) const {
} }
int PIString::find(const char str, const int start) const { int PIString::find(const char c, const int start) const {
for (int i = start; i < length(); ++i) for (int i = start; i < length(); ++i)
if (at(i) == str) if (at(i) == c)
return i; return i;
return -1; return -1;
} }
@@ -687,9 +761,9 @@ int PIString::find(const PIString & str, const int start) const {
} }
int PIString::findLast(const char str, const int start) const { int PIString::findLast(const char c, const int start) const {
for (int i = length() - 1; i >= start; --i) for (int i = length() - 1; i >= start; --i)
if (at(i) == str) if (at(i) == c)
return i; return i;
return -1; return -1;
} }
@@ -730,7 +804,7 @@ int PIString::findCWord(const PIString & word, const int start) const {
} }
int PIString::findRange(const PIChar & start, const PIChar & end, const PIChar & shield, const int start_index, int * len) const { int PIString::findRange(const PIChar start, const PIChar end, const PIChar shield, const int start_index, int * len) const {
if (len) *len = 0; if (len) *len = 0;
bool trim_ = (start != ' ' && start != '\t' && start != '\n' && start != '\r'), eq = (start == end); bool trim_ = (start != ' ' && start != '\t' && start != '\n' && start != '\r'), eq = (start == end);
int sz = size_s(), ls = -1, le = -1, cnt = 0; int sz = size_s(), ls = -1, le = -1, cnt = 0;
@@ -783,7 +857,7 @@ int PIString::findAnyLast(const PIString & str, const int start) const {
} }
int PIString::entries(const PIChar & c) const { int PIString::entries(const PIChar c) const {
int sz = size_s(), ret = 0; int sz = size_s(), ret = 0;
for (int i = 0; i < sz; ++i) for (int i = 0; i < sz; ++i)
if (at(i) == c) ++ret; if (at(i) == c) ++ret;
@@ -804,9 +878,14 @@ bool PIString::endsWith(const PIString & str) const {
bool PIString::toBool() const { bool PIString::toBool() const {
static const PIString s_true = PIStringAscii("true");
static const PIString s_yes = PIStringAscii("yes" );
static const PIString s_on = PIStringAscii("on" );
static const PIString s_ok = PIStringAscii("ok" );
PIString s(*this); PIString s(*this);
s = s.trimmed().toLowerCase(); s = s.trimmed().toLowerCase();
if ( atof(s.toNativeDecimalPoints().data()) > 0. || s == "true" || s == "yes" || s == "on" || s == "ok") return true; if (s == s_true || s == s_yes || s == s_on || s == s_ok) return true;
if (atof(s.toNativeDecimalPoints().data()) > 0.) return true;
return false; return false;
} }
@@ -953,7 +1032,7 @@ PIString PIString::takeNumber() {
} }
PIString PIString::takeRange(const PIChar & start, const PIChar & end, const PIChar & shield) { PIString PIString::takeRange(const PIChar start, const PIChar end, const PIChar shield) {
PIString ret; PIString ret;
bool trim_ = (start != ' ' && start != '\t' && start != '\n' && start != '\r'), eq = (start == end); bool trim_ = (start != ' ' && start != '\t' && start != '\n' && start != '\r'), eq = (start == end);
int sz = size_s(), ls = -1, le = -1, cnt = 0; int sz = size_s(), ls = -1, le = -1, cnt = 0;
@@ -991,7 +1070,7 @@ PIString PIString::takeRange(const PIChar & start, const PIChar & end, const PIC
} }
PIString PIString::inBrackets(const PIChar &start, const PIChar &end) const { PIString PIString::inBrackets(const PIChar start, const PIChar end) const {
int slen = length(); int slen = length();
int st = -1, bcnt = 0; int st = -1, bcnt = 0;
PIChar cc; PIChar cc;
@@ -1030,9 +1109,9 @@ PIString PIString::toNativeDecimalPoints() const {
#ifdef HAS_LOCALE #ifdef HAS_LOCALE
PIString s(*this); PIString s(*this);
if (currentLocale == 0) return s; if (currentLocale == 0) return s;
return s.replaceAll(".", currentLocale->decimal_point).replaceAll(",", currentLocale->decimal_point); return s.replaceAll('.', currentLocale->decimal_point).replaceAll(',', currentLocale->decimal_point);
#else #else
return PIString(*this).replaceAll(",", "."); return PIString(*this).replaceAll(',', '.');
#endif #endif
} }
@@ -1062,27 +1141,27 @@ ldouble PIString::toLDouble() const {
PIString & PIString::setReadableSize(llong bytes) { PIString & PIString::setReadableSize(llong bytes) {
clear(); clear();
if (bytes < 1024) {*this += (PIString::fromNumber(bytes) + " B"); return *this;} if (bytes < 1024) {*this += (PIString::fromNumber(bytes) + PIStringAscii(" B")); return *this;}
double fres = bytes / 1024.; double fres = bytes / 1024.;
llong res = bytes / 1024; llong res = bytes / 1024;
fres -= res; fres -= res;
if (res < 1024) {*this += (PIString::fromNumber(res) + "." + PIString::fromNumber(llong(fres * 10)).left(1) + " kB"); return *this;} if (res < 1024) {*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" kB")); return *this;}
fres = res / 1024.; fres = res / 1024.;
res /= 1024; res /= 1024;
fres -= res; fres -= res;
if (res < 1024) {*this += (PIString::fromNumber(res) + "." + PIString::fromNumber(llong(fres * 10)).left(1) + " MB"); return *this;} if (res < 1024) {*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" MB")); return *this;}
fres = res / 1024.; fres = res / 1024.;
res /= 1024; res /= 1024;
fres -= res; fres -= res;
if (res < 1024) {*this += (PIString::fromNumber(res) + "." + PIString::fromNumber(llong(fres * 10)).left(1) + " GB"); return *this;} if (res < 1024) {*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" GB")); return *this;}
fres = res / 1024.; fres = res / 1024.;
res /= 1024; res /= 1024;
fres -= res; fres -= res;
if (res < 1024) {*this += (PIString::fromNumber(res) + "." + PIString::fromNumber(llong(fres * 10)).left(1) + " TB"); return *this;} if (res < 1024) {*this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" TB")); return *this;}
fres = res / 1024.; fres = res / 1024.;
res /= 1024; res /= 1024;
fres -= res; fres -= res;
*this += (PIString::fromNumber(res) + "." + PIString::fromNumber(llong(fres * 10)).left(1) + " PB"); *this += (PIString::fromNumber(res) + PIStringAscii(".") + PIString::fromNumber(llong(fres * 10)).left(1) + PIStringAscii(" PB"));
return *this; return *this;
} }
@@ -1110,14 +1189,14 @@ void parseVersion(PIString s, PIVector<int> & codes, PIStringList & strs) {
} }
int mccnt = 2 - s.entries('.'); int mccnt = 2 - s.entries('.');
if (mccnt > 0) { if (mccnt > 0) {
int ind = s.findLast(".") + 1; int ind = s.findLast('.') + 1;
while (!_versionDelims_.contains(s[ind])) { while (!_versionDelims_.contains(s[ind])) {
++ind; ++ind;
if (ind > s.size_s() - 1) if (ind > s.size_s() - 1)
break; break;
} }
for (int i = 0; i < mccnt; ++i) for (int i = 0; i < mccnt; ++i)
s.insert(ind, ".0"); s.insert(ind, PIStringAscii(".0"));
} }
PIStringList comps; PIStringList comps;
while (!s.isEmpty()) { while (!s.isEmpty()) {
@@ -1132,7 +1211,7 @@ void parseVersion(PIString s, PIVector<int> & codes, PIStringList & strs) {
} }
for (int i = 0; i < comps.size_s(); ++i) { for (int i = 0; i < comps.size_s(); ++i) {
if (comps[i].isEmpty()) if (comps[i].isEmpty())
comps[i] = "0"; comps[i] = '0';
bool ok = false; bool ok = false;
int val = comps[i].toInt(-1, &ok); int val = comps[i].toInt(-1, &ok);
if (ok) { if (ok) {
@@ -1148,20 +1227,20 @@ void parseVersion(PIString s, PIVector<int> & codes, PIStringList & strs) {
int versionLabelValue(PIString s) { int versionLabelValue(PIString s) {
int ret = -10000; int ret = -10000;
if (s.isEmpty()) return 0; if (s.isEmpty()) return 0;
if (s.startsWith("pre")) { if (s.startsWith(PIStringAscii("pre"))) {
s.cutLeft(3); s.cutLeft(3);
ret -= 1; ret -= 1;
} }
if (s.startsWith("rc")) { if (s.startsWith(PIStringAscii("rc"))) {
s.cutLeft(2); s.cutLeft(2);
ret += s.toInt(); ret += s.toInt();
} }
if (s.startsWith("r")) { if (s.startsWith(PIStringAscii("r"))) {
s.cutLeft(1); s.cutLeft(1);
ret += 10000 + s.toInt(); ret += 10000 + s.toInt();
} }
if (s == "alpha") ret -= 4; if (s == PIStringAscii("alpha")) ret -= 4;
if (s == "beta" ) ret -= 2; if (s == PIStringAscii("beta" )) ret -= 2;
return ret; return ret;
} }
@@ -1200,13 +1279,13 @@ PIString versionNormalize(const PIString & v) {
PIString ret; PIString ret;
for (int i = 0; i < codes.size_s(); ++i) { for (int i = 0; i < codes.size_s(); ++i) {
if (i > 0) { if (i > 0) {
if (i < 3) ret += "."; if (i < 3) ret += '.';
else ret += "-"; else ret += '-';
} }
ret += PIString::fromNumber(codes[i]); ret += PIString::fromNumber(codes[i]);
} }
for (int i = 0; i < strs.size_s(); ++i) { for (int i = 0; i < strs.size_s(); ++i) {
ret += "_"; ret += '_';
ret += strs[i]; ret += strs[i];
} }
return ret; return ret;

View File

@@ -43,17 +43,20 @@ public:
static const float ElideCenter; static const float ElideCenter;
static const float ElideRight ; static const float ElideRight ;
PIString & operator +=(const PIChar & c) {push_back(c); return *this;} PIString & operator +=(const PIChar c) {push_back(c); return *this;}
PIString & operator +=(const char c) {push_back(PIChar(c)); return *this;}
PIString & operator +=(const char * str); PIString & operator +=(const char * str);
PIString & operator +=(const wchar_t * str); PIString & operator +=(const wchar_t * str);
PIString & operator +=(const PIByteArray & ba) {appendFromChars((const char * )ba.data(), ba.size_s(), __utf8name__); return *this;} PIString & operator +=(const PIByteArray & ba) {appendFromChars((const char * )ba.data(), ba.size_s(), __utf8name__); return *this;}
PIString & operator +=(const PIString & str); PIString & operator +=(const PIString & str);
PIString(const PIString & o): PIDeque<PIChar>() {*this += o;} PIString(const PIString & o): PIDeque<PIChar>(o) {}
PIString(PIString && o): PIDeque<PIChar>(std::move(o)) {}
//! Contructs string with single symbol "c" //! Contructs string with single symbol "c"
PIString(const PIChar & c): PIDeque<PIChar>() {*this += c;} PIString(const PIChar c): PIDeque<PIChar>() {*this += c;}
PIString(const char c): PIDeque<PIChar>() {*this += PIChar(c);} PIString(const char c): PIDeque<PIChar>() {*this += PIChar(c);}
/*! \brief Contructs string from c-string "str" /*! \brief Contructs string from c-string "str"
@@ -82,13 +85,15 @@ public:
/*! \brief Contructs string as sequence of symbols "c" of buffer with length "len" /*! \brief Contructs string as sequence of symbols "c" of buffer with length "len"
* \details Example: \snippet pistring.cpp PIString(int, PIChar) */ * \details Example: \snippet pistring.cpp PIString(int, PIChar) */
PIString(const int len, const PIChar & c): PIDeque<PIChar>() {for (int i = 0; i < len; ++i) push_back(c);} PIString(const int len, const PIChar c): PIDeque<PIChar>() {for (int i = 0; i < len; ++i) push_back(c);}
~PIString() {} ~PIString() {}
PIString & operator =(const PIString & o) {if (this == &o) return *this; clear(); *this += o; return *this;} PIString & operator =(const PIString & o) {if (this == &o) return *this; clear(); *this += o; return *this;}
PIString & operator =(PIString && o) {swap(o); return *this;}
/*! \brief Return c-string representation of string /*! \brief Return c-string representation of string
* \details Converts content of string to c-string and return * \details Converts content of string to c-string and return
* pointer to first char. This buffer is valid until new convertion * pointer to first char. This buffer is valid until new convertion
@@ -106,7 +111,7 @@ public:
bool operator ==(const PIString & str) const; bool operator ==(const PIString & str) const;
//! Compare operator //! Compare operator
bool operator ==(const PIChar c) const {return *this == PIString(c);} bool operator ==(const PIChar c) const {if (size_s() != 1) return false; return at(0) == c;}
//! Compare operator //! Compare operator
bool operator ==(const char * str) const {return *this == PIString(str);} bool operator ==(const char * str) const {return *this == PIString(str);}
@@ -115,7 +120,7 @@ public:
bool operator !=(const PIString & str) const; bool operator !=(const PIString & str) const;
//! Compare operator //! Compare operator
bool operator !=(const PIChar c) const {return *this != PIString(c);} bool operator !=(const PIChar c) const {if (size_s() != 1) return true; return at(0) != c;}
//! Compare operator //! Compare operator
bool operator !=(const char * str) const {return *this != PIString(str);} bool operator !=(const char * str) const {return *this != PIString(str);}
@@ -124,7 +129,7 @@ public:
bool operator <(const PIString & str) const; bool operator <(const PIString & str) const;
//! Compare operator //! Compare operator
bool operator <(const PIChar c) const {return *this < PIString(c);} bool operator <(const PIChar c) const {if (size_s() != 1) return size_s() < 1; return at(0) < c;}
//! Compare operator //! Compare operator
bool operator <(const char * str) const {return *this < PIString(str);} bool operator <(const char * str) const {return *this < PIString(str);}
@@ -133,7 +138,7 @@ public:
bool operator >(const PIString & str) const; bool operator >(const PIString & str) const;
//! Compare operator //! Compare operator
bool operator >(const PIChar c) const {return *this > PIString(c);} bool operator >(const PIChar c) const {if (size_s() != 1) return size_s() > 1; return at(0) > c;}
//! Compare operator //! Compare operator
bool operator >(const char * str) const {return *this > PIString(str);} bool operator >(const char * str) const {return *this > PIString(str);}
@@ -142,7 +147,7 @@ public:
bool operator <=(const PIString & str) const {return !(*this > str);} bool operator <=(const PIString & str) const {return !(*this > str);}
//! Compare operator //! Compare operator
bool operator <=(const PIChar c) const {return *this <= PIString(c);} bool operator <=(const PIChar c) const {return !(*this > c);}
//! Compare operator //! Compare operator
bool operator <=(const char * str) const {return *this <= PIString(str);} bool operator <=(const char * str) const {return *this <= PIString(str);}
@@ -151,7 +156,7 @@ public:
bool operator >=(const PIString & str) const {return !(*this < str);} bool operator >=(const PIString & str) const {return !(*this < str);}
//! Compare operator //! Compare operator
bool operator >=(const PIChar c) const {return *this >= PIString(c);} bool operator >=(const PIChar c) const {return !(*this < c);}
//! Compare operator //! Compare operator
bool operator >=(const char * str) const {return *this >= PIString(str);} bool operator >=(const char * str) const {return *this >= PIString(str);}
@@ -162,7 +167,11 @@ public:
/*! \brief Append symbol "c" at the end of string /*! \brief Append symbol "c" at the end of string
* \details Example: \snippet pistring.cpp PIString::<<(PIChar) */ * \details Example: \snippet pistring.cpp PIString::<<(PIChar) */
PIString & operator <<(const PIChar & c) {*this += c; return *this;} PIString & operator <<(const PIChar c) {*this += c; return *this;}
/*! \brief Append symbol "c" at the end of string
* \details Example: \snippet pistring.cpp PIString::<<(PIChar) */
PIString & operator <<(const char c) {*this += PIChar(c); return *this;}
/*! \brief Append c-string "str" at the end of string /*! \brief Append c-string "str" at the end of string
* \details Example: \snippet pistring.cpp PIString::<<(char * ) */ * \details Example: \snippet pistring.cpp PIString::<<(char * ) */
@@ -177,11 +186,6 @@ public:
PIString & operator <<(const int & num) {*this += PIString::fromNumber(num); return *this;} PIString & operator <<(const int & num) {*this += PIString::fromNumber(num); return *this;}
PIString & operator <<(const uint & num) {*this += PIString::fromNumber(num); return *this;} PIString & operator <<(const uint & num) {*this += PIString::fromNumber(num); return *this;}
/*! \brief Append string representation of "num" at the end of string
* \details Example: \snippet pistring.cpp PIString::<<(int) */
PIString & operator <<(const short & num) {*this += PIString::fromNumber(num); return *this;}
PIString & operator <<(const ushort & num) {*this += PIString::fromNumber(num); return *this;}
/*! \brief Append string representation of "num" at the end of string /*! \brief Append string representation of "num" at the end of string
* \details Example: \snippet pistring.cpp PIString::<<(int) */ * \details Example: \snippet pistring.cpp PIString::<<(int) */
PIString & operator <<(const long & num) {*this += PIString::fromNumber(num); return *this;} PIString & operator <<(const long & num) {*this += PIString::fromNumber(num); return *this;}
@@ -278,7 +282,24 @@ public:
* \details Example: \snippet pistring.cpp PIString::replaceAll * \details Example: \snippet pistring.cpp PIString::replaceAll
* \sa \a replace(), \a replaced() */ * \sa \a replace(), \a replaced() */
PIString & replaceAll(const PIString & what, const PIString & with); PIString & replaceAll(const PIString & what, const PIString & with);
PIString replaceAll(const PIString & what, const PIString & with) const {PIString str(*this); str.replaceAll(what, with); return str;}
/*! \brief Replace all founded substrings "what" with symbol "with" and return this string
* \details Example: \snippet pistring.cpp PIString::replaceAll
* \sa \a replace(), \a replaced() */
PIString & replaceAll(const PIString & what, const char with);
/*! \brief Replace all founded symbols "what" with symbol "with" and return this string
* \details Example: \snippet pistring.cpp PIString::replaceAll
* \sa \a replace(), \a replaced() */
PIString & replaceAll(const char what, const char with);
PIString replacedAll(const PIString & what, const PIString & with) const {PIString str(*this); str.replaceAll(what, with); return str;}
PIString replacedAll(const char what, const char with) const {PIString str(*this); str.replaceAll(what, with); return str;}
PIString & removeAll(const PIString & str);
PIString & removeAll(char c) {PIDeque<PIChar>::removeAll(PIChar(c)); return *this;}
/*! \brief Repeat content of string "times" times and return this string /*! \brief Repeat content of string "times" times and return this string
* \details Example: \snippet pistring.cpp PIString::repeat */ * \details Example: \snippet pistring.cpp PIString::repeat */
@@ -290,11 +311,11 @@ public:
/*! \brief Insert symbol "c" after index "index" and return this string /*! \brief Insert symbol "c" after index "index" and return this string
* \details Example: \snippet pistring.cpp PIString::insert_0 */ * \details Example: \snippet pistring.cpp PIString::insert_0 */
PIString & insert(const int index, const PIChar & c) {PIDeque<PIChar>::insert(index, c); return *this;} PIString & insert(const int index, const PIChar c) {PIDeque<PIChar>::insert(index, c); return *this;}
/*! \brief Insert symbol "c" after index "index" and return this string /*! \brief Insert symbol "c" after index "index" and return this string
* \details Example: \snippet pistring.cpp PIString::insert_1 */ * \details Example: \snippet pistring.cpp PIString::insert_1 */
PIString & insert(const int index, const char & c) {return insert(index, PIChar(c));} PIString & insert(const int index, const char c) {return insert(index, PIChar(c));}
/*! \brief Insert string "str" after index "index" and return this string /*! \brief Insert string "str" after index "index" and return this string
* \details Example: \snippet pistring.cpp PIString::insert_2 */ * \details Example: \snippet pistring.cpp PIString::insert_2 */
@@ -308,13 +329,13 @@ public:
* "c" at the end of string, and return this string * "c" at the end of string, and return this string
* \details Example: \snippet pistring.cpp PIString::expandRightTo * \details Example: \snippet pistring.cpp PIString::expandRightTo
* \sa \a expandLeftTo() */ * \sa \a expandLeftTo() */
PIString & expandRightTo(const int len, const PIChar & c) {if (len > length()) resize(len, c); return *this;} PIString & expandRightTo(const int len, const PIChar c) {if (len > length()) resize(len, c); return *this;}
/*! \brief Enlarge string to length "len" by addition sequence of symbols /*! \brief Enlarge string to length "len" by addition sequence of symbols
* "c" at the beginning of string, and return this string * "c" at the beginning of string, and return this string
* \details Example: \snippet pistring.cpp PIString::expandLeftTo * \details Example: \snippet pistring.cpp PIString::expandLeftTo
* \sa \a expandRightTo() */ * \sa \a expandRightTo() */
PIString & expandLeftTo(const int len, const PIChar & c) {if (len > length()) insert(0, PIString(len - length(), c)); return *this;} PIString & expandLeftTo(const int len, const PIChar c) {if (len > length()) insert(0, PIString(len - length(), c)); return *this;}
/*! \brief Add "c" symbols at the beginning and end of the string, and return this string /*! \brief Add "c" symbols at the beginning and end of the string, and return this string
* \sa \a quoted() */ * \sa \a quoted() */
@@ -327,7 +348,7 @@ public:
/*! \brief Reverse string and return this string /*! \brief Reverse string and return this string
* \details Example: \snippet pistring.cpp PIString::reverse * \details Example: \snippet pistring.cpp PIString::reverse
* \sa \a reversed() */ * \sa \a reversed() */
PIString & reverse() {PIString str(*this); clear(); piForeachR (const PIChar & c, str) push_back(c); return *this;} PIString & reverse() {PIString str(*this); clear(); piForeachCR (PIChar c, str) push_back(c); return *this;}
/*! \brief Reverse copy of this string and return it /*! \brief Reverse copy of this string and return it
* \details Example: \snippet pistring.cpp PIString::reversed * \details Example: \snippet pistring.cpp PIString::reversed
@@ -390,13 +411,13 @@ public:
* \details "Shield" symbol prevent analysis of the next symbol. * \details "Shield" symbol prevent analysis of the next symbol.
* Example: \snippet pistring.cpp PIString::takeRange * Example: \snippet pistring.cpp PIString::takeRange
* \sa \a takeSymbol(), \a takeWord(), \a takeLine(), \a takeNumber() */ * \sa \a takeSymbol(), \a takeWord(), \a takeLine(), \a takeNumber() */
PIString takeRange(const PIChar & start, const PIChar & end, const PIChar & shield = '\\'); PIString takeRange(const PIChar start, const PIChar end, const PIChar shield = '\\');
/*! \brief Return a string in brackets "start" and "end" symbols from the begin of this /*! \brief Return a string in brackets "start" and "end" symbols from the begin of this
* string and return it. * string and return it.
* \details Example: string = "a(b(c)d)e"; inBrackets('(', ')') = "b(c)d"; */ * \details Example: string = "a(b(c)d)e"; inBrackets('(', ')') = "b(c)d"; */
PIString inBrackets(const PIChar & start, const PIChar & end) const; PIString inBrackets(const PIChar start, const PIChar end) const;
/*! \brief Return real bytes count of this string /*! \brief Return real bytes count of this string
* \details It`s equivalent length of char sequence * \details It`s equivalent length of char sequence
@@ -463,11 +484,8 @@ public:
PIString toNativeDecimalPoints() const; PIString toNativeDecimalPoints() const;
//! \brief Returns if string contains "str" //! \brief Returns if string contains "c"
bool contains(const char str) const {return contains(PIString(str));} bool contains(const char c) const {return PIDeque<PIChar>::contains(PIChar(c));}
//! \brief Returns if string contains "str"
bool contains(const PIChar str) const {return contains(PIString(str));}
//! \brief Returns if string contains "str" //! \brief Returns if string contains "str"
bool contains(const char * str) const {return contains(PIString(str));} bool contains(const char * str) const {return contains(PIString(str));}
@@ -476,9 +494,9 @@ public:
bool contains(const PIString & str) const {return find(str) >= 0;} bool contains(const PIString & str) const {return find(str) >= 0;}
//! \brief Search substring "str" from symbol at index "start" and return first occur position //! \brief Search symbol "c" from symbol at index "start" and return first occur position
//! \details Example: \snippet pistring.cpp PIString::find //! \details Example: \snippet pistring.cpp PIString::find
int find(const char str, const int start = 0) const; int find(const char c, const int start = 0) const;
//! \brief Search substring "str" from symbol at index "start" and return first occur position //! \brief Search substring "str" from symbol at index "start" and return first occur position
//! \details Example: \snippet pistring.cpp PIString::find //! \details Example: \snippet pistring.cpp PIString::find
@@ -488,9 +506,9 @@ public:
//! \details Example: \snippet pistring.cpp PIString::find //! \details Example: \snippet pistring.cpp PIString::find
int find(const char * str, const int start = 0) const {return find(PIString(str), start);} int find(const char * str, const int start = 0) const {return find(PIString(str), start);}
//! \brief Search substring "str" from symbol at index "start" and return last occur position //! \brief Search symbol "c" from symbol at index "start" and return last occur position
//! \details Example: \snippet pistring.cpp PIString::findLast //! \details Example: \snippet pistring.cpp PIString::findLast
int findLast(const char str, const int start = 0) const; int findLast(const char c, const int start = 0) const;
//! \brief Search substring "str" from symbol at index "start" and return last occur position //! \brief Search substring "str" from symbol at index "start" and return last occur position
//! \details Example: \snippet pistring.cpp PIString::findLast //! \details Example: \snippet pistring.cpp PIString::findLast
@@ -510,7 +528,7 @@ public:
//! \brief Search range between "start" and "end" symbols at index "start_index" and return first occur position. //! \brief Search range between "start" and "end" symbols at index "start_index" and return first occur position.
//! \details Example: \snippet pistring.cpp PIString::findRange //! \details Example: \snippet pistring.cpp PIString::findRange
int findRange(const PIChar & start, const PIChar & end, const PIChar & shield = '\\', const int start_index = 0, int * len = 0) const; int findRange(const PIChar start, const PIChar end, const PIChar shield = '\\', const int start_index = 0, int * len = 0) const;
//! \brief Search any symbol of "str" from symbol at index "start" and return first occur position //! \brief Search any symbol of "str" from symbol at index "start" and return first occur position
//! \details Example: \snippet pistring.cpp PIString::findAny //! \details Example: \snippet pistring.cpp PIString::findAny
@@ -529,7 +547,7 @@ public:
int findAnyLast(const char * str, const int start = 0) const {return findAnyLast(PIString(str), start);} int findAnyLast(const char * str, const int start = 0) const {return findAnyLast(PIString(str), start);}
//! \brief Returns number of occurrences of symbol "c" //! \brief Returns number of occurrences of symbol "c"
int entries(const PIChar & c) const; int entries(const PIChar c) const;
//! \brief Returns number of occurrences of symbol "c" //! \brief Returns number of occurrences of symbol "c"
int entries(char c) const {return entries(PIChar(c));} int entries(char c) const {return entries(PIChar(c));}
@@ -714,9 +732,6 @@ public:
//! \details Example: \snippet pistring.cpp PIString::readableSize //! \details Example: \snippet pistring.cpp PIString::readableSize
static PIString readableSize(llong bytes); static PIString readableSize(llong bytes);
PIString & removeAll(char v) {replaceAll(v, ""); return *this;}
PIString & removeAll(const PIString & v) {replaceAll(v, ""); return *this;}
private: private:
static const char toBaseN[]; static const char toBaseN[];
static const int fromBaseN[]; static const int fromBaseN[];
@@ -759,6 +774,12 @@ inline PIString operator +(const PIString & f, const char * str) {PIString s(f);
//! \relatesalso PIString \brief Return concatenated string //! \relatesalso PIString \brief Return concatenated string
inline PIString operator +(const char * str, const PIString & f) {return PIString(str) + f;} inline PIString operator +(const char * str, const PIString & f) {return PIString(str) + f;}
//! \relatesalso PIString \brief Return concatenated string
inline PIString operator +(const char c, const PIString & f) {return PIChar(c) + f;}
//! \relatesalso PIString \brief Return concatenated string
inline PIString operator +(const PIString & f, const char c) {return f + PIChar(c);}
inline char chrUpr(char c); inline char chrUpr(char c);
inline char chrLwr(char c); inline char chrLwr(char c);

View File

@@ -37,17 +37,22 @@ public:
//! Contructs strings list with one string "str" //! Contructs strings list with one string "str"
PIStringList(const PIString & str) {push_back(str);} PIStringList(const PIString & str) {push_back(str);}
PIStringList(PIString && str) {push_back(std::move(str));}
//! Contructs empty strings list with strings "s0" and "s1" //! Contructs empty strings list with strings "s0" and "s1"
PIStringList(const PIString & s0, const PIString & s1) {push_back(s0); push_back(s1);} PIStringList(const PIString & s0, const PIString & s1) {push_back(s0); push_back(s1);}
PIStringList(PIString && s0, PIString && s1) {push_back(std::move(s0)); push_back(std::move(s1));}
//! Contructs empty strings list with strings "s0", "s1" and "s2" //! Contructs empty strings list with strings "s0", "s1" and "s2"
PIStringList(const PIString & s0, const PIString & s1, const PIString & s2) {push_back(s0); push_back(s1); push_back(s2);} PIStringList(const PIString & s0, const PIString & s1, const PIString & s2) {push_back(s0); push_back(s1); push_back(s2);}
PIStringList(PIString && s0, PIString && s1, PIString && s2) {push_back(std::move(s0)); push_back(std::move(s1)); push_back(std::move(s2));}
//! Contructs empty strings list with strings "s0", "s1", "s2" and "s3" //! Contructs empty strings list with strings "s0", "s1", "s2" and "s3"
PIStringList(const PIString & s0, const PIString & s1, const PIString & s2, const PIString & s3) {push_back(s0); push_back(s1); push_back(s2); push_back(s3);} PIStringList(const PIString & s0, const PIString & s1, const PIString & s2, const PIString & s3) {push_back(s0); push_back(s1); push_back(s2); push_back(s3);}
PIStringList(PIString && s0, PIString && s1, PIString && s2, PIString && s3) {push_back(std::move(s0)); push_back(std::move(s1)); push_back(std::move(s2)); push_back(std::move(s3));}
PIStringList(const PIStringList & o): PIDeque<PIString>() {resize(o.size()); for (uint i = 0; i < size(); ++i) (*this)[i] = o[i];} PIStringList(const PIStringList & o): PIDeque<PIString>(o) {}
PIStringList(PIStringList && o): PIDeque<PIString>(std::move(o)) {}
PIStringList(const PIVector<PIString> & o): PIDeque<PIString>() {resize(o.size()); for (uint i = 0; i < size(); ++i) (*this)[i] = o[i];} PIStringList(const PIVector<PIString> & o): PIDeque<PIString>() {resize(o.size()); for (uint i = 0; i < size(); ++i) (*this)[i] = o[i];}
PIStringList(const PIDeque<PIString> & o): PIDeque<PIString>() {resize(o.size()); for (uint i = 0; i < size(); ++i) (*this)[i] = o[i];} PIStringList(const PIDeque<PIString> & o): PIDeque<PIString>() {resize(o.size()); for (uint i = 0; i < size(); ++i) (*this)[i] = o[i];}
@@ -83,6 +88,7 @@ public:
PIStringList & operator =(const PIStringList & o) {PIDeque<PIString>::operator=(o); return *this;} PIStringList & operator =(const PIStringList & o) {PIDeque<PIString>::operator=(o); return *this;}
PIStringList & operator <<(const PIString & str) {append(str); return *this;} PIStringList & operator <<(const PIString & str) {append(str); return *this;}
PIStringList & operator <<(PIString && str) {append(std::move(str)); return *this;}
PIStringList & operator <<(const PIStringList & sl) {append(sl); return *this;} PIStringList & operator <<(const PIStringList & sl) {append(sl); return *this;}
}; };

View File

@@ -39,7 +39,7 @@
template<typename T> template<typename T>
class PIP_EXPORT __PIVariantFunctions__ { class __PIVariantFunctions__ {
public: public:
static PIString typeNameHelper() {return PIStringAscii("");} static PIString typeNameHelper() {return PIStringAscii("");}
@@ -59,7 +59,7 @@ struct PIP_EXPORT __PIVariantInfo__ {
}; };
template<typename T> template<typename T>
struct PIP_EXPORT __PIVariantTypeInfo__ { struct __PIVariantTypeInfo__ {
typedef T PureType; typedef T PureType;
typedef const T ConstPureType; typedef const T ConstPureType;
typedef T * PointerType; typedef T * PointerType;
@@ -102,7 +102,7 @@ REGISTER_VARIANT_TYPEINFO(ns::classname)
#define REGISTER_VARIANT_CPP(classname) \ #define REGISTER_VARIANT_CPP(classname) \
template <typename T> \ template <typename T> \
class PIP_EXPORT __##classname##_PIVariantInitializer__ { \ class __##classname##_PIVariantInitializer__ { \
public: \ public: \
__##classname##_PIVariantInitializer__(const PIString & name) { \ __##classname##_PIVariantInitializer__(const PIString & name) { \
if (__PIVariantInfoStorage__::get()->map->contains(name)) \ if (__PIVariantInfoStorage__::get()->map->contains(name)) \
@@ -115,7 +115,7 @@ public: \
#define REGISTER_NS_VARIANT_CPP(ns, classname) \ #define REGISTER_NS_VARIANT_CPP(ns, classname) \
template <typename T> \ template <typename T> \
class PIP_EXPORT __##ns##classname##_PIVariantInitializer__ { \ class __##ns##classname##_PIVariantInitializer__ { \
public: \ public: \
__##ns##classname##_PIVariantInitializer__(const PIString & name) { \ __##ns##classname##_PIVariantInitializer__(const PIString & name) { \
if (__PIVariantInfoStorage__::get()->map->contains(name)) \ if (__PIVariantInfoStorage__::get()->map->contains(name)) \
@@ -155,7 +155,7 @@ PIByteArray __PIVariantFunctions__<classname_from>::castHelper<classname_to>(PIB
PIByteArray ret; ret << t; \ PIByteArray ret; ret << t; \
return ret;} \ return ret;} \
template <typename T, typename C> \ template <typename T, typename C> \
class PIP_EXPORT __##classname_from##_##classname_to##_PIVariantCastInitializer__ { \ class __##classname_from##_##classname_to##_PIVariantCastInitializer__ { \
public: \ public: \
__##classname_from##_##classname_to##_PIVariantCastInitializer__(const PIString & name, const PIString & cname) { \ __##classname_from##_##classname_to##_PIVariantCastInitializer__(const PIString & name, const PIString & cname) { \
__PIVariantInfo__ * vi(__PIVariantInfoStorage__::get()->map->value(name, 0)); \ __PIVariantInfo__ * vi(__PIVariantInfoStorage__::get()->map->value(name, 0)); \
@@ -206,7 +206,7 @@ class PIP_EXPORT PIVariant {
public: public:
//! Type of %PIVariant content //! Type of %PIVariant content
enum PIP_EXPORT Type { enum Type {
pivInvalid /** Invalid type , default type of empty contructor */ = 0 , pivInvalid /** Invalid type , default type of empty contructor */ = 0 ,
pivBool /** bool */ , pivBool /** bool */ ,
pivChar /** char */ , pivChar /** char */ ,

View File

@@ -23,11 +23,12 @@
#ifndef PIAUTH_H #ifndef PIAUTH_H
#define PIAUTH_H #define PIAUTH_H
#include "pip_crypt_export.h"
#include "piobject.h" #include "piobject.h"
#include "picrypt.h" #include "picrypt.h"
class PIP_EXPORT PIAuth : public PIObject class PIP_CRYPT_EXPORT PIAuth : public PIObject
{ {
PIOBJECT(PIAuth) PIOBJECT(PIAuth)
public: public:

View File

@@ -23,9 +23,10 @@
#ifndef PICRYPT_H #ifndef PICRYPT_H
#define PICRYPT_H #define PICRYPT_H
#include "pip_crypt_export.h"
#include "pistring.h" #include "pistring.h"
class PIP_EXPORT PICrypt { class PIP_CRYPT_EXPORT PICrypt {
public: public:
//! Construct and generate random key //! Construct and generate random key
PICrypt(); PICrypt();

View File

@@ -30,8 +30,7 @@ class PIP_EXPORT PIGeoPosition : public PIMathVectorT3d
{ {
public: public:
enum CoordinateSystem enum CoordinateSystem {
{
Unknown=0, /// Unknown coordinate system Unknown=0, /// Unknown coordinate system
Geodetic, /// Geodetic latitude, longitude, and height above ellipsoid Geodetic, /// Geodetic latitude, longitude, and height above ellipsoid
Geocentric, /// Geocentric (regular spherical coordinates) Geocentric, /// Geocentric (regular spherical coordinates)

View File

@@ -44,7 +44,7 @@ public:
PIVector<TypeInfo> getInfo() const; PIVector<TypeInfo> getInfo() const;
#pragma pack(push, 1) #pragma pack(push, 1)
struct _Type { struct PIP_EXPORT _Type {
_Type(); _Type();
uint id; uint id;
uint count; uint count;
@@ -54,7 +54,7 @@ public:
}; };
#pragma pack(pop) #pragma pack(pop)
struct TypeInfo: _Type { struct PIP_EXPORT TypeInfo: _Type {
PIString name; PIString name;
}; };
@@ -63,7 +63,7 @@ public:
mutable PIMutex mutex; mutable PIMutex mutex;
}; };
PIByteArray & operator <<(PIByteArray & s, const PIIntrospectionContainers::TypeInfo & v); PIP_EXPORT PIByteArray & operator <<(PIByteArray & s, const PIIntrospectionContainers::TypeInfo & v);
PIByteArray & operator >>(PIByteArray & s, PIIntrospectionContainers::TypeInfo & v); PIP_EXPORT PIByteArray & operator >>(PIByteArray & s, PIIntrospectionContainers::TypeInfo & v);
#endif // PIINTROSPECTION_CONTAINERS_P_H #endif // PIINTROSPECTION_CONTAINERS_P_H

View File

@@ -214,9 +214,10 @@ PIByteArray PIIntrospection::packThreads() {
if (p) { if (p) {
p->mutex.lock(); p->mutex.lock();
PIMap<PIThread*, PIIntrospectionThreads::ThreadInfo> & tm(p->threads); PIMap<PIThread*, PIIntrospectionThreads::ThreadInfo> & tm(p->threads);
for (PIMap<PIThread*, PIIntrospectionThreads::ThreadInfo>::iterator i = tm.begin(); i != tm.end(); ++i) { auto it = tm.makeIterator();
i.value().classname = PIStringAscii(i.key()->className()); while (it.next()) {
i.value().name = i.key()->name(); it.valueRef().classname = PIStringAscii(it.key()->className());
it.valueRef().name = it.key()->name();
} }
ret << tm.values(); ret << tm.values();
p->mutex.unlock(); p->mutex.unlock();

View File

@@ -27,7 +27,7 @@
#include "pisystemmonitor.h" #include "pisystemmonitor.h"
class PIIntrospection { class PIP_EXPORT PIIntrospection {
public: public:
enum InfoTypes { enum InfoTypes {
@@ -38,12 +38,12 @@ public:
itThreads = 0x10, itThreads = 0x10,
}; };
struct RequiredInfo { struct PIP_EXPORT RequiredInfo {
RequiredInfo(); RequiredInfo();
PIFlags<InfoTypes> types; PIFlags<InfoTypes> types;
}; };
struct ProcessInfo { struct PIP_EXPORT ProcessInfo {
ProcessInfo(); ProcessInfo();
PIString execCommand, hostname, user, OS_name, OS_version, architecture; PIString execCommand, hostname, user, OS_name, OS_version, architecture;
@@ -53,14 +53,14 @@ public:
PIStringList build_options; PIStringList build_options;
}; };
struct ProcessStat { struct PIP_EXPORT ProcessStat {
ProcessStat() {} ProcessStat() {}
PISystemMonitor::ProcessStats proc; PISystemMonitor::ProcessStats proc;
PIVector<PISystemMonitor::ThreadStats> threads; PIVector<PISystemMonitor::ThreadStats> threads;
}; };
struct ObjectInfo { struct PIP_EXPORT ObjectInfo {
ObjectInfo(); ObjectInfo();
PIString classname, name; PIString classname, name;
@@ -91,13 +91,13 @@ public:
}; };
PIByteArray & operator <<(PIByteArray & b, const PIIntrospection::RequiredInfo & v); PIP_EXPORT PIByteArray & operator <<(PIByteArray & b, const PIIntrospection::RequiredInfo & v);
PIByteArray & operator >>(PIByteArray & b, PIIntrospection::RequiredInfo & v); PIP_EXPORT PIByteArray & operator >>(PIByteArray & b, PIIntrospection::RequiredInfo & v);
PIByteArray & operator <<(PIByteArray & b, const PIIntrospection::ProcessInfo & v); PIP_EXPORT PIByteArray & operator <<(PIByteArray & b, const PIIntrospection::ProcessInfo & v);
PIByteArray & operator >>(PIByteArray & b, PIIntrospection::ProcessInfo & v); PIP_EXPORT PIByteArray & operator >>(PIByteArray & b, PIIntrospection::ProcessInfo & v);
PIByteArray & operator <<(PIByteArray & b, const PIIntrospection::ObjectInfo & v); PIP_EXPORT PIByteArray & operator <<(PIByteArray & b, const PIIntrospection::ObjectInfo & v);
PIByteArray & operator >>(PIByteArray & b, PIIntrospection::ObjectInfo & v); PIP_EXPORT PIByteArray & operator >>(PIByteArray & b, PIIntrospection::ObjectInfo & v);
#endif // PIINTROSPECTION_SERVER_P_H #endif // PIINTROSPECTION_SERVER_P_H

View File

@@ -35,7 +35,7 @@ public:
sWaiting, sWaiting,
}; };
struct ThreadInfo { struct PIP_EXPORT ThreadInfo {
ThreadInfo(); ThreadInfo();
PIString classname, name; PIString classname, name;
int id, delay; int id, delay;
@@ -57,7 +57,7 @@ public:
}; };
PIByteArray & operator <<(PIByteArray & b, const PIIntrospectionThreads::ThreadInfo & v); PIP_EXPORT PIByteArray & operator <<(PIByteArray & b, const PIIntrospectionThreads::ThreadInfo & v);
PIByteArray & operator >>(PIByteArray & b, PIIntrospectionThreads::ThreadInfo & v); PIP_EXPORT PIByteArray & operator >>(PIByteArray & b, PIIntrospectionThreads::ThreadInfo & v);
#endif // PIINTROSPECTION_THREADS_P_H #endif // PIINTROSPECTION_THREADS_P_H

View File

@@ -96,7 +96,7 @@ bool PIBinaryLog::openDevice() {
piForeachC(PIFile::FileInfo &i, es) { piForeachC(PIFile::FileInfo &i, es) {
if (i.extension() == "binlog" && i.isFile() && i.baseName().startsWith(filePrefix())) { if (i.extension() == "binlog" && i.isFile() && i.baseName().startsWith(filePrefix())) {
setPath(i.path); setPath(i.path);
piBreak; break;
} }
} }
} }

View File

@@ -56,7 +56,7 @@ public:
}; };
//! \brief Struct contains information about all records with same ID //! \brief Struct contains information about all records with same ID
struct BinLogRecordInfo { struct PIP_EXPORT BinLogRecordInfo {
BinLogRecordInfo() { BinLogRecordInfo() {
id = count = 0; id = count = 0;
minimum_size = maximum_size = 0; minimum_size = maximum_size = 0;
@@ -70,7 +70,7 @@ public:
}; };
//! \brief Struct contains full information about Binary Log file and about all Records using map of \a BinLogRecordInfo //! \brief Struct contains full information about Binary Log file and about all Records using map of \a BinLogRecordInfo
struct BinLogInfo { struct PIP_EXPORT BinLogInfo {
PIString path; PIString path;
int records_count; int records_count;
llong log_size; llong log_size;
@@ -80,7 +80,7 @@ public:
}; };
//! \brief Struct contains position, ID and timestamp of record in file //! \brief Struct contains position, ID and timestamp of record in file
struct BinLogIndex { struct PIP_EXPORT BinLogIndex {
int id; int id;
llong pos; llong pos;
PISystemTime timestamp; PISystemTime timestamp;
@@ -293,7 +293,7 @@ protected:
DeviceInfoFlags deviceInfoFlags() const {return PIIODevice::Reliable;} DeviceInfoFlags deviceInfoFlags() const {return PIIODevice::Reliable;}
private: private:
struct BinLogRecord { struct PIP_EXPORT BinLogRecord {
int id; int id;
int size; int size;
PISystemTime timestamp; PISystemTime timestamp;

View File

@@ -505,8 +505,8 @@ private:
#ifdef PIP_STD_IOSTREAM #ifdef PIP_STD_IOSTREAM
std::ostream & operator <<(std::ostream & s, const PIConfig::Branch & v); PIP_EXPORT std::ostream & operator <<(std::ostream & s, const PIConfig::Branch & v);
std::ostream & operator <<(std::ostream & s, const PIConfig::Entry & v); PIP_EXPORT std::ostream & operator <<(std::ostream & s, const PIConfig::Entry & v);
#endif #endif
inline PICout operator <<(PICout s, const PIConfig::Branch & v) {s.setControl(0, true); v.piCoutt(s, ""); s.restoreControl(); return s;} inline PICout operator <<(PICout s, const PIConfig::Branch & v) {s.setControl(0, true); v.piCoutt(s, ""); s.restoreControl(); return s;}

View File

@@ -43,7 +43,7 @@ public:
explicit PIEthernet(); explicit PIEthernet();
//! \brief Type of %PIEthernet //! \brief Type of %PIEthernet
enum PIP_EXPORT Type { enum Type {
UDP /** UDP - User Datagram Protocol */ , UDP /** UDP - User Datagram Protocol */ ,
TCP_Client /** TCP client - allow connection to TCP server */ , TCP_Client /** TCP client - allow connection to TCP server */ ,
TCP_Server /** TCP server - receive connections from TCP clients */ , TCP_Server /** TCP server - receive connections from TCP clients */ ,
@@ -51,7 +51,7 @@ public:
}; };
//! \brief Parameters of %PIEthernet //! \brief Parameters of %PIEthernet
enum PIP_EXPORT Parameters { enum Parameters {
ReuseAddress /** Rebind address if there is already binded. Enabled by default */ = 0x1, ReuseAddress /** Rebind address if there is already binded. Enabled by default */ = 0x1,
Broadcast /** Broadcast send. Disabled by default */ = 0x2, Broadcast /** Broadcast send. Disabled by default */ = 0x2,
SeparateSockets /** If this parameter is set, %PIEthernet will initialize two different sockets, SeparateSockets /** If this parameter is set, %PIEthernet will initialize two different sockets,
@@ -63,7 +63,7 @@ public:
//! \brief IPv4 network address, IP and port //! \brief IPv4 network address, IP and port
class Address { class PIP_EXPORT Address {
friend class PIEthernet; friend class PIEthernet;
friend inline PIByteArray & operator <<(PIByteArray & s, const PIEthernet::Address & v); friend inline PIByteArray & operator <<(PIByteArray & s, const PIEthernet::Address & v);
friend inline PIByteArray & operator >>(PIByteArray & s, PIEthernet::Address & v); friend inline PIByteArray & operator >>(PIByteArray & s, PIEthernet::Address & v);
@@ -322,7 +322,7 @@ public:
//! Flags of network interface //! Flags of network interface
enum PIP_EXPORT InterfaceFlag { enum InterfaceFlag {
ifActive /** Is active */ = 0x1, ifActive /** Is active */ = 0x1,
ifRunning /** Is running */ = 0x2, ifRunning /** Is running */ = 0x2,
ifBroadcast /** Support broadcast */ = 0x4, ifBroadcast /** Support broadcast */ = 0x4,
@@ -485,7 +485,7 @@ protected:
void applyTimeout(int fd, int opt, double ms); void applyTimeout(int fd, int opt, double ms);
void applyOptInt(int level, int opt, int val); void applyOptInt(int level, int opt, int val);
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_EXPORT)
int sock, sock_s; int sock, sock_s;
bool connected_, connecting_, listen_threaded, server_bounded; bool connected_, connecting_, listen_threaded, server_bounded;
mutable Address addr_r, addr_s, addr_lr; mutable Address addr_r, addr_s, addr_lr;

View File

@@ -235,7 +235,7 @@ PIByteArray PIFile::readAll(bool forceRead) {
llong s = size(); llong s = size();
if (s < 0) return a; if (s < 0) return a;
a.resize(s); a.resize(s);
s = readAll(a.data()); fread(a.data(), 1, s, PRIVATE->fd);
seek(cp); seek(cp);
if (s >= 0) a.resize(s); if (s >= 0) a.resize(s);
return a; return a;
@@ -593,7 +593,7 @@ void PIFile::setDefaultCharset(const char * c) {
PIFile::FileInfo PIFile::fileInfo(const PIString & path) { PIFile::FileInfo PIFile::fileInfo(const PIString & path) {
FileInfo ret; FileInfo ret;
if (path.isEmpty()) return ret; if (path.isEmpty()) return ret;
ret.path = path.replaceAll("\\", PIDir::separator); ret.path = path.replacedAll("\\", PIDir::separator);
PIString n = ret.name(); PIString n = ret.name();
//piCout << "open" << path; //piCout << "open" << path;
#ifdef WINDOWS #ifdef WINDOWS

View File

@@ -38,7 +38,7 @@ public:
struct PIP_EXPORT FileInfo { struct PIP_EXPORT FileInfo {
FileInfo() {size = 0; id_group = id_user = 0;} FileInfo() {size = 0; id_group = id_user = 0;}
enum PIP_EXPORT Flag { enum Flag {
File = 0x01, File = 0x01,
Dir = 0x02, Dir = 0x02,
Dot = 0x04, Dot = 0x04,
@@ -292,7 +292,7 @@ protected:
private: private:
PIString strType(const PIIODevice::DeviceMode type); PIString strType(const PIIODevice::DeviceMode type);
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_EXPORT)
int ret, prec_, fdi; int ret, prec_, fdi;
PIString prec_str; PIString prec_str;

View File

@@ -26,7 +26,7 @@
#include "pithread.h" #include "pithread.h"
class PIGPIO: public PIThread class PIP_EXPORT PIGPIO: public PIThread
{ {
PIOBJECT_SUBCLASS(PIGPIO, PIThread) PIOBJECT_SUBCLASS(PIGPIO, PIThread)
public: public:
@@ -85,7 +85,7 @@ public:
//! \} //! \}
private: private:
struct GPIOData { struct PIP_EXPORT GPIOData {
GPIOData() {dir = PIGPIO::In; num = fd = -1;} GPIOData() {dir = PIGPIO::In; num = fd = -1;}
PIString name; PIString name;
int dir; int dir;

View File

@@ -382,7 +382,7 @@ void PIIODevice::splitFullPath(PIString fpwm, PIString * full_path, DeviceMode *
int dm = 0; int dm = 0;
DeviceOptions op = 0; DeviceOptions op = 0;
if (fpwm.find("(") > 0 && fpwm.find(")") > 0) { if (fpwm.find("(") > 0 && fpwm.find(")") > 0) {
PIString dms(fpwm.right(fpwm.length() - fpwm.findLast("(")).takeRange("(", ")").trim().toLowerCase().removeAll(" ")); PIString dms(fpwm.right(fpwm.length() - fpwm.findLast("(")).takeRange("(", ")").trim().toLowerCase().removeAll(' '));
PIStringList opts(dms.split(",")); PIStringList opts(dms.split(","));
piForeachC (PIString & o, opts) { piForeachC (PIString & o, opts) {
//piCout << dms; //piCout << dms;

View File

@@ -491,7 +491,7 @@ bool PIPeer::dataRead(uchar * readed, int size) {
if (p.name != from) continue; if (p.name != from) continue;
piForeach (PeerInfo::PeerAddress & a, p.addresses) { piForeach (PeerInfo::PeerAddress & a, p.addresses) {
if (a.address != addr) continue; if (a.address != addr) continue;
if (a.last_ping >= time) piBreak; if (a.last_ping >= time) break;
ptime = ctime - time; ptime = ctime - time;
a.last_ping = time; a.last_ping = time;
a.wait_ping = false; a.wait_ping = false;
@@ -677,7 +677,7 @@ bool PIPeer::mbcastRead(uchar * data, int size) {
if (peer.name == pi.name) peer.sync = 0; if (peer.name == pi.name) peer.sync = 0;
ch = true; ch = true;
} }
piBreak; break;
} }
} }
if (exist || isRemoved(rpeer)) continue; if (exist || isRemoved(rpeer)) continue;

View File

@@ -36,7 +36,7 @@ public:
explicit PIPeer(const PIString & name = PIString()); explicit PIPeer(const PIString & name = PIString());
virtual ~PIPeer(); virtual ~PIPeer();
class PeerInfo { class PIP_EXPORT PeerInfo {
friend class PIPeer; friend class PIPeer;
friend PIByteArray & operator <<(PIByteArray & s, const PIPeer::PeerInfo & v); friend PIByteArray & operator <<(PIByteArray & s, const PIPeer::PeerInfo & v);
friend PIByteArray & operator >>(PIByteArray & s, PIPeer::PeerInfo & v); friend PIByteArray & operator >>(PIByteArray & s, PIPeer::PeerInfo & v);
@@ -44,7 +44,7 @@ public:
PeerInfo() {dist = sync = cnt = 0; trace = -1; was_update = false; _data = 0;} PeerInfo() {dist = sync = cnt = 0; trace = -1; was_update = false; _data = 0;}
~PeerInfo() {} ~PeerInfo() {}
struct PeerAddress { struct PIP_EXPORT PeerAddress {
PeerAddress(const PIEthernet::Address & a = PIEthernet::Address(), const PIEthernet::Address & m = PIEthernet::Address("255.255.255.0")); PeerAddress(const PIEthernet::Address & a = PIEthernet::Address(), const PIEthernet::Address & m = PIEthernet::Address("255.255.255.0"));
bool isAvailable() const {return ping > 0;} bool isAvailable() const {return ping > 0;}
PIEthernet::Address address; PIEthernet::Address address;

View File

@@ -544,7 +544,7 @@ bool PISerial::openDevice() {
piForeachC (DeviceInfo & d, devs) { piForeachC (DeviceInfo & d, devs) {
if (d.id() == pl) { if (d.id() == pl) {
p = d.path; p = d.path;
piBreak; break;
} }
} }
if (p.isEmpty()) { if (p.isEmpty()) {

View File

@@ -72,7 +72,7 @@ public:
}; };
//! \brief Information about serial device //! \brief Information about serial device
struct DeviceInfo { struct PIP_EXPORT DeviceInfo {
DeviceInfo(); DeviceInfo();
//! \brief String representation of USB ID in format \"xxxx:xxxx\" //! \brief String representation of USB ID in format \"xxxx:xxxx\"
@@ -246,7 +246,7 @@ protected:
bool openDevice(); bool openDevice();
bool closeDevice(); bool closeDevice();
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_EXPORT)
int fd, vtime; int fd, vtime;
bool sending; bool sending;
PITimeMeasurer tm_; PITimeMeasurer tm_;

View File

@@ -86,7 +86,7 @@ private:
void initPrivate(); void initPrivate();
int dsize; int dsize;
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_EXPORT)
}; };

View File

@@ -77,7 +77,7 @@ private:
uchar spi_bits; uchar spi_bits;
PIByteArray tx_buf, rx_buf; PIByteArray tx_buf, rx_buf;
PIByteArray recv_buf; PIByteArray recv_buf;
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_EXPORT)
}; };
#endif // PISPI_H #endif // PISPI_H

View File

@@ -34,7 +34,7 @@ public:
explicit PIUSB(ushort vid = 0, ushort pid = 0); explicit PIUSB(ushort vid = 0, ushort pid = 0);
~PIUSB() {closeDevice();} ~PIUSB() {closeDevice();}
struct Endpoint { struct PIP_EXPORT Endpoint {
Endpoint(uchar a = 0, uchar at = 0, ushort mps = 0) {address = a; attributes = at; max_packet_size = mps; parse();} Endpoint(uchar a = 0, uchar at = 0, ushort mps = 0) {address = a; attributes = at; max_packet_size = mps; parse();}
enum Direction {Write = 0, Read = 1}; enum Direction {Write = 0, Read = 1};
@@ -54,7 +54,7 @@ public:
UsageType usage_type; UsageType usage_type;
}; };
struct Interface { struct PIP_EXPORT Interface {
Interface() {index = value_to_select = class_code = subclass_code = protocol_code = 0;} Interface() {index = value_to_select = class_code = subclass_code = protocol_code = 0;}
uchar index; uchar index;
uchar value_to_select; uchar value_to_select;
@@ -64,7 +64,7 @@ public:
PIVector<PIUSB::Endpoint> endpoints; PIVector<PIUSB::Endpoint> endpoints;
}; };
struct Configuration { struct PIP_EXPORT Configuration {
Configuration() {index = value_to_select = attributes = max_power = 0; self_powered = remote_wakeup = false;} Configuration() {index = value_to_select = attributes = max_power = 0; self_powered = remote_wakeup = false;}
uchar index; uchar index;
uchar value_to_select; uchar value_to_select;
@@ -75,7 +75,7 @@ public:
PIVector<PIUSB::Interface> interfaces; PIVector<PIUSB::Interface> interfaces;
}; };
struct Descriptor { struct PIP_EXPORT Descriptor {
Descriptor() {usb_spec_number = 0; device_class = device_subclass = device_protocol = max_packet_size = 0; id_vendor = id_product = id_device_release = 0; index_manufacturer = index_product = index_serial = 0;} Descriptor() {usb_spec_number = 0; device_class = device_subclass = device_protocol = max_packet_size = 0; id_vendor = id_product = id_device_release = 0; index_manufacturer = index_product = index_serial = 0;}
ushort usb_spec_number; ushort usb_spec_number;
uchar device_class; uchar device_class;
@@ -148,6 +148,6 @@ protected:
}; };
PICout operator <<(PICout s, const PIUSB::Endpoint & v); PIP_EXPORT PICout operator <<(PICout s, const PIUSB::Endpoint & v);
#endif // PIUSB_H #endif // PIUSB_H

View File

@@ -102,7 +102,7 @@ protected:
llong bytes_all, bytes_cur; llong bytes_all, bytes_cur;
private: private:
enum PIP_EXPORT PacketType {pt_Unknown, pt_Data, pt_ReplySuccess, pt_ReplyInvalid, pt_Break, pt_Start, pt_Pause}; enum PacketType {pt_Unknown, pt_Data, pt_ReplySuccess, pt_ReplyInvalid, pt_Break, pt_Start, pt_Pause};
# pragma pack(push,1) # pragma pack(push,1)
struct PIP_EXPORT StartRequest { struct PIP_EXPORT StartRequest {

View File

@@ -23,11 +23,12 @@
#ifndef PIBROADCAST_H #ifndef PIBROADCAST_H
#define PIBROADCAST_H #define PIBROADCAST_H
#include "pip_io_utils_export.h"
#include "piethutilbase.h" #include "piethutilbase.h"
#include "piethernet.h" #include "piethernet.h"
class PIBroadcast: public PIThread, public PIEthUtilBase { class PIP_IO_UTILS_EXPORT PIBroadcast: public PIThread, public PIEthUtilBase {
PIOBJECT_SUBCLASS(PIBroadcast, PIThread) PIOBJECT_SUBCLASS(PIBroadcast, PIThread)
public: public:

View File

@@ -375,21 +375,22 @@ bool PIConnection::removeDevice(const PIString & full_path) {
PIStringList dntd(deviceNames(dev)); PIStringList dntd(deviceNames(dev));
piForeachC (PIString & n, dntd) piForeachC (PIString & n, dntd)
device_names.removeOne(n); device_names.removeOne(n);
piForeachC (SPair & s, senders) { for (auto s = senders.constBegin(); s != senders.constEnd(); s++) {
if (s.second == 0) continue; if (s.value() == 0) continue;
s.second->lock(); s.value()->lock();
s.second->devices.removeAll(dev); s.value()->devices.removeAll(dev);
s.second->unlock(); s.value()->unlock();
} }
device_modes.remove(dev); device_modes.remove(dev);
piForeachC (PEPair & i, extractors) { for (auto i = extractors.constBegin(); i != extractors.constEnd(); i++) {
if (i.second == 0) continue; if (i.value() == 0) continue;
i.second->devices.removeAll(dev); i.value()->devices.removeAll(dev);
} }
bounded_extractors.remove(dev); bounded_extractors.remove(dev);
channels_.remove(dev); channels_.remove(dev);
for (PIMap<PIIODevice * , PIVector<PIIODevice * > >::iterator it = channels_.begin(); it != channels_.end(); ++it) auto it = channels_.makeIterator();
it.value().removeAll(dev); while (it.next())
it.valueRef().removeAll(dev);
__device_pool__->lock(); __device_pool__->lock();
if (diags_.value(dev, 0) != 0) if (diags_.value(dev, 0) != 0)
delete diags_.value(dev); delete diags_.value(dev);
@@ -404,15 +405,16 @@ void PIConnection::removeAllDevices() {
PIVector<PIIODevice * > bdevs(__device_pool__->boundedDevices(this)); PIVector<PIIODevice * > bdevs(__device_pool__->boundedDevices(this));
__device_pool__->lock(); __device_pool__->lock();
piForeach (PIIODevice * d, bdevs) { piForeach (PIIODevice * d, bdevs) {
piForeachC (SPair & s, senders) { for (auto s = senders.constBegin(); s != senders.constEnd(); s++) {
if (s.second == 0) continue; if (s.value() == 0) continue;
s.second->lock(); s.value()->lock();
s.second->devices.removeAll(d); s.value()->devices.removeAll(d);
s.second->unlock(); s.value()->unlock();
} }
channels_.remove(d); channels_.remove(d);
for (PIMap<PIIODevice * , PIVector<PIIODevice * > >::iterator it = channels_.begin(); it != channels_.end(); ++it) auto it = channels_.makeIterator();
it.value().removeAll(d); while (it.next())
it.valueRef().removeAll(d);
if (diags_.value(d, 0) != 0) if (diags_.value(d, 0) != 0)
delete diags_.value(d); delete diags_.value(d);
diags_.remove(d); diags_.remove(d);
@@ -421,9 +423,9 @@ void PIConnection::removeAllDevices() {
__device_pool__->unlock(); __device_pool__->unlock();
device_modes.clear(); device_modes.clear();
bounded_extractors.clear(); bounded_extractors.clear();
piForeachC (PEPair & i, extractors) { for (auto i = extractors.constBegin(); i != extractors.constEnd(); i++) {
if (i.second == 0) continue; if (i.value() == 0) continue;
i.second->devices.clear(); i.value()->devices.clear();
} }
} }
@@ -563,15 +565,16 @@ bool PIConnection::removeFilter(const PIString & name_) {
void PIConnection::removeAllFilters() { void PIConnection::removeAllFilters() {
__device_pool__->lock(); __device_pool__->lock();
piForeachC (PEPair & i, extractors) { for (auto i = extractors.constBegin(); i != extractors.constEnd(); i++) {
if (i.second == 0) continue; if (i.value() == 0) continue;
channels_.remove(i.second->extractor); channels_.remove(i.value()->extractor);
for (PIMap<PIIODevice * , PIVector<PIIODevice * > >::iterator it = channels_.begin(); it != channels_.end(); ++it) auto it = channels_.makeIterator();
it.value().removeAll(i.second->extractor); while (it.next())
if (diags_.value(i.second->extractor, 0) != 0) it.valueRef().removeAll(i.value()->extractor);
delete diags_.value(i.second->extractor); if (diags_.value(i.value()->extractor, 0) != 0)
diags_.remove(i.second->extractor); delete diags_.value(i.value()->extractor);
delete i.second; diags_.remove(i.value()->extractor);
delete i.value();
} }
extractors.clear(); extractors.clear();
bounded_extractors.clear(); bounded_extractors.clear();
@@ -581,28 +584,31 @@ void PIConnection::removeAllFilters() {
PIVector<PIPacketExtractor * > PIConnection::filters() const { PIVector<PIPacketExtractor * > PIConnection::filters() const {
PIVector<PIPacketExtractor * > ret; PIVector<PIPacketExtractor * > ret;
piForeachC (PEPair & i, extractors) for (auto i = extractors.constBegin(); i != extractors.constEnd(); i++) {
if (i.second != 0) if (i.value() != 0)
if (i.second->extractor != 0) ret << i.second->extractor; if (i.value()->extractor != 0) ret << i.value()->extractor;
}
return ret; return ret;
} }
PIStringList PIConnection::filterNames() const { PIStringList PIConnection::filterNames() const {
PIStringList ret; PIStringList ret;
piForeachC (PEPair & i, extractors) for (auto i = extractors.constBegin(); i != extractors.constEnd(); i++) {
if (i.second != 0) if (i.value() != 0)
if (i.second->extractor != 0) ret << i.first; if (i.value()->extractor != 0) ret << i.key();
}
return ret; return ret;
} }
PIPacketExtractor * PIConnection::filter(const PIString & name_) const { PIPacketExtractor * PIConnection::filter(const PIString & name_) const {
PIString fname_ = name_.trimmed(); PIString fname_ = name_.trimmed();
piForeachC (PEPair & i, extractors) for (auto i = extractors.constBegin(); i != extractors.constEnd(); i++) {
if (i.second != 0) if (i.value() != 0)
if (i.second->extractor != 0 && i.first == fname_) if (i.value()->extractor != 0 && i.key() == fname_)
return i.second->extractor; return i.value()->extractor;
}
return 0; return 0;
} }
@@ -655,8 +661,9 @@ bool PIConnection::removeChannel(const PIString & name0) {
if (pe0 != 0) dev0 = pe0; if (pe0 != 0) dev0 = pe0;
if (dev0 == 0) return false; if (dev0 == 0) return false;
channels_.remove(dev0); channels_.remove(dev0);
for (PIMap<PIIODevice * , PIVector<PIIODevice * > >::iterator it = channels_.begin(); it != channels_.end(); ++it) auto it = channels_.makeIterator();
it.value().removeAll(dev0); while (it.next())
it.valueRef().removeAll(dev0);
return true; return true;
} }
@@ -784,9 +791,10 @@ float PIConnection::senderFrequency(const PIString & name) const {
void PIConnection::removeAllSenders() { void PIConnection::removeAllSenders() {
piForeachC (SPair & s, senders) for (auto s = senders.constBegin(); s != senders.constEnd(); s++) {
if (s.second != 0) if (s.value() != 0)
delete s.second; delete s.value();
}
senders.clear(); senders.clear();
} }
@@ -802,8 +810,8 @@ void PIConnection::startThreadedRead(const PIString & full_path_name) {
void PIConnection::startAllThreadedReads() { void PIConnection::startAllThreadedReads() {
piForeachC (DevicePool::DDPair & d, __device_pool__->devices) for (auto d = __device_pool__->devices.constBegin(); d != __device_pool__->devices.constEnd(); d++)
startThreadedRead(d.first); startThreadedRead(d.key());
} }
@@ -816,10 +824,10 @@ void PIConnection::startSender(const PIString & name) {
void PIConnection::startAllSenders() { void PIConnection::startAllSenders() {
piForeachC (SPair & s, senders) { for (auto s = senders.constBegin(); s != senders.constEnd(); s++) {
if (s.second == 0) continue; if (s.value() == 0) continue;
if (!s.second->isRunning() && !__device_pool__->fake) if (!s.value()->isRunning() && !__device_pool__->fake)
s.second->start(s.second->int_); s.value()->start(s.value()->int_);
} }
} }
@@ -835,8 +843,8 @@ void PIConnection::stopThreadedRead(const PIString & full_path_name) {
void PIConnection::stopAllThreadedReads() { void PIConnection::stopAllThreadedReads() {
piForeachC (DevicePool::DDPair & d, __device_pool__->devices) for (auto d = __device_pool__->devices.constBegin(); d != __device_pool__->devices.constEnd(); d++)
stopThreadedRead(d.first); stopThreadedRead(d.key());
} }
@@ -848,10 +856,10 @@ void PIConnection::stopSender(const PIString & name) {
void PIConnection::stopAllSenders() { void PIConnection::stopAllSenders() {
piForeachC (SPair & s, senders) { for (auto s = senders.constBegin(); s != senders.constEnd(); s++) {
if (s.second == 0) continue; if (s.value() == 0) continue;
if (s.second->isRunning()) if (s.value()->isRunning())
s.second->stop(); s.value()->stop();
} }
} }
@@ -1012,14 +1020,14 @@ bool PIConnection::DevicePool::removeDevice(PIConnection * parent, const PIStrin
void PIConnection::DevicePool::unboundConnection(PIConnection * parent) { void PIConnection::DevicePool::unboundConnection(PIConnection * parent) {
PIStringList rem; PIStringList rem;
piForeachC (DDPair & i, devices) { for (auto i = devices.constBegin(); i != devices.constEnd(); i++) {
if (i.second == 0) { if (i.value() == 0) {
rem << i.first; rem << i.key();
continue; continue;
} }
i.second->listeners.removeAll(parent); i.value()->listeners.removeAll(parent);
if (i.second->listeners.isEmpty()) if (i.value()->listeners.isEmpty())
rem << i.first; rem << i.key();
} }
piForeachC (PIString & i, rem) { piForeachC (PIString & i, rem) {
DeviceData * dd = devices.value(i); DeviceData * dd = devices.value(i);
@@ -1105,9 +1113,9 @@ PIConnection::DevicePool::DeviceData::~DeviceData() {
void PIConnection::DevicePool::run() { void PIConnection::DevicePool::run() {
PIVector<PIConnection * > conns(PIConnection::allConnections()); PIVector<PIConnection * > conns(PIConnection::allConnections());
piForeach (PIConnection * c, conns) { piForeach (PIConnection * c, conns) {
piForeachC (PIConnection::DPair & d, c->diags_) { for (auto d = c->diags_.constBegin(); d != c->diags_.constEnd(); d++) {
if (d.second == 0) continue; if (d.value() == 0) continue;
d.second->tick(0, 1); d.value()->tick(0, 1);
} }
} }
} }
@@ -1236,8 +1244,9 @@ void PIConnection::Sender::tick(void * , int) {
void PIConnection::unboundExtractor(PIPacketExtractor * pe) { void PIConnection::unboundExtractor(PIPacketExtractor * pe) {
if (pe == 0) return; if (pe == 0) return;
channels_.remove(pe); channels_.remove(pe);
for (PIMap<PIIODevice * , PIVector<PIIODevice * > >::iterator it = channels_.begin(); it != channels_.end(); ++it) auto it = channels_.makeIterator();
it.value().removeAll(pe); while (it.next())
it.valueRef().removeAll(pe);
bounded_extractors.remove(pe); bounded_extractors.remove(pe);
PIVector<PIIODevice * > k = bounded_extractors.keys(); PIVector<PIIODevice * > k = bounded_extractors.keys();
piForeach (PIIODevice * i, k) { piForeach (PIIODevice * i, k) {

View File

@@ -404,7 +404,7 @@ private:
void __DevicePool_threadReadDP(void * ddp); void __DevicePool_threadReadDP(void * ddp);
extern PIConnection::DevicePool * __device_pool__; extern PIP_EXPORT PIConnection::DevicePool * __device_pool__;
class PIP_EXPORT __DevicePoolContainer__ { class PIP_EXPORT __DevicePoolContainer__ {
public: public:

View File

@@ -49,7 +49,7 @@ public:
}; };
//! Information about current diagnostics state //! Information about current diagnostics state
struct State { struct PIP_EXPORT State {
State(); State();
float immediate_freq; float immediate_freq;
float integral_freq; float integral_freq;
@@ -123,7 +123,7 @@ public:
//! \} //! \}
private: private:
struct Entry { struct PIP_EXPORT Entry {
Entry() {bytes_ok = bytes_fail = 0; cnt_ok = cnt_fail = 0; empty = true;} Entry() {bytes_ok = bytes_fail = 0; cnt_ok = cnt_fail = 0; empty = true;}
ullong bytes_ok; ullong bytes_ok;
ullong bytes_fail; ullong bytes_fail;

View File

@@ -23,9 +23,10 @@
#ifndef PIETHUTILBASE_H #ifndef PIETHUTILBASE_H
#define PIETHUTILBASE_H #define PIETHUTILBASE_H
#include "pip_io_utils_export.h"
#include "pibytearray.h" #include "pibytearray.h"
class PIEthUtilBase { class PIP_IO_UTILS_EXPORT PIEthUtilBase {
public: public:
PIEthUtilBase(); PIEthUtilBase();
~PIEthUtilBase(); ~PIEthUtilBase();

View File

@@ -35,7 +35,7 @@ public:
PIFileTransfer(); PIFileTransfer();
~PIFileTransfer(); ~PIFileTransfer();
enum PIP_EXPORT StepType {pft_None, pft_Description, pft_Data}; enum StepType {pft_None, pft_Description, pft_Data};
struct PIP_EXPORT PFTFileInfo: public PIFile::FileInfo { struct PIP_EXPORT PFTFileInfo: public PIFile::FileInfo {
PFTFileInfo(const PIFile::FileInfo &fi = PIFile::FileInfo()): PIFile::FileInfo(fi) {} PFTFileInfo(const PIFile::FileInfo &fi = PIFile::FileInfo()): PIFile::FileInfo(fi) {}

View File

@@ -23,20 +23,21 @@
#ifndef PISTREAMPACKER_H #ifndef PISTREAMPACKER_H
#define PISTREAMPACKER_H #define PISTREAMPACKER_H
#include "pip_io_utils_export.h"
#include "piobject.h" #include "piobject.h"
#include "piethutilbase.h" #include "piethutilbase.h"
class PIIODevice; class PIIODevice;
class PIP_EXPORT PIStreamPacker: public PIObject, public PIEthUtilBase { class PIP_IO_UTILS_EXPORT PIStreamPacker: public PIObject, public PIEthUtilBase {
PIOBJECT(PIStreamPacker) PIOBJECT(PIStreamPacker)
public: public:
//! Contructs packer and try to assign \"dev\" //! Contructs packer and try to assign \"dev\"
PIStreamPacker(PIIODevice * dev = 0); PIStreamPacker(PIIODevice * dev = 0);
//! Progress info //! Progress info
struct Progress { struct PIP_IO_UTILS_EXPORT Progress {
Progress(); Progress();
//! Is send/receive in progress //! Is send/receive in progress

View File

@@ -23,9 +23,10 @@
#ifndef PILUAPROGRAM_H #ifndef PILUAPROGRAM_H
#define PILUAPROGRAM_H #define PILUAPROGRAM_H
#include "pip_lua_export.h"
#include "pip_lua.h" #include "pip_lua.h"
class PILuaProgram class PIP_LUA_EXPORT PILuaProgram
{ {
public: public:
//! Constructs an empty PILuaProgram, initialize Lua context //! Constructs an empty PILuaProgram, initialize Lua context
@@ -44,7 +45,7 @@ public:
luabridge::Namespace getGlobalNamespace(); luabridge::Namespace getGlobalNamespace();
private: private:
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_LUA_EXPORT)
}; };
#endif // PILUAPROGRAM_H #endif // PILUAPROGRAM_H

View File

@@ -24,11 +24,7 @@
#ifndef PIP_LUA_H #ifndef PIP_LUA_H
#define PIP_LUA_H #define PIP_LUA_H
extern "C" { #include "lua.hpp"
# include "lua.h"
# include "lauxlib.h"
# include "lualib.h"
}
#include <LuaBridge/LuaBridge.h> #include <LuaBridge/LuaBridge.h>
#include "pistring.h" #include "pistring.h"

View File

@@ -30,12 +30,12 @@ typedef complexd (*FuncFunc)(void * , int, complexd * );
namespace PIEvaluatorTypes { namespace PIEvaluatorTypes {
enum PIP_EXPORT eType {etNumber, etOperator, etVariable, etFunction}; enum eType {etNumber, etOperator, etVariable, etFunction};
enum PIP_EXPORT Operation {oNone, oAdd, oSubtract, oMultiply, oDivide, oResidue, oPower, enum Operation {oNone, oAdd, oSubtract, oMultiply, oDivide, oResidue, oPower,
oEqual, oNotEqual, oGreater, oSmaller, oGreaterEqual, oSmallerEqual, oEqual, oNotEqual, oGreater, oSmaller, oGreaterEqual, oSmallerEqual,
oAnd, oOr, oFunction oAnd, oOr, oFunction
}; };
enum PIP_EXPORT BaseFunctions {bfUnknown, bfSin, bfCos, bfTg, bfCtg, enum BaseFunctions {bfUnknown, bfSin, bfCos, bfTg, bfCtg,
bfArcsin, bfArccos, bfArctg, bfArcctg, bfArcsin, bfArccos, bfArctg, bfArcctg,
bfExp, bfRandom, bfRandomn, bfExp, bfRandom, bfRandomn,
bfSh, bfCh, bfTh, bfCth, bfSh, bfCh, bfTh, bfCth,

View File

@@ -23,6 +23,7 @@
#ifndef PIFFT_H #ifndef PIFFT_H
#define PIFFT_H #define PIFFT_H
#include "pip_fftw_export.h"
#include "pimathcomplex.h" #include "pimathcomplex.h"
class PIP_EXPORT PIFFT_double class PIP_EXPORT PIFFT_double
@@ -123,7 +124,7 @@ typedef PIFFT_float PIFFTf;
#ifndef CC_VC #ifndef CC_VC
#define _PIFFTW_H(type) class _PIFFTW_P_##type##_ { \ #define _PIFFTW_H(type) class PIP_FFTW_EXPORT _PIFFTW_P_##type##_ { \
public: \ public: \
_PIFFTW_P_##type##_(); \ _PIFFTW_P_##type##_(); \
~_PIFFTW_P_##type##_(); \ ~_PIFFTW_P_##type##_(); \
@@ -138,7 +139,7 @@ _PIFFTW_H(double)
_PIFFTW_H(ldouble) _PIFFTW_H(ldouble)
template <typename T> template <typename T>
class PIP_EXPORT PIFFTW class PIFFTW
{ {
public: public:
explicit PIFFTW() {p = 0; newP(p);} explicit PIFFTW() {p = 0; newP(p);}

View File

@@ -103,21 +103,21 @@ inline float sqr(const float & v) {return v * v;}
inline double sqr(const double & v) {return v * v;} inline double sqr(const double & v) {return v * v;}
inline double sinc(const double & v) {if (v == 0.) return 1.; double t = M_PI * v; return sin(t) / t;} inline double sinc(const double & v) {if (v == 0.) return 1.; double t = M_PI * v; return sin(t) / t;}
double piJ0(const double & v); PIP_EXPORT double piJ0(const double & v);
double piJ1(const double & v); PIP_EXPORT double piJ1(const double & v);
double piJn(int n, const double & v); PIP_EXPORT double piJn(int n, const double & v);
double piY0(const double & v); PIP_EXPORT double piY0(const double & v);
double piY1(const double & v); PIP_EXPORT double piY1(const double & v);
double piYn(int n, const double & v); PIP_EXPORT double piYn(int n, const double & v);
inline double toDb(double val) {return 10. * log10(val);} inline double toDb(double val) {return 10. * log10(val);}
inline double fromDb(double val) {return pow(10., val / 10.);} inline double fromDb(double val) {return pow(10., val / 10.);}
inline double toRad(double deg) {return deg * M_PI_180;} inline double toRad(double deg) {return deg * M_PI_180;}
inline double toDeg(double rad) {return rad * M_180_PI;} inline double toDeg(double rad) {return rad * M_180_PI;}
// [-1 ; 1] // [-1 ; 1]
double randomd(); PIP_EXPORT double randomd();
// [-1 ; 1] normal // [-1 ; 1] normal
double randomn(double dv = 0., double sv = 1.); PIP_EXPORT double randomn(double dv = 0., double sv = 1.);
inline PIVector<double> abs(const PIVector<double> & v) { inline PIVector<double> abs(const PIVector<double> & v) {

View File

@@ -27,7 +27,7 @@
/// Differential evaluations /// Differential evaluations
struct TransferFunction { struct PIP_EXPORT TransferFunction {
PIVector<double> vector_Bm, vector_An; PIVector<double> vector_Bm, vector_An;
}; };

View File

@@ -25,7 +25,7 @@
#include "pimathmatrix.h" #include "pimathmatrix.h"
class PIQuaternion class PIP_EXPORT PIQuaternion
{ {
friend PIQuaternion operator*(const PIQuaternion & q0, const PIQuaternion & q1); friend PIQuaternion operator*(const PIQuaternion & q0, const PIQuaternion & q1);
friend PIQuaternion operator*(const double & a, const PIQuaternion & q); friend PIQuaternion operator*(const double & a, const PIQuaternion & q);
@@ -57,8 +57,8 @@ protected:
}; };
PIQuaternion operator *(const double & a, const PIQuaternion & q); PIP_EXPORT PIQuaternion operator *(const double & a, const PIQuaternion & q);
PIQuaternion operator *(const PIQuaternion & q0, const PIQuaternion & q1); PIP_EXPORT PIQuaternion operator *(const PIQuaternion & q0, const PIQuaternion & q1);
inline PIQuaternion operator +(const PIQuaternion & q0, const PIQuaternion & q1) {return PIQuaternion(q0.vector() + q1.vector(), q0.scalar() + q1.scalar());} inline PIQuaternion operator +(const PIQuaternion & q0, const PIQuaternion & q1) {return PIQuaternion(q0.vector() + q1.vector(), q0.scalar() + q1.scalar());}
inline PIQuaternion operator -(const PIQuaternion & q0, const PIQuaternion & q1) {return PIQuaternion(q0.vector() - q1.vector(), q0.scalar() - q1.scalar());} inline PIQuaternion operator -(const PIQuaternion & q0, const PIQuaternion & q1) {return PIQuaternion(q0.vector() - q1.vector(), q0.scalar() - q1.scalar());}
inline PIQuaternion operator -(const PIQuaternion & q0) {return PIQuaternion(-q0.vector(), -q0.scalar());} inline PIQuaternion operator -(const PIQuaternion & q0) {return PIQuaternion(-q0.vector(), -q0.scalar());}

View File

@@ -26,7 +26,7 @@
#include "pimathbase.h" #include "pimathbase.h"
template <typename T> template <typename T>
class PIP_EXPORT PIStatistic { class PIStatistic {
public: public:
PIStatistic() {mean = variance = skewness = kurtosis = T();} PIStatistic() {mean = variance = skewness = kurtosis = T();}

View File

@@ -20,10 +20,11 @@
#ifndef PIOPENCL_H #ifndef PIOPENCL_H
#define PIOPENCL_H #define PIOPENCL_H
#include "pip_opencl_export.h"
#include "pivariant.h" #include "pivariant.h"
class PIOpenCL { class PIP_OPENCL_EXPORT PIOpenCL {
public: public:
struct KernelArg; struct KernelArg;
@@ -69,7 +70,7 @@ public:
Double, Double,
}; };
struct KernelArg { struct PIP_OPENCL_EXPORT KernelArg {
KernelArg(); KernelArg();
AddressQualifier address_qualifier; AddressQualifier address_qualifier;
AccessQualifier access_qualifier; AccessQualifier access_qualifier;
@@ -85,7 +86,7 @@ public:
void init(void * _k, uint index); void init(void * _k, uint index);
}; };
struct Device { struct PIP_OPENCL_EXPORT Device {
Device() {id = platform_id = 0; max_compute_units = max_clock_frequency = 0; max_memory_size = 0;} Device() {id = platform_id = 0; max_compute_units = max_clock_frequency = 0; max_memory_size = 0;}
bool isValid() const {return id != 0;} bool isValid() const {return id != 0;}
PIString displayText() const {return name.trimmed() + " (" + device_version.trimmed() + ")";} PIString displayText() const {return name.trimmed() + " (" + device_version.trimmed() + ")";}
@@ -100,7 +101,7 @@ public:
ullong max_memory_size; ullong max_memory_size;
}; };
struct Platform { struct PIP_OPENCL_EXPORT Platform {
Platform() {id = 0;} Platform() {id = 0;}
bool isValid() const {return id != 0;} bool isValid() const {return id != 0;}
PIString displayText() const {return name.trimmed() + " (" + version.trimmed() + ", " + profile.trimmed() + ")";} PIString displayText() const {return name.trimmed() + " (" + version.trimmed() + ", " + profile.trimmed() + ")";}
@@ -113,7 +114,7 @@ public:
PIVector<Device> devices; PIVector<Device> devices;
}; };
class Context { class PIP_OPENCL_EXPORT Context {
friend class Program; friend class Program;
public: public:
~Context(); ~Context();
@@ -125,10 +126,10 @@ public:
void zero(); void zero();
void deletePrograms(); void deletePrograms();
PIVector<Program * > programs_; PIVector<Program * > programs_;
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_OPENCL_EXPORT)
}; };
class Program { class PIP_OPENCL_EXPORT Program {
friend class Context; friend class Context;
friend class Kernel; friend class Kernel;
public: public:
@@ -143,10 +144,10 @@ public:
Context * context_; Context * context_;
PIString source_; PIString source_;
PIVector<Kernel * > kernels_; PIVector<Kernel * > kernels_;
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_OPENCL_EXPORT)
}; };
class Kernel { class PIP_OPENCL_EXPORT Kernel {
friend class Program; friend class Program;
public: public:
const PIString & name() const {return name_;} const PIString & name() const {return name_;}
@@ -165,7 +166,7 @@ public:
Program * program_; Program * program_;
PIString name_; PIString name_;
PIVector<KernelArg> args_; PIVector<KernelArg> args_;
PRIVATE_DECLARATION PRIVATE_DECLARATION(PIP_OPENCL_EXPORT)
}; };
static void init(); static void init();
@@ -177,7 +178,7 @@ public:
private: private:
static PIString prog_header; static PIString prog_header;
PIOpenCL() {;} PIOpenCL() {;}
class Initializer { class PIP_OPENCL_EXPORT Initializer {
public: public:
Initializer(); Initializer();
static Initializer * instance(); static Initializer * instance();

View File

@@ -20,6 +20,8 @@
#ifndef PIPLATFORM_H #ifndef PIPLATFORM_H
#define PIPLATFORM_H #define PIPLATFORM_H
#include <pip_export.h>
#if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) #if defined(WIN64) || defined(_WIN64) || defined(__WIN64__)
# define WINDOWS # define WINDOWS
# define ARCH_BITS_64 # define ARCH_BITS_64
@@ -90,11 +92,5 @@
# define typeof __typeof__ # define typeof __typeof__
#endif #endif
#if defined(DOXYGEN) || defined(CC_GCC) || defined(PICODE)
# undef PIP_EXPORT
# define PIP_EXPORT
# undef DEPRECATED
# define DEPRECATED
#endif
#endif // PIPLATFORM_H #endif // PIPLATFORM_H

Some files were not shown because too many files have changed in this diff Show More