diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000..abd3c837 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,448 @@ +cmake_minimum_required(VERSION 3.20) +project(AdvancedSettings VERSION 5.7.4 LANGUAGES CXX) + +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core) +find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Gui Multimedia Qml Quick WebSockets Widgets QuickControls2 QuickDialogs2 Svg) +find_package(Qt${QT_VERSION_MAJOR} OPTIONAL_COMPONENTS DBus) + +qt_standard_project_setup() + +if(QT_KNOWN_POLICY_QTP0001) + qt_policy(SET QTP0001 NEW) +endif() + +# ability to just put .qrc files into the source list +set(CMAKE_AUTORCC ON) + +set(SRCS + src/alarm_clock/vr_alarm.cpp + src/keyboard_input/input_parser.cpp + src/keyboard_input/keyboard_input.cpp + src/main.cpp + src/openvr/ivrinput.cpp + src/openvr/lh_console_util.cpp + src/openvr/openvr_init.cpp + src/openvr/ovr_application_wrapper.cpp + src/openvr/ovr_overlay_wrapper.cpp + src/openvr/ovr_settings_wrapper.cpp + src/openvr/ovr_system_wrapper.cpp + src/overlaycontroller.cpp + src/settings/settings.cpp + src/settings/settings_object.cpp + src/tabcontrollers/AudioTabController.cpp + src/tabcontrollers/ChaperoneTabController.cpp + src/tabcontrollers/FixFloorTabController.cpp + src/tabcontrollers/MoveCenterTabController.cpp + src/tabcontrollers/RotationTabController.cpp + src/tabcontrollers/SettingsTabController.cpp + src/tabcontrollers/StatisticsTabController.cpp + src/tabcontrollers/SteamVRTabController.cpp + src/tabcontrollers/UtilitiesTabController.cpp + src/tabcontrollers/VideoTabController.cpp + src/utils/ChaperoneUtils.cpp + src/utils/FrameRateUtils.cpp + src/utils/paths.cpp + src/utils/setup.cpp + src/utils/update_rate.cpp +) + +set(HEADERS + src/alarm_clock/vr_alarm.h + src/keyboard_input/input_parser.h + src/keyboard_input/keyboard_input.h + #TODO, check if we need this + #src/keyboard_input/keyboard_sender.h + src/openvr/ivrinput.h + src/openvr/ivrinput_action.h + src/openvr/ivrinput_input_source.h + src/openvr/ivrinput_manifest.h + src/openvr/lh_console_util.h + src/openvr/openvr_init.h + src/openvr/ovr_application_wrapper.h + src/openvr/ovr_overlay_wrapper.h + src/openvr/ovr_settings_wrapper.h + src/openvr/ovr_system_wrapper.h + src/overlaycontroller.h + src/settings/settings.h + src/settings/settings_object.h + src/settings/internal/bool_setting_value.h + src/settings/internal/double_setting_value.h + src/settings/internal/setting_value.h + src/settings/internal/settings_controller.h + src/settings/internal/settings_object_data.h + src/settings/internal/specific_setting_value.h + src/tabcontrollers/AudioTabController.h + src/tabcontrollers/ChaperoneTabController.h + src/tabcontrollers/FixFloorTabController.h + src/tabcontrollers/MoveCenterTabController.h + src/tabcontrollers/RotationTabController.h + src/tabcontrollers/SettingsTabController.h + src/tabcontrollers/StatisticsTabController.h + src/tabcontrollers/SteamVRTabController.h + src/tabcontrollers/UtilitiesTabController.h + src/tabcontrollers/VideoTabController.h + src/utils/ChaperoneUtils.h + src/utils/FrameRateUtils.h + src/utils/paths.h + src/utils/setup.h + src/utils/update_rate.h + src/utils/Matrix.h + src/quaternion/quaternion.h + ) + +set(QML_FILES + src/res/qml/utilities_page/keyboard_utils/KeyboardGroupBox.qml + src/res/qml/utilities_page/media_keys/MediaControllerKeys.qml + src/res/qml/utilities_page/media_keys/MediaButton.qml + src/res/qml/utilities_page/misc/MiscBox.qml + src/res/qml/utilities_page/alarm_clock/AlarmGroupBox.qml + src/res/qml/utilities_page/UtilitiesPage.qml + src/res/qml/motion_page/space_drag/SpaceDragGroupBox.qml + src/res/qml/motion_page/height_toggle/HeightToggleGroupBox.qml + src/res/qml/motion_page/gravity/GravityGroupBox.qml + src/res/qml/motion_page/MotionPage.qml + src/res/qml/PlayspacePage.qml + src/res/qml/SettingsPage.qml + src/res/qml/ChaperoneWarningsPage.qml + src/res/qml/chaperone_page/ChaperonePage.qml + src/res/qml/chaperone_page/change_orientation/ChangeOrientationGroupBox.qml + src/res/qml/chaperone_page/chaperone_additional/ChaperoneAdditionalPage.qml + src/res/qml/chaperone_page/chaperone_additional/chaperonemisc/ChaperoneMiscGroupBox.qml + src/res/qml/chaperone_page/chaperone_additional/chaperonetype/ChaperoneTypeGroupBox.qml + src/res/qml/chaperone_page/chaperone_additional/chaperoneboundscolor/ChaperoneBoundsColorGroupBox.qml + src/res/qml/RootPage.qml + src/res/qml/steamvr_page/steamvrmisc/SteamVRMiscGroupBox.qml + src/res/qml/steamvr_page/SteamVRPage.qml + src/res/qml/steamvr_page/camera/CameraGroupBox.qml + src/res/qml/steamvr_page/steamvr_additional/SteamVRTXRXPage.qml + src/res/qml/steamvr_page/steamvrbind/SteamVRBindGroupBox.qml + src/res/qml/audio_page/device_selector/MicDeviceSelector.qml + src/res/qml/audio_page/device_selector/AudioDeviceSelector.qml + src/res/qml/audio_page/device_selector/MirrorDeviceSelector.qml + src/res/qml/audio_page/device_selector/MirrorVolumeSlider.qml + src/res/qml/audio_page/device_selector/MicVolumeSlider.qml + src/res/qml/audio_page/dialog_boxes/AudioDeleteProfileDialog.qml + src/res/qml/audio_page/dialog_boxes/AudioNewProfileDialog.qml + src/res/qml/audio_page/dialog_boxes/AudioMessageDialog.qml + src/res/qml/audio_page/proximity/ProximityToggle.qml + src/res/qml/audio_page/profiles/ProfileButtons.qml + src/res/qml/audio_page/AudioPage.qml + src/res/qml/audio_page/push_to_talk/PttButtons.qml + src/res/qml/FixFloorPage.qml + src/res/qml/common/MySlider.qml + src/res/qml/common/MyResources.qml + src/res/qml/common/MyPushButton.qml + src/res/qml/common/HourComboBox.qml + src/res/qml/common/MyText.qml + src/res/qml/common/MyToggleButton.qml + src/res/qml/common/MinuteSecondComboBox.qml + src/res/qml/common/MyComboBox.qml + src/res/qml/common/MyTextField.qml + src/res/qml/common/TimeAssembly.qml + src/res/qml/common/MyDialogOkPopup.qml + src/res/qml/common/mainwidget.qml + src/res/qml/common/LineSeparator.qml + src/res/qml/common/MyPushButton2.qml + src/res/qml/common/MyStackViewPage.qml + src/res/qml/common/MyRadioButton.qml + src/res/qml/common/FullWidthSliderBox.qml + src/res/qml/common/MyDialogOkCancelPopup.qml + src/res/qml/rotation_page/view_ratchet/ViewRatchetGroupBox.qml + src/res/qml/rotation_page/redirected/RedirectedGroupBox.qml + src/res/qml/rotation_page/redirected/AutoTurnGroupBox.qml + src/res/qml/rotation_page/snap_turn/SnapTurnGroupBox.qml + src/res/qml/rotation_page/space_turn/SpaceTurnGroupBox.qml + src/res/qml/rotation_page/RotationPage.qml + src/res/qml/video_page/brightness/BrightnessGroupBox.qml + src/res/qml/video_page/profiles/VideoProfileGroupBox.qml + src/res/qml/video_page/overlaycolorbright/OverlayMethodGroupBox.qml + src/res/qml/video_page/miscvid/VideoMiscGroupBox.qml + src/res/qml/video_page/supersampling/SuperSamplingGroupBox.qml + src/res/qml/video_page/color/ColorGroupBox.qml + src/res/qml/video_page/VideoPage.qml + src/res/qml/video_page/dialogboxes/VideoNewProfileDialog.qml + src/res/qml/video_page/dialogboxes/VideoMessageDialog.qml + src/res/qml/video_page/dialogboxes/VideoDeleteProfileDialog.qml + src/res/qml/StatisticsPage.qml +) + +set(RESOURCES src/res/resources.qrc) + +# make alias path relative to src/res/qml +foreach(qml_file ${QML_FILES}) + cmake_path(RELATIVE_PATH qml_file BASE_DIRECTORY src/res/qml OUTPUT_VARIABLE qml_alias) + set_source_files_properties(${qml_file} PROPERTIES QT_RESOURCE_ALIAS ${qml_alias}) +endforeach() + +set_source_files_properties(src/res/qml/common/MyResources.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE) + +qt_add_executable(AdvancedSettings WIN32 MACOSX_BUNDLE ${SRCS} ${RESOURCES} ${HEADERS}) + +target_include_directories(AdvancedSettings PUBLIC + src + third-party/nlohmann + third-party/openvr/headers) + +# Avoid collision between executable name and QML module directory (QTBUG-98568). +if(NOT WIN32 AND NOT APPLE) + set_property(TARGET AdvancedSettings PROPERTY OUTPUT_NAME AdvancedSettings_app) +endif() + +target_compile_definitions(AdvancedSettings PRIVATE + APPLICATION_VERSION=\"${PROJECT_VERSION}\" +) + +find_library(OPENVR_LIBRARIES + NAMES + openvr_api + PATHS + ${CMAKE_CURRENT_SOURCE_DIR}/third-party/openvr/bin + ${CMAKE_CURRENT_SOURCE_DIR}/third-party/openvr/lib + PATH_SUFFIXES + linux64 + win64 + NO_DEFAULT_PATH + NO_CMAKE_FIND_ROOT_PATH) + +target_link_libraries(AdvancedSettings PRIVATE + Qt::Core + Qt::Gui + # For QRhi + Qt::GuiPrivate + Qt::Multimedia + Qt::Qml + Qt::Quick + Qt::WebSockets + Qt::Widgets + Qt::QuickControls2 + Qt::QuickDialogs2 + Qt::Svg + ${OPENVR_LIBRARIES} +) + +qt_add_qml_module(AdvancedSettings + URI AdvancedSettings + VERSION ${PROJECT_VERSION} + QML_FILES ${QML_FILES} +) + + +if(GCC) + target_compile_options(AdvancedSettings + -Wcast-align + -Wconversion + -Wdouble-promotion + -Wduplicated-branches + -Wduplicated-cond + -Wextra + -Wformat=2 + -Wlogical-op + -Wno-sign-conversion + -Wnon-virtual-dtor + -Wnull-dereference + -Wold-style-cast + -Woverloaded-virtual + -Wpedantic + -Wrestrict + -Wshadow + -Wunused + -Wzero-as-null-pointer-constant + -flto + ) + + if(warnings_as_errors) + target_compile_options(AdvancedSettings + -Werror + ) + endif() +endif() + +if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + target_compile_options(AdvancedSettings + --system-header-prefix=qt + --system-header-prefix=third-party + -Wcast-align + -Wconversion + -Wdouble-promotion + -Wextra + -Wextra-semi + -Wformat=2 + -Wmissing-variable-declarations + -Wmost + -Wno-sign-conversion + -Wnon-virtual-dtor + -Wold-style-cast + -Woverloaded-virtual + -Wpedantic + -Wshadow + -Wunused + -Wzero-as-null-pointer-constant + -flto + ) + if(warnings_as_errors) + target_compile_options(AdvancedSettings + -Werror + ) + endif() +endif() + +if(debugSymbolsAndLogs) + target_compile_definitions(AdvancedSettings PRIVATE + ENABLE_DEBUG_LOGGING + ) +endif() + +if(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") + cmake_path(GET QT_DIR PARENT_PATH QT_ROOT) + cmake_path(GET QT_ROOT PARENT_PATH QT_ROOT) + cmake_path(GET QT_ROOT PARENT_PATH QT_ROOT) + + cmake_path(NATIVE_PATH QT_ROOT NORMALIZE NATIVE_QT_ROOT) + cmake_path(NATIVE_PATH QT_DIR NORMALIZE NATIVE_QT_DIR) + cmake_path(NATIVE_PATH PROJECT_SOURCE_DIR NORMALIZE NATIVE_PROJECT_SOURCE_DIR) + + # Needs to be executed: Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process + configure_file(build_scripts/win/env.ps1.in env.ps1) + configure_file(build_scripts/win/env.sh.in env.sh @ONLY) + + # Adds default qt plugins path + configure_file(build_scripts/win/qt.conf.in qt.conf ESCAPE_QUOTES) + + target_sources(AdvancedSettings PUBLIC + src/keyboard_input/input_sender_win.cpp + src/media_keys/media_keys_win.cpp + src/tabcontrollers/audiomanager/AudioManagerWindows.cpp + ) + + target_link_libraries(AdvancedSettings PRIVATE + ole32 + user32 + ) + target_include_directories(AdvancedSettings PUBLIC third-party/policyconfig) + + target_compile_definitions(AdvancedSettings PRIVATE + _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING + ) + if(MSVC) + target_compile_options(AdvancedSettings PUBLIC + /Gw + /W4 + /permissive- + /w14254 + /w14263 + /w14265 + /w14287 + /w14296 + /w14311 + /w14545 + /w14546 + /w14547 + /w14549 + /w14555 + /w14640 + /w14826 + /w14905 + /w14906 + /w14928 + /wd4127 + /we4289 + ) + + if(warnings_as_errors) + target_compile_options(AdvancedSettings + /WX + ) + endif() + elseif(win32-clang-msvc) + target_compile_options(AdvancedSettings + -Wcast-align + -Wdouble-promotion + -Wextra + -Wformat=2 + -Wmissing-variable-declarations + -Wmost + -Wnon-virtual-dtor + -Wold-style-cast + -Woverloaded-virtual + -Wshadow + -Wunused + -flto + /Gw + /W4 + /imsvc /imsvc /imsvc + /w14254 + /w14263 + /w14265 + /w14287 + /w14296 + /w14311 + /w14545 + /w14546 + /w14547 + /w14549 + /w14555 + /w14640 + /w14826 + /w14905 + /w14906 + /w14928 + /wd4127 + /we4289 + ) + endif() + +elseif(UNIX AND NOT MACOS) + if(noX11) + target_sources(AdvancedSettings PUBLIC + src/keyboard_input/input_sender_dummy.cpp + ) + else() + target_sources(AdvancedSettings PUBLIC + src/keyboard_input/input_sender_X11.cpp + ) + + target_link_libraries(AdvancedSettings PRIVATE + Xtst + X11 + ) + endif() + + if(noDBUS) + target_sources(AdvancedSettings PUBLIC + src/media_keys/media_keys_dummy.cpp + ) + else() + target_sources(AdvancedSettings PUBLIC + src/media_keys/media_keys_dbus.cpp + ) + + target_link_libraries(AdvancedSettings PRIVATE + Qt::DBus + ) + endif() + + if(noPulse) + target_sources(AdvancedSettings PUBLIC + src/tabcontrollers/audiomanager/AudioManagerDummy.cpp + ) + else() + target_sources(AdvancedSettings PUBLIC + src/tabcontrollers/audiomanager/AudioManagerPulse.cpp + ) + + target_link_libraries(AdvancedSettings PRIVATE + pulse + ) + endif() +elseif(MACOS) + target_sources(AdvancedSettings PUBLIC + src/keyboard_input/input_sender_dummy.cpp + src/media_keys/media_keys_dummy.cpp + src/tabcontrollers/audiomanager/AudioManagerDummy.cpp + ) +endif() diff --git a/advancedSettings.pro b/advancedSettings.pro deleted file mode 100644 index e5dbd508..00000000 --- a/advancedSettings.pro +++ /dev/null @@ -1,129 +0,0 @@ -QT += core gui qml quick multimedia widgets websockets -CONFIG += c++1z file_copies optimize_full - -DEFINES += ELPP_THREAD_SAFE ELPP_QT_LOGGING ELPP_NO_DEFAULT_LOG_FILE - -VERSION = "$$cat($$PWD/build_scripts/compile_version_string.txt)" -DEFINES += APPLICATION_VERSION=\\\"$$VERSION\\\" -# Qmake can't handle non-integers in the version string, -# so we take out anything after the dash. -SPLIT_VERSION_STRING = $$split(VERSION, -) -NUMERICAL_VERSION_NUMBER = $$member(SPLIT_VERSION_STRING, 0, 0) -VERSION = $$NUMERICAL_VERSION_NUMBER - -# Keep the literal version number in the description field for debugging. -QMAKE_TARGET_DESCRIPTION = "$$cat($$PWD/build_scripts/compile_version_string.txt)" - -lessThan(QT_MAJOR_VERSION, 5): error("requires Qt 5.12 or higher") -lessThan(QT_MINOR_VERSION, 12): error("requires Qt 5.12 or higher") - -TARGET = AdvancedSettings -TEMPLATE = app - -win32:DESTDIR = bin/win64/AdvancedSettings -unix:DESTDIR = bin/linux/AdvancedSettings - -include_dir = $$PWD/build_scripts/qt/ - -win32-msvc { - include($$include_dir/compilers/msvc.pri) -} -win32-clang-msvc{ - include($$include_dir/compilers/clang-msvc.pri) -} -*g++* { - include($$include_dir/compilers/gcc.pri) -} -#Look for anything clang that is not clang-msvc, since it does not -#allow all the same switches as regular clang. -*clang|*clang-g++|*clang-libc++ { - include($$include_dir/compilers/clang.pri) -} - -include($$include_dir/sources.pri) - -include($$include_dir/resources.pri) - -# Copy extra files -COPIES += resCopy readmeCopy licenseCopy packageFoldersCopy openvrApiCopy packageFilesCopy -COPY_DEST_DIR = $$OUT_PWD/$$DESTDIR - -resCopy.files = $$files(src/res) -resCopy.path = $$COPY_DEST_DIR - -readmeCopy.files = Readme.md -readmeCopy.path = $$COPY_DEST_DIR - -licenseCopy.files = LICENSE \ - third-party/openvr/LICENSE-VALVE \ - third-party/easylogging++/LICENSE-MIT -licenseCopy.path = $$COPY_DEST_DIR - -packageFoldersCopy.files = src/package_files/default_action_manifests -packageFoldersCopy.path = $$COPY_DEST_DIR - -packageFilesCopy.files = src/package_files/action_manifest.json src/package_files/manifest.vrmanifest -win32:packageFilesCopy.files += src/package_files/qt.conf src/package_files/restartvrserver.bat src/package_files/startdesktopmode.bat -packageFilesCopy.path = $$COPY_DEST_DIR - -win32:openvrApiCopy.files = third-party/openvr/bin/win64/openvr_api.dll -unix:openvrApiCopy.files = third-party/openvr/lib/linux64/libopenvr_api.so -openvrApiCopy.path = $$COPY_DEST_DIR - -# Deploy openssl when on win32 -win32 { - COPIES += opensslCopy - opensslCopy.files = third-party/openssl/libcrypto-1_1-x64.dll - opensslCopy.files += third-party/openssl/libssl-1_1-x64.dll - opensslCopy.files += third-party/openssl/LICENSE-OPENSSL - opensslCopy.path = $$COPY_DEST_DIR -} - -# Deploy resources and DLLs to exe dir on Windows -win32 { - WINDEPLOYQT_LOCATION = $$dirname(QMAKE_QMAKE)/windeployqt.exe - - CONFIG( debug, debug|release ) { - WINDEPLOYQT_BUILD_TARGET += "--debug" - } else { - WINDEPLOYQT_BUILD_TARGET += "--release" - } - - WINDEPLOYQT_OPTIONS = --dir $$COPY_DEST_DIR/qtdata \ - --libdir $$COPY_DEST_DIR \ - --plugindir $$COPY_DEST_DIR/qtdata/plugins \ - --no-system-d3d-compiler \ - --no-opengl-sw \ - $$WINDEPLOYQT_BUILD_TARGET \ - --qmldir $$PWD/src/res/qml \ - $$COPY_DEST_DIR/AdvancedSettings.exe - WINDEPLOYQT_FULL_LINE = "$$WINDEPLOYQT_LOCATION $$WINDEPLOYQT_OPTIONS" - - # Force windeployqt to run in cmd, because powershell has different syntax - # for running executables. - QMAKE_POST_LINK = cmd /c $$WINDEPLOYQT_FULL_LINE -} - -# Add make install support -unix { - isEmpty(PREFIX){ - PREFIX = /opt/OpenVR-AdvancedSettings - } - - message(PREFIX value is: \'$$PREFIX\'. `make install` will install to this location.) - - application.path = $$PREFIX - application.files = $$COPY_DEST_DIR - - INSTALLS += application -} - -debugSymbolsAndLogs { - message(Debug symbols and logging enabled.) - CONFIG += force_debug_info - DEFINES += ENABLE_DEBUG_LOGGING -} - -warnings_as_errors { - message(Warnings as errors enabled.) -} diff --git a/build_scripts/qt/compilers/clang-gcc-common-switches.pri b/build_scripts/qt/compilers/clang-gcc-common-switches.pri deleted file mode 100644 index c7c2a835..00000000 --- a/build_scripts/qt/compilers/clang-gcc-common-switches.pri +++ /dev/null @@ -1,16 +0,0 @@ -QMAKE_CXXFLAGS += -Wextra - -QMAKE_CXXFLAGS += -Wshadow - -QMAKE_CXXFLAGS += -Wold-style-cast - -QMAKE_CXXFLAGS += -Wnon-virtual-dtor - -QMAKE_CXXFLAGS += -Wcast-align -Wunused -Woverloaded-virtual -Wformat=2 - -QMAKE_CXXFLAGS += -Wdouble-promotion - -# Enable Link Time Optimization -QMAKE_CXXFLAGS += -flto -# Clang LTO requires the gold linker instead of ld -QMAKE_LFLAGS += -flto -fuse-ld=gold diff --git a/build_scripts/qt/compilers/clang-msvc.pri b/build_scripts/qt/compilers/clang-msvc.pri deleted file mode 100644 index bdd6f8a7..00000000 --- a/build_scripts/qt/compilers/clang-msvc.pri +++ /dev/null @@ -1,18 +0,0 @@ -include(common-msvc.pri) - -#win32-clang-msvc is unable to correctly build the first time -#with warnings as errors on. There seems to be an issue with the moc_predefs.h -#file not being built correctly when /WX is on. Until the issue is fixed, -#win32-clang-msvc is built without /WX. - -#clang-msvc does not enable the c++17 flag with qmake's c++1z flag. -QMAKE_CXXFLAGS += /std:c++17 - -include(clang-gcc-common-switches.pri) - -QMAKE_CXXFLAGS += -Wmost - -QMAKE_CXXFLAGS += -Weffc++ -Wmissing-variable-declarations - -#clang-msvc spams warnings on -Wconversion and -Wsign-conversion -# from the moc .cpp files including Qt stuff. diff --git a/build_scripts/qt/compilers/clang.pri b/build_scripts/qt/compilers/clang.pri deleted file mode 100644 index e938c5b5..00000000 --- a/build_scripts/qt/compilers/clang.pri +++ /dev/null @@ -1,62 +0,0 @@ -# comments are the value of CLANG_VERSION -CLANG_VERSION = $$system("clang++ --version | grep 'clang version'") -# clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final) -CLANG_VERSION = $$split(CLANG_VERSION, ' ') -# CLANG_VERSION is now a list, this is shown as spaces in QMAKE -# clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final) -CLANG_VERSION = $$member(CLANG_VERSION, 2) -# 6.0.0-1ubuntu2 -CLANG_VERSION = $$split(CLANG_VERSION, '.') -# 6 0 0-1ubuntu2 -CLANG_VERSION = $$member(CLANG_VERSION, 0) -# 6 - -greaterThan(CLANG_VERSION, 4) { - message('clang++' version is above 4. Using regular clang++.) - QMAKE_CXX = clang++ - QMAKE_LINK = clang++ -} -else { - message('clang++' version is not above 4. Attempting to use highest specific version.) - system("clang++-5 --version") { - QMAKE_CXX = clang++-5 - QMAKE_LINK = clang++-5 - message('clang++-5' found.) - } - system("clang++-6 --version") { - QMAKE_CXX = clang++-6 - QMAKE_LINK = clang++-6 - message('clang++-6' found.) - } - system("clang++-7 --version") { - QMAKE_CXX = clang++-7 - QMAKE_LINK = clang++-7 - message('clang++-7' found.) - } - system("clang++-8 --version") { - QMAKE_CXX = clang++-8 - QMAKE_LINK = clang++-8 - message('clang++-8' found.) - } -} - -system("$$QMAKE_CXX --version") - -include(clang-gcc-common-switches.pri) - -QMAKE_CXXFLAGS += -Wmost - -QMAKE_CXXFLAGS += -Wpedantic - -warnings_as_errors { - QMAKE_CXXFLAGS += -Werror -} - -#All includes from the third-party directory will not warn. -QMAKE_CXXFLAGS += --system-header-prefix=third-party -QMAKE_CXXFLAGS += --system-header-prefix=qt - -# Sign conversion warns on auto generated Qt MOC files. -QMAKE_CXXFLAGS += -Weffc++ -Wconversion -Wno-sign-conversion - -QMAKE_CXXFLAGS += -Wextra-semi -Wzero-as-null-pointer-constant -Wmissing-variable-declarations diff --git a/build_scripts/qt/compilers/common-msvc.pri b/build_scripts/qt/compilers/common-msvc.pri deleted file mode 100644 index 5347a674..00000000 --- a/build_scripts/qt/compilers/common-msvc.pri +++ /dev/null @@ -1,49 +0,0 @@ -#Removing -W3 from both FLAGS is necessary, otherwise compiler will give -#D9025: overriding '/W4' with '/W3' -QMAKE_CFLAGS_WARN_ON -= -W3 -QMAKE_CXXFLAGS_WARN_ON -= -W3 -#C4127 is a warning in qvarlengtharray.h that can not be turned off -#on the current version of MSVC. -QMAKE_CXXFLAGS += /W4 /wd4127 -# The codecvt header being used in AudioManagerWindows.cpp is deprecated by the standard, -# but no suitable replacement has been standardized yet. It is possible to use the Windows -# specific MultiByteToWideChar() and WideCharToMultiByte() from -DEFINES += _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING - -# Enables Whole Program Optimization -QMAKE_CXXFLAGS += /Gw - -# 'operator': conversion from 'type1:field_bits' to 'type2:field_bits', possible loss of data -QMAKE_CXXFLAGS += /w14254 -# 'function': member function does not override any base class virtual member function -QMAKE_CXXFLAGS += /w14263 -# 'classname': class has virtual functions, but destructor is not virtual instances of this class may not be destructed correctly -QMAKE_CXXFLAGS += /w14265 -# 'operator': unsigned/negative constant mismatch -QMAKE_CXXFLAGS += /w14287 -# nonstandard extension used: 'variable': loop control variable declared in the for-loop is used outside the for-loop scope -QMAKE_CXXFLAGS += /we4289 -# 'operator': expression is always 'boolean_value' -QMAKE_CXXFLAGS += /w14296 -# 'variable': pointer truncation from 'type1' to 'type2' -QMAKE_CXXFLAGS += /w14311 -# expression before comma evaluates to a function which is missing an argument list -QMAKE_CXXFLAGS += /w14545 -# function call before comma missing argument list -QMAKE_CXXFLAGS += /w14546 -# 'operator': operator before comma has no effect; expected operator with side-effect -QMAKE_CXXFLAGS += /w14547 -# 'operator': operator before comma has no effect; did you intend 'operator'? -QMAKE_CXXFLAGS += /w14549 -# expression has no effect; expected expression with side-effect -QMAKE_CXXFLAGS += /w14555 -# Enable warning on thread un-safe static member initialization -QMAKE_CXXFLAGS += /w14640 -# Conversion from 'type1' to 'type_2' is sign-extended. This may cause unexpected runtime behavior. -QMAKE_CXXFLAGS += /w14826 -# wide string literal cast to 'LPSTR' -QMAKE_CXXFLAGS += /w14905 -# string literal cast to 'LPWSTR' -QMAKE_CXXFLAGS += /w14906 -# illegal copy-initialization; more than one user-defined conversion has been implicitly applied -QMAKE_CXXFLAGS += /w14928 diff --git a/build_scripts/qt/compilers/gcc.pri b/build_scripts/qt/compilers/gcc.pri deleted file mode 100644 index dc86954d..00000000 --- a/build_scripts/qt/compilers/gcc.pri +++ /dev/null @@ -1,44 +0,0 @@ -GCC_VERSION = $$system("g++ -dumpversion") -greaterThan(GCC_VERSION, 6) { - message('g++' version is above 6. Using regular g++.) -} -else { - message('g++' version is not above 6. Attempting to use highest specific version.) - system(g++-7 --version) { - message('g++-7' found.) - QMAKE_CXX = g++-7 - QMAKE_LINK = g++-7 - } - system(g++-8 --version) { - message('g++-8' found.) - QMAKE_CXX = g++-8 - QMAKE_LINK = g++-8 - } - system(g++-9 --version) { - message('g++-9' found.) - QMAKE_CXX = g++-9 - QMAKE_LINK = g++-9 - } -} - -system("$$QMAKE_CXX --version") - -include(clang-gcc-common-switches.pri) - -QMAKE_CXXFLAGS += -Wpedantic - -warnings_as_errors { - QMAKE_CXXFLAGS += -Werror -} - -# GCC only switches -QMAKE_CXXFLAGS += -Wduplicated-branches -Wduplicated-cond -Wlogical-op -Wrestrict -Wnull-dereference - -# Sign conversion warns on auto generated Qt MOC files. -QMAKE_CXXFLAGS += -Wconversion -Wno-sign-conversion - -QMAKE_CXXFLAGS += -Wzero-as-null-pointer-constant - -# Qmake will append this even though higher optimization levels are used. -QMAKE_LFLAGS_RELEASE -= -Wl,-O1 -QMAKE_LFLAGS += -Wl,-O3 -O3 diff --git a/build_scripts/qt/compilers/msvc.pri b/build_scripts/qt/compilers/msvc.pri deleted file mode 100644 index 4ff8b445..00000000 --- a/build_scripts/qt/compilers/msvc.pri +++ /dev/null @@ -1,12 +0,0 @@ -include(common-msvc.pri) - -warnings_as_errors { - # Warnings as errors - QMAKE_CXXFLAGS += /WX -} - -# Enables Link Time Optimization -QMAKE_CXXFLAGS += /GL - -# Force standards-conformance -QMAKE_CXXFLAGS += /permissive- diff --git a/build_scripts/qt/resources.pri b/build_scripts/qt/resources.pri deleted file mode 100644 index 4d0e0c50..00000000 --- a/build_scripts/qt/resources.pri +++ /dev/null @@ -1,69 +0,0 @@ -project_dir = $$PWD/../../ - -win32:LIBS += -L"$$project_dir/third-party/openvr/lib/win64" -luser32 -lole32 -unix:LIBS += -L"$$project_dir/third-party/openvr/lib/linux64" -LIBS += -lopenvr_api - -RESOURCES += src/res/resources.qrc - -DISTFILES += \ - src/res/sounds/alarm01.wav \ - src/res/sounds/click.wav \ - src/res/sounds/focus.wav \ - src/res/img/audio/microphone/ptt_notification.png \ - src/res/img/audio/microphone/ptt_notification.svg \ - src/res/img/battery/* \ - src/res/img/icons/* \ - src/res/img/alarm/* \ - src/res/img/video/* \ - src/res/img/chaperone/* \ - src/res/qml/qmldir \ - src/res/qml/audio_page/* \ - src/res/qml/ChaperonePage.qml \ - src/res/qml/ChaperoneWarningsPage.qml \ - src/res/qml/chaperone_page/* \ - src/res/qml/chaperone_page/change_orientation/* \ - src/res/qml/chaperone_page/chaperone_additional/* \ - src/res/qml/chaperone_page/chaperone_additional/chaperoneboundscolor/* \ - src/res/qml/chaperone_page/chaperone_additional/chaperonetype/* \ - src/res/qml/chaperone_page/chaperone_additional/chaperonemisc/* \ - src/res/qml/FixFloorPage.qml \ - src/res/qml/PlayspacePage.qml \ - src/res/qml/motion_page/* \ - src/res/qml/motion_page/gravity/* \ - src/res/qml/motion_page/height_toggle/* \ - src/res/qml/motion_page/space_drag/* \ - src/res/qml/RootPage.qml \ - src/res/qml/SettingsPage.qml \ - src/res/qml/StatisticsPage.qml \ - src/res/qml/steamvr_page/SteamVRPage.qml \ - src/res/qml/steamvr_page/steamvr_additional/* \ - src/res/qml/steamvr_page/camera/* \ - src/res/qml/steamvr_page/steamvrmisc/* \ - src/res/qml/steamvr_page/steamvrbind/* \ - src/res/qml/utilities_page/* \ - src/res/qml/utilities_page/media_keys/* \ - src/res/qml/utilities_page/keyboard_utils/* \ - src/res/qml/utilities_page/alarm_clock/* \ - src/res/qml/utilities_page/misc/* \ - src/res/qml/audio_page/dialog_boxes/* \ - src/res/qml/audio_page/device_selector/* \ - src/res/qml/audio_page/proximity/* \ - src/res/qml/audio_page/push_to_talk/* \ - src/res/qml/audio_page/profiles/* \ - src/res/qml/video_page/* \ - src/res/qml/video_page/brightness/* \ - src/res/qml/video_page/color/* \ - src/res/qml/video_page/supersampling/* \ - src/res/qml/video_page/miscvid/* \ - src/res/qml/video_page/profiles/* \ - src/res/qml/video_page/dialogboxes/* \ - src/res/qml/video_page/overlaycolorbright/* \ - src/res/qml/rotation_page/* \ - src/res/qml/rotation_page/redirected/* \ - src/res/qml/rotation_page/snap_turn/* \ - src/res/qml/rotation_page/space_turn/* \ - src/res/qml/rotation_page/view_ratchet/* \ - src/res/qml/common/* - -win32:RC_ICONS += src/res/img/icons/advicon256px.ico diff --git a/build_scripts/qt/sources.pri b/build_scripts/qt/sources.pri deleted file mode 100644 index 8b8499f1..00000000 --- a/build_scripts/qt/sources.pri +++ /dev/null @@ -1,157 +0,0 @@ -SOURCES += src/main.cpp\ - src/overlaycontroller.cpp \ - src/tabcontrollers/AudioTabController.cpp \ - src/tabcontrollers/ChaperoneTabController.cpp \ - src/tabcontrollers/FixFloorTabController.cpp \ - src/tabcontrollers/MoveCenterTabController.cpp \ - src/tabcontrollers/SettingsTabController.cpp \ - src/tabcontrollers/StatisticsTabController.cpp \ - src/tabcontrollers/SteamVRTabController.cpp \ - src/tabcontrollers/UtilitiesTabController.cpp \ - src/tabcontrollers/VideoTabController.cpp \ - src/tabcontrollers/RotationTabController.cpp\ - src/utils/ChaperoneUtils.cpp \ - src/openvr/openvr_init.cpp \ - src/openvr/ivrinput.cpp \ - src/openvr/ovr_settings_wrapper.cpp \ - src/openvr/ovr_overlay_wrapper.cpp \ - src/openvr/ovr_system_wrapper.cpp \ - src/openvr/lh_console_util.cpp \ - src/openvr/ovr_application_wrapper.cpp \ - src/utils/setup.cpp \ - src/utils/paths.cpp \ - src/utils/FrameRateUtils.cpp \ - src/keyboard_input/keyboard_input.cpp \ - src/keyboard_input/input_parser.cpp \ - src/settings/settings.cpp \ - src/settings/settings_object.cpp \ - src/alarm_clock/vr_alarm.cpp \ - src/utils/update_rate.cpp \ - - - -HEADERS += src/overlaycontroller.h \ - src/tabcontrollers/AudioTabController.h \ - src/tabcontrollers/ChaperoneTabController.h \ - src/tabcontrollers/FixFloorTabController.h \ - src/tabcontrollers/MoveCenterTabController.h \ - src/tabcontrollers/SettingsTabController.h \ - src/tabcontrollers/StatisticsTabController.h \ - src/tabcontrollers/SteamVRTabController.h \ - src/tabcontrollers/UtilitiesTabController.h \ - src/tabcontrollers/VideoTabController.h \ - src/tabcontrollers/audiomanager/AudioManager.h \ - src/tabcontrollers/RotationTabController.h\ - src/keyboard_input/keyboard_input.h \ - src/media_keys/media_keys.h \ - src/utils/Matrix.h \ - src/utils/ChaperoneUtils.h \ - src/quaternion/quaternion.h \ - src/openvr/openvr_init.h \ - src/openvr/ivrinput_action.h \ - src/openvr/ivrinput_manifest.h \ - src/openvr/ivrinput_action_set.h \ - src/openvr/ivrinput_input_source.h \ - src/openvr/ivrinput.h \ - src/openvr/ovr_settings_wrapper.h \ - src/openvr/ovr_overlay_wrapper.h \ - src/openvr/ovr_system_wrapper.h \ - src/openvr/ovr_application_wrapper.h \ - src/openvr/lh_console_util.h \ - src/utils/setup.h \ - src/utils/paths.h \ - src/utils/FrameRateUtils.h \ - src/keyboard_input/input_parser.h \ - src/keyboard_input/input_sender.h \ - src/settings/settings.h \ - src/settings/internal/setting_value.h \ - src/settings/internal/settings_internal.h \ - src/settings/internal/settings_controller.h \ - src/settings/internal/specific_setting_value.h \ - src/settings/settings_object.h \ - src/settings/internal/settings_object_data.h \ - src/alarm_clock/vr_alarm.h \ - src/settings/internal/settings_object_data.h \ - src/settings/internal/settings_object_data.h \ - src/utils/update_rate.h \ - - -win32 { - SOURCES += src/tabcontrollers/audiomanager/AudioManagerWindows.cpp \ - src/keyboard_input/input_sender_win.cpp \ - src/media_keys/media_keys_win.cpp - HEADERS += src/tabcontrollers/audiomanager/AudioManagerWindows.h -} - -unix:!macx { - !noX11 { - message(X11 features enabled.) - SOURCES += src/keyboard_input/input_sender_X11.cpp - CONFIG += x11 - LIBS += -lXtst - } - else { - message(X11 features disabled.) - SOURCES += src/keyboard_input/input_sender_dummy.cpp - } - - !noDBUS { - message(DBUS features enabled.) - SOURCES += src/media_keys/media_keys_dbus.cpp - QT += dbus - } - else { - message(DBUS features disabled.) - SOURCES += src/media_keys/media_keys_dummy.cpp - } - - !noPulse { - message(PulseAudio features enabled.) - SOURCES += src/tabcontrollers/audiomanager/AudioManagerPulse.cpp - HEADERS += src/tabcontrollers/audiomanager/AudioManagerPulse.h \ - src/tabcontrollers/audiomanager/AudioManagerPulse_internal.h - LIBS += -lpulse - } - else { - message(PulseAudio features disabled.) - SOURCES += src/tabcontrollers/audiomanager/AudioManagerDummy.cpp - HEADERS += src/tabcontrollers/audiomanager/AudioManagerDummy.h - } -} - -macx { - SOURCES += src/keyboard_input/input_sender_dummy.cpp \ - src/media_keys/media_keys_dummy.cpp \ - src/tabcontrollers/audiomanager/AudioManagerDummy.cpp - HEADERS += src/tabcontrollers/audiomanager/AudioManagerDummy.h - -} - -win32-msvc { - INCLUDEPATH += third-party/openvr/headers \ - third-party/easylogging++ \ - third-party/policyconfig -} - -win32-clang-msvc { - QMAKE_CXXFLAGS += /imsvc "$$PWD/../../third-party/openvr/headers" - QMAKE_CXXFLAGS += /imsvc "$$PWD/../../third-party/easylogging++" - QMAKE_CXXFLAGS += /imsvc "$$PWD/../../third-party/policyconfig" -} - -# Anything g++ or clang -# In order to suppress warnings in third party headers -*clang|*clang-g++|*clang-libc++|*g++* { - #Force Linux to look into the current dir for the OpenVR lib - QMAKE_LFLAGS += '-Wl,-rpath,\'\$$ORIGIN\'' - - QMAKE_CXXFLAGS += -isystem $$[QT_INSTALL_HEADERS] - QMAKE_CXXFLAGS += -isystem $$[QT_INSTALL_HEADERS]/QtCore - QMAKE_CXXFLAGS += -isystem $$[QT_INSTALL_HEADERS]/QtGui - - QMAKE_CXXFLAGS += -isystem $$PWD/../../third-party/openvr/headers - QMAKE_CXXFLAGS += -isystem $$PWD/../../third-party/easylogging++ -} - -# easylogging++ used to be a header only lib. Now requires easylogging++.cc -SOURCES += third-party/easylogging++/easylogging++.cc diff --git a/build_scripts/win/env.ps1.in b/build_scripts/win/env.ps1.in new file mode 100644 index 00000000..9ad382fd --- /dev/null +++ b/build_scripts/win/env.ps1.in @@ -0,0 +1,5 @@ +if ($null -ne $env:_SAVED_PATH) { + $env:PATH=$env:_SAVED_PATH; +} +$env:_SAVED_PATH=$env:PATH; +$env:PATH+=";@NATIVE_QT_ROOT@\bin;@NATIVE_PROJECT_SOURCE_DIR@\third-party\openvr\bin\win64"; \ No newline at end of file diff --git a/build_scripts/win/env.sh.in b/build_scripts/win/env.sh.in new file mode 100644 index 00000000..14ba9b60 --- /dev/null +++ b/build_scripts/win/env.sh.in @@ -0,0 +1,9 @@ +export _SAVED_PATH="${_SAVED_PATH:-}" +if [ ! -z "$_SAVED_PATH" ]; then + export PATH="$_SAVED_PATH" +fi +export _SAVED_PATH="$PATH" +export PATH="$PATH:$(echo "@NATIVE_QT_ROOT@"|sed -E 's/(\w):/\/\L\1/')/bin:$(echo "@PROJECT_SOURCE_DIR@"|sed -E 's/(\w):/\/\L\1/')/third-party/openvr/bin/win64" + +echo $_SAVED_PATH +echo $PATH \ No newline at end of file diff --git a/build_scripts/win/qt.conf.in b/build_scripts/win/qt.conf.in new file mode 100644 index 00000000..48fd995a --- /dev/null +++ b/build_scripts/win/qt.conf.in @@ -0,0 +1,2 @@ +[Paths] +Plugins=@QT_ROOT@\\plugins diff --git a/cmake/CPackConfig.cmake b/cmake/CPackConfig.cmake new file mode 100644 index 00000000..6d518caa --- /dev/null +++ b/cmake/CPackConfig.cmake @@ -0,0 +1,8 @@ +set(CPACK_PACKAGE_NAME "${PROJECT_NAME}") +set(CPACK_PACKAGE_VENDOR "OVRAS Team") + +# NSIS installer config +set(CPACK_PACKAGE_ICON "${CMAKE_SOURCE_DIR}/src/res/img/icons/advicon256px.ico") +set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENSE") +set(CPACK_NSIS_PACKAGE_NAME "${PROJECT_NAME} ${CMAKE_VERSION}") +set(CPACK_NSIS_MODIFY_PATH OFF) diff --git a/compile_commands.json b/compile_commands.json new file mode 120000 index 00000000..25eb4b2b --- /dev/null +++ b/compile_commands.json @@ -0,0 +1 @@ +build/compile_commands.json \ No newline at end of file diff --git a/src/alarm_clock/vr_alarm.cpp b/src/alarm_clock/vr_alarm.cpp index 35e96969..3573a533 100644 --- a/src/alarm_clock/vr_alarm.cpp +++ b/src/alarm_clock/vr_alarm.cpp @@ -1,8 +1,12 @@ -#include #include "../tabcontrollers/UtilitiesTabController.h" #include "vr_alarm.h" #include "../openvr/ovr_overlay_wrapper.h" #include "../utils/update_rate.h" +#include + +#include +#include +#include namespace alarm_clock { @@ -20,8 +24,10 @@ VrAlarm::VrAlarm() ovr_overlay_wrapper::hideOverlay( m_alarmOverlayHandle ); - const auto filename = "/res/img/alarm/alarm_activated.png"; - ovr_overlay_wrapper::setOverlayFromFile( m_alarmOverlayHandle, filename ); + // Only need to set it once, no need to keep it in memory + QImage alarmIcon( QString( ":/alarm/alarm_activated.png" ) ); + ovr_overlay_wrapper::setOverlayFromQImage( m_alarmOverlayHandle, + alarmIcon ); ovr_overlay_wrapper::setOverlayWidthInMeters( m_alarmOverlayHandle, 0.3f ); @@ -76,13 +82,14 @@ void VrAlarm::checkAlarmStatus() && timeToAlarmActivation > 0; if ( activateAlarm ) { - LOG( INFO ) << "Alarm fired at " << m_alarm.hour() << ":" - << m_alarm.minute() << ":" << m_alarm.second() << "."; + qInfo() << "Alarm fired at " << m_alarm.hour() << ":" + << m_alarm.minute() << ":" << m_alarm.second() << "."; showAlarmNotification(); setAlarmEnabled( false ); std::thread t( - []( vr::VROverlayHandle_t overlayHandle ) { + []( vr::VROverlayHandle_t overlayHandle ) + { // This will freeze the overlay for 3 seconds std::this_thread::sleep_for( std::chrono::seconds( 3 ) ); ovr_overlay_wrapper::hideOverlay( overlayHandle ); @@ -102,9 +109,9 @@ void VrAlarm::setAlarmTime( const int hour, const int minute, const int second ) { if ( !QTime::isValid( hour, minute, second ) ) { - LOG( ERROR ) << "setAlarmTime passed invalid time values: '" << hour - << "' hours, '" << minute << "' minutes, '" << second - << "' seconds."; + qCritical() << "setAlarmTime passed invalid time values: '" << hour + << "' hours, '" << minute << "' minutes, '" << second + << "' seconds."; } setSetting( IntSetting::UTILITY_alarmHour, hour ); @@ -119,20 +126,20 @@ void VrAlarm::modAlarmTime( const int hour, const int minute, const int second ) { if ( hour > 22 || hour < -22 ) { - LOG( ERROR ) << "modAlarmTime called with incorrect hour value: '" - << hour << "'. Values not applied."; + qCritical() << "modAlarmTime called with incorrect hour value: '" + << hour << "'. Values not applied."; return; } if ( minute > 58 || minute < -58 ) { - LOG( ERROR ) << "modAlarmTime called with incorrect minute value: '" - << minute << "'. Values not applied."; + qCritical() << "modAlarmTime called with incorrect minute value: '" + << minute << "'. Values not applied."; return; } if ( second > 58 || minute < -58 ) { - LOG( ERROR ) << "modAlarmTime called with incorrect second value: '" - << second << "'. Values not applied."; + qCritical() << "modAlarmTime called with incorrect second value: '" + << second << "'. Values not applied."; return; } diff --git a/src/keyboard_input/input_parser.cpp b/src/keyboard_input/input_parser.cpp index 91d1b53a..3aff1838 100644 --- a/src/keyboard_input/input_parser.cpp +++ b/src/keyboard_input/input_parser.cpp @@ -1,5 +1,8 @@ #include "input_parser.h" +#include +#include + std::optional getModifier( const char& character ) noexcept { switch ( character ) @@ -50,7 +53,7 @@ std::optional getFunctionNumber( const char& character ) noexcept return Token::KEY_F9; default: - LOG( INFO ) << "Unknown function key number: " << character; + qInfo() << "Unknown function key number: " << character; return std::nullopt; } } @@ -80,7 +83,7 @@ std::optional getFunctionNumberExtended( const char& character ) noexcept case '9': return Token::KEY_F19; default: - LOG( INFO ) << "Unknown function key number: " << character; + qInfo() << "Unknown function key number: " << character; return std::nullopt; } } @@ -210,7 +213,7 @@ std::vector if ( !isupper( *ch ) || isspace( *ch ) ) { - LOG( INFO ) << "Unknown character found in sequence: " << *ch; + qInfo() << "Unknown character found in sequence: " << *ch; continue; } // Everything below is upper case diff --git a/src/keyboard_input/input_parser.h b/src/keyboard_input/input_parser.h index 6b29ab67..54a3510e 100644 --- a/src/keyboard_input/input_parser.h +++ b/src/keyboard_input/input_parser.h @@ -3,7 +3,6 @@ #include #include #include -#include enum class Token { diff --git a/src/keyboard_input/input_sender.h b/src/keyboard_input/input_sender.h index 81c94999..5dfba81d 100644 --- a/src/keyboard_input/input_sender.h +++ b/src/keyboard_input/input_sender.h @@ -1,6 +1,5 @@ #pragma once #include "input_parser.h" -#include enum class KeyStatus { diff --git a/src/keyboard_input/input_sender_win.cpp b/src/keyboard_input/input_sender_win.cpp index d98024f9..c39d3715 100644 --- a/src/keyboard_input/input_sender_win.cpp +++ b/src/keyboard_input/input_sender_win.cpp @@ -2,6 +2,8 @@ #include #include #include +#include +#include WORD convertToVirtualKeycode( const Token token ) { @@ -183,13 +185,13 @@ void sendKeyboardInputRaw( std::vector inputs ) 0, nullptr ) ) { - LOG( ERROR ) + qCritical() << "Error calling SendInput(): Could not get error message (" << errCode << ")"; } else { - LOG( ERROR ) << "Error calling SendInput(): " << err; + qCritical() << "Error calling SendInput(): " << err; } } } diff --git a/src/main.cpp b/src/main.cpp index 9a5dc596..fa5d6f00 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,6 +1,11 @@ #include "utils/setup.h" #include "settings/settings.h" #include "openvr/ovr_settings_wrapper.h" + +#include +#include +#include + #ifdef _WIN64 # include extern "C" __declspec( dllexport ) DWORD NvOptimusEnablement = 0x00000001; @@ -8,16 +13,13 @@ extern "C" __declspec( dllexport ) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001; #endif -INITIALIZE_EASYLOGGINGPP - int main( int argc, char* argv[] ) { setUpLogging(); - LOG( INFO ) << "Settings File: " - << settings::initializeAndGetSettingsPath(); + qInfo() << "Settings File: " << settings::initializeAndGetSettingsPath(); - LOG( INFO ) << settings::getSettingsAndValues(); + qInfo() << settings::getSettingsAndValues(); QCoreApplication::setAttribute( Qt::AA_Use96Dpi ); QCoreApplication::setAttribute( Qt::AA_UseDesktopOpenGL ); @@ -30,8 +32,6 @@ int main( int argc, char* argv[] ) mainEventLoop.setApplicationVersion( application_strings::applicationVersionString ); - qInstallMessageHandler( mainQtMessageHandler ); - const auto commandLineArgs = argument::returnCommandLineParser( mainEventLoop ); @@ -51,34 +51,25 @@ int main( int argc, char* argv[] ) { QQmlEngine qmlEngine; - advsettings::OverlayController controller( commandLineArgs.desktopMode, - commandLineArgs.forceNoSound, - qmlEngine ); - - constexpr auto widgetPath = "res/qml/common/mainwidget.qml"; - const auto path = paths::binaryDirectoryFindFile( widgetPath ); - - if ( !path.has_value() ) - { - LOG( ERROR ) << "Unable to find file '" << widgetPath << "'."; - throw std::runtime_error( - "Unable to find critical file. See log for more information." ); - } + std::unique_ptr controller( + new advsettings::OverlayController( commandLineArgs.desktopMode, + commandLineArgs.forceNoSound, + qmlEngine ) ); const auto url - = QUrl::fromLocalFile( QString::fromStdString( ( *path ) ) ); + = QUrl( "qrc:/qt/qml/AdvancedSettings/common/mainwidget.qml" ); QQmlComponent component( &qmlEngine, url ); auto errors = component.errors(); for ( auto& e : errors ) { - LOG( ERROR ) << "QML Error: " << e.toString().toStdString() - << std::endl; + qCritical() << "QML Error: " + << e.toString().toStdString(); //<< std::endl; } auto quickObj = component.create(); - controller.SetWidget( qobject_cast( quickObj ), - application_strings::applicationDisplayName, - application_strings::applicationKey ); + controller->SetWidget( qobject_cast( quickObj ), + application_strings::applicationDisplayName, + application_strings::applicationKey ); // Attempts to install the application manifest on all "regular" starts. if ( !commandLineArgs.forceNoManifest ) @@ -99,7 +90,7 @@ int main( int argc, char* argv[] ) } catch ( std::exception& e ) { - LOG( ERROR ) << e.what(); + qCritical() << e.what(); } } @@ -129,7 +120,7 @@ int main( int argc, char* argv[] ) } catch ( const std::exception& e ) { - LOG( FATAL ) << e.what(); + qFatal() << e.what(); return ReturnErrorCode::GENERAL_FAILURE; } } diff --git a/src/media_keys/media_keys.h b/src/media_keys/media_keys.h index e83f135e..5ded3e5c 100644 --- a/src/media_keys/media_keys.h +++ b/src/media_keys/media_keys.h @@ -1,5 +1,4 @@ #pragma once -#include #include #include diff --git a/src/media_keys/media_keys_dbus.cpp b/src/media_keys/media_keys_dbus.cpp index fc1eeb67..6edb4faf 100644 --- a/src/media_keys/media_keys_dbus.cpp +++ b/src/media_keys/media_keys_dbus.cpp @@ -3,6 +3,8 @@ #include #include #include +#include +#include namespace keyboardinput { @@ -10,7 +12,7 @@ void callMethodForAllMediaPlayerAvailableServices( const QString& method ) { if ( !QDBusConnection::sessionBus().isConnected() ) { - LOG( ERROR ) << "Media Keys: Unable to connect to DBUS session bus."; + qCritical() << "Media Keys: Unable to connect to DBUS session bus."; return; } @@ -18,9 +20,9 @@ void callMethodForAllMediaPlayerAvailableServices( const QString& method ) = QDBusConnection::sessionBus().interface()->registeredServiceNames(); if ( !names.isValid() ) { - LOG( ERROR ) + qCritical() << "Media Keys: Error getting DBUS registered service names:"; - LOG( ERROR ) << names.error().message(); + qCritical() << names.error().message(); } foreach ( QString name, names.value() ) diff --git a/src/media_keys/media_keys_win.cpp b/src/media_keys/media_keys_win.cpp index 33190592..8026904f 100644 --- a/src/media_keys/media_keys_win.cpp +++ b/src/media_keys/media_keys_win.cpp @@ -1,6 +1,8 @@ #include "media_keys.h" #include "src/keyboard_input/input_sender.h" #include +#include +#include namespace keyboardinput { @@ -45,13 +47,13 @@ void sendKeyboardInputRaw( std::vector inputs ) 0, nullptr ) ) { - LOG( ERROR ) + qCritical() << "Error calling SendInput(): Could not get error message (" << errCode << ")"; } else { - LOG( ERROR ) << "Error calling SendInput(): " << err; + qCritical() << "Error calling SendInput(): " << err; } } } diff --git a/src/openvr/ivrinput.cpp b/src/openvr/ivrinput.cpp index ef27afec..acdb834d 100644 --- a/src/openvr/ivrinput.cpp +++ b/src/openvr/ivrinput.cpp @@ -3,7 +3,8 @@ #include #include #include -#include +#include +#include namespace input { @@ -30,8 +31,8 @@ vr::InputDigitalActionData_t getDigitalActionData( DigitalAction& action ) if ( error != vr::EVRInputError::VRInputError_None ) { - LOG( ERROR ) << "Error getting IVRInput Digital Action Data for handle " - << action.name() << ". SteamVR Error: " << error; + qCritical() << "Error getting IVRInput Digital Action Data for handle " + << action.name() << ". SteamVR Error: " << error; } return handleData; @@ -60,8 +61,8 @@ vr::InputAnalogActionData_t getAnalogActionData( AnalogAction& action ) if ( error != vr::EVRInputError::VRInputError_None ) { - LOG( ERROR ) << "Error getting IVRInput Digital Action Data for handle " - << action.name() << ". SteamVR Error: " << error; + qCritical() << "Error getting IVRInput Digital Action Data for handle " + << action.name() << ". SteamVR Error: " << error; } return handleData; @@ -454,7 +455,7 @@ void SteamIVRInput::UpdateStates() if ( error != vr::EVRInputError::VRInputError_None ) { - LOG( ERROR ) + qCritical() << "Error during IVRInput action state update. OpenVR Error: " << error; } diff --git a/src/openvr/ivrinput_action.h b/src/openvr/ivrinput_action.h index f00bdb59..3206d591 100644 --- a/src/openvr/ivrinput_action.h +++ b/src/openvr/ivrinput_action.h @@ -1,6 +1,7 @@ #pragma once #include -#include +#include +#include namespace input { @@ -30,8 +31,8 @@ class Action if ( error != vr::EVRInputError::VRInputError_None ) { - LOG( ERROR ) << "Error getting handle for '" << actionName - << "'. OpenVR Error: " << error; + qCritical() << "Error getting handle for '" << actionName + << "'. OpenVR Error: " << error; } } /*! diff --git a/src/openvr/ivrinput_action_set.h b/src/openvr/ivrinput_action_set.h index 44603325..29b56965 100644 --- a/src/openvr/ivrinput_action_set.h +++ b/src/openvr/ivrinput_action_set.h @@ -1,6 +1,7 @@ #pragma once #include -#include +#include +#include namespace input { @@ -16,8 +17,8 @@ class ActionSet auto error = vr::VRInput()->GetActionSetHandle( setName, &handle ); if ( error != vr::EVRInputError::VRInputError_None ) { - LOG( ERROR ) << "Error getting handle for '" << setName - << "'. OpenVR Error: " << error; + qCritical() << "Error getting handle for '" << setName + << "'. OpenVR Error: " << error; } m_activeActionSet.ulActionSet = handle; diff --git a/src/openvr/ivrinput_input_source.h b/src/openvr/ivrinput_input_source.h index 995453ba..fc9e8218 100644 --- a/src/openvr/ivrinput_input_source.h +++ b/src/openvr/ivrinput_input_source.h @@ -1,6 +1,7 @@ #pragma once #include -#include +#include +#include namespace input { @@ -17,9 +18,8 @@ class InputSource if ( error != vr::EVRInputError::VRInputError_None ) { - LOG( ERROR ) << "Error getting input handle for '" - << inputSourceName - << "'. OpenVR Input Error: " << error; + qCritical() << "Error getting input handle for '" << inputSourceName + << "'. OpenVR Input Error: " << error; } } /*! diff --git a/src/openvr/ivrinput_manifest.h b/src/openvr/ivrinput_manifest.h index 2e12cef9..002120e3 100644 --- a/src/openvr/ivrinput_manifest.h +++ b/src/openvr/ivrinput_manifest.h @@ -1,6 +1,7 @@ #pragma once #include -#include +#include +#include #include "../utils/paths.h" namespace input @@ -19,8 +20,8 @@ class Manifest if ( !actionManifestPath.has_value() ) { - LOG( ERROR ) << "Could not find action manifest. Action manifests " - "not initialized."; + qCritical() << "Could not find action manifest. Action manifests " + "not initialized."; return; } @@ -29,8 +30,8 @@ class Manifest auto error = vr::VRInput()->SetActionManifestPath( validManifestPath ); if ( error != vr::EVRInputError::VRInputError_None ) { - LOG( ERROR ) << "Error setting action manifest path: " - << validManifestPath << ". OpenVR Error: " << error; + qCritical() << "Error setting action manifest path: " + << validManifestPath << ". OpenVR Error: " << error; } } diff --git a/src/openvr/lh_console_util.cpp b/src/openvr/lh_console_util.cpp index 41dfdacf..d67fa7c5 100644 --- a/src/openvr/lh_console_util.cpp +++ b/src/openvr/lh_console_util.cpp @@ -1,4 +1,7 @@ #include "lh_console_util.h" +#include +#include +#include namespace lh_con_util { @@ -6,12 +9,12 @@ bool LHCUtil::FindAll() { if ( !FindAllRX() ) { - LOG( ERROR ) << "Find All Recievers Failed"; + qCritical() << "Find All Recievers Failed"; return false; } if ( !FindAllTX() ) { - LOG( ERROR ) << "Find All Transmitters Failed"; + qCritical() << "Find All Transmitters Failed"; return false; } return true; @@ -26,7 +29,7 @@ bool LHCUtil::FindAllRX() QString output = QString( lhProcess->readAllStandardOutput() ); QStringList outputLines - = output.split( QRegExp( "[\r\n]" ), QString::SkipEmptyParts ); + = output.split( QRegularExpression( "[\r\n]" ), Qt::SkipEmptyParts ); bool RecieverStart = false; for ( auto OutputLine : outputLines ) @@ -44,7 +47,7 @@ bool LHCUtil::FindAllRX() } OutputLine.simplified().remove( " " ); OutputLine.remove( 0, 1 ); - // LOG( WARNING ) << OutputLine << std::endl; + // qWarning() << OutputLine << std::endl; RXTX_Pairs_.push_back( RXTX_Pair{ OutputLine, " ", true, false } ); } } @@ -53,21 +56,21 @@ bool LHCUtil::FindAllRX() bool LHCUtil::FindConnectedTX( QString RXSerial ) { - LOG( WARNING ) << RXSerial; + qWarning() << RXSerial; QProcess* lhProcess = new QProcess(); lhProcess->start( path_, QStringList() << "/serial" << RXSerial << "exit" ); lhProcess->waitForFinished(); QString output = QString( lhProcess->readAllStandardOutput() ); QStringList outputLines - = output.split( QRegExp( "[\r\n]" ), QString::SkipEmptyParts ); + = output.split( QRegularExpression( "[\r\n]" ), Qt::SkipEmptyParts ); // std::vector OutputLines // = exec( ( "\"" + path_ + "\" /serial " + RXSerial + " exit" ).c_str() // ); bool lhConFound = false; for ( auto outputLine : outputLines ) { - // LOG( WARNING ) << outputLine; + // qWarning() << outputLine; if ( outputLine.contains( "Connected to receiver" ) ) { auto splitList = outputLine.split( ":" ); @@ -84,7 +87,7 @@ bool LHCUtil::FindConnectedTX( QString RXSerial ) rxtx.TX_Serial = TXSerial; rxtx.Is_Paired = true; rxtx.Is_Init = true; - LOG( WARNING ) + qWarning() << "tx serial stored: " << TXSerial.toStdString(); return true; } @@ -102,7 +105,7 @@ bool LHCUtil::FindConnectedTX( QString RXSerial ) rxtx.TX_Serial = ""; rxtx.Is_Paired = false; rxtx.Is_Init = true; - LOG( WARNING ) << "tx oops"; + qWarning() << "tx oops"; return true; } } diff --git a/src/openvr/lh_console_util.h b/src/openvr/lh_console_util.h index cff50d2a..ae816413 100644 --- a/src/openvr/lh_console_util.h +++ b/src/openvr/lh_console_util.h @@ -12,7 +12,6 @@ #include #include #include -#include namespace lh_con_util { diff --git a/src/openvr/openvr_init.cpp b/src/openvr/openvr_init.cpp index 908a2aa3..6f141c97 100644 --- a/src/openvr/openvr_init.cpp +++ b/src/openvr/openvr_init.cpp @@ -1,8 +1,10 @@ #include +#include #include #include #include "openvr_init.h" -#include +#include +#include #include "../openvr/ivrinput_manifest.h" namespace openvr_init @@ -29,17 +31,17 @@ bool initializeProperly( const OpenVrInitializationType initType ) // In particular in some setups these errors are thrown while // nothing is wrong with their setup presumably this is some sort of // race condition - LOG( WARNING ) << "HMD not Found During Startup"; - LOG( WARNING ) << "steamvr error: " - + std::string( - vr::VR_GetVRInitErrorAsEnglishDescription( - initError ) ); + qWarning() << "HMD not Found During Startup"; + qWarning() << "steamvr error: " + + std::string( + vr::VR_GetVRInitErrorAsEnglishDescription( + initError ) ); return false; } - LOG( ERROR ) << "Failed to initialize OpenVR: " - + std::string( - vr::VR_GetVRInitErrorAsEnglishDescription( - initError ) ); + qCritical() << "Failed to initialize OpenVR: " + + std::string( + vr::VR_GetVRInitErrorAsEnglishDescription( + initError ) ); // Going to stop Exiting App, This may lead to crashes if OpenVR // actually fails to start, HOWEVER based on the HMD errors we are // probably pre-maturely killing ourselves from some sort of OpenVR race @@ -48,7 +50,7 @@ bool initializeProperly( const OpenVrInitializationType initType ) return false; } - LOG( INFO ) << "OpenVR initialized successfully."; + qInfo() << "OpenVR initialized successfully."; return true; } @@ -65,9 +67,9 @@ void initializeOpenVR( const OpenVrInitializationType initType, int count ) // as of 5.8.1 Based on some information from valve, if ANY interface // fails to load we should have issues. we will re-initialize a few // times if that is the case and hope that fixes things - LOG( WARNING ) << "OpenVR version is invalid: Interface version " - << interfaceAndVersion << " not found. attempt number: " - << std::to_string( trynumber ); + qWarning() << "OpenVR version is invalid: Interface version " + << interfaceAndVersion << " not found. attempt number: " + << std::to_string( trynumber ); }; // Check whether OpenVR is too outdated @@ -121,16 +123,16 @@ void initializeOpenVR( const OpenVrInitializationType initType, int count ) } if ( !success && count < 3 ) { - LOG( WARNING ) << "An error occured on initialization of " - "openvr/steamvr attempting again " - << std::to_string( count + 1 ) << " of 3 Attempts"; + qWarning() << "An error occured on initialization of " + "openvr/steamvr attempting again " + << std::to_string( count + 1 ) << " of 3 Attempts"; std::this_thread::sleep_for( std::chrono::seconds( 5 ) ); // 5.8.1 Unknown if VR shutdown needs to be callled if vr init fails initializeOpenVR( initType, ( count + 1 ) ); } if ( count >= 3 ) { - LOG( ERROR ) << "initialization errors persist proceeding anyways"; + qCritical() << "initialization errors persist proceeding anyways"; } } diff --git a/src/openvr/ovr_application_wrapper.cpp b/src/openvr/ovr_application_wrapper.cpp index e63be246..2d06ea93 100644 --- a/src/openvr/ovr_application_wrapper.cpp +++ b/src/openvr/ovr_application_wrapper.cpp @@ -1,4 +1,6 @@ #include "ovr_application_wrapper.h" +#include +#include constexpr uint32_t bufferLen = 4096; namespace ovr_application_wrapper { @@ -12,9 +14,8 @@ std::string getSceneAppID() std::string keys = key; if ( error != vr::VRApplicationError_None ) { - LOG( WARNING ) << "Could not Get App ID by PID: " - + std::to_string( error ); - LOG( WARNING ) << "Attempting to find through Enumeration"; + qWarning() << "Could not Get App ID by PID: " + std::to_string( error ); + qWarning() << "Attempting to find through Enumeration"; auto appCount = vr::VRApplications()->GetApplicationCount(); const uint32_t bufferMax = vr::k_unMaxApplicationKeyLength; char cStringOut[bufferMax]; @@ -25,17 +26,17 @@ std::string getSceneAppID() std::string appID( cStringOut ); if ( appID.find( "steam.app" ) != std::string::npos ) { - LOG( WARNING ) << "Found App ID through Enumeration (only " - "steam apps caught): " - << appID; + qWarning() << "Found App ID through Enumeration (only " + "steam apps caught): " + << appID; if ( error2 == vr::VRApplicationError_None ) { return appID; } - LOG( WARNING ) << "Error getting app id via Enum: " << error2; + qWarning() << "Error getting app id via Enum: " << error2; } } - LOG( ERROR ) << "Unable to Find App ID by PID or by Enumeration"; + qCritical() << "Unable to Find App ID by PID or by Enumeration"; return "error"; } return keys; diff --git a/src/openvr/ovr_application_wrapper.h b/src/openvr/ovr_application_wrapper.h index 17e6cc1d..3eb1c44e 100644 --- a/src/openvr/ovr_application_wrapper.h +++ b/src/openvr/ovr_application_wrapper.h @@ -3,7 +3,6 @@ #include #include #include -#include #include #include diff --git a/src/openvr/ovr_overlay_wrapper.cpp b/src/openvr/ovr_overlay_wrapper.cpp index 9cf5553a..6631dc6f 100644 --- a/src/openvr/ovr_overlay_wrapper.cpp +++ b/src/openvr/ovr_overlay_wrapper.cpp @@ -1,4 +1,7 @@ #include "ovr_overlay_wrapper.h" +#include +#include +#include namespace ovr_overlay_wrapper { @@ -11,10 +14,9 @@ OverlayError createOverlay( const std::string overlayKey, overlayKey.c_str(), overlayName.c_str(), overlayHandle ); if ( oError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not create overlay: " << overlayName - << "because " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) - << " " << customErrorMsg; + qCritical() << "Could not create overlay: " << overlayName << "because " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) + << " " << customErrorMsg; return OverlayError::UndefinedError; } return OverlayError::NoError; @@ -30,10 +32,10 @@ OverlayError setOverlayColor( vr::VROverlayHandle_t overlayHandle, = vr::VROverlay()->SetOverlayColor( overlayHandle, red, green, blue ); if ( oError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Error setting Overlay Color For " - << getOverlayKey( overlayHandle ) << " with error: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) - << " " << customErrorMsg; + qCritical() << "Error setting Overlay Color For " + << getOverlayKey( overlayHandle ) << " with error: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) + << " " << customErrorMsg; return OverlayError::UndefinedError; } return OverlayError::NoError; @@ -47,10 +49,10 @@ OverlayError setOverlayAlpha( vr::VROverlayHandle_t overlayHandle, = vr::VROverlay()->SetOverlayAlpha( overlayHandle, alpha ); if ( oError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Error setting Overlay Alpha For " - << getOverlayKey( overlayHandle ) << " with error: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) - << " " << customErrorMsg; + qCritical() << "Error setting Overlay Alpha For " + << getOverlayKey( overlayHandle ) << " with error: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) + << " " << customErrorMsg; return OverlayError::UndefinedError; } return OverlayError::NoError; @@ -64,10 +66,10 @@ OverlayError setOverlayWidthInMeters( vr::VROverlayHandle_t overlayHandle, overlayHandle, widthInMeters ); if ( oError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Error setting overlay width For " - << getOverlayKey( overlayHandle ) << " with error: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) - << " " << customErrorMsg; + qCritical() << "Error setting overlay width For " + << getOverlayKey( overlayHandle ) << " with error: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) + << " " << customErrorMsg; return OverlayError::UndefinedError; } return OverlayError::NoError; @@ -81,34 +83,52 @@ OverlayError setOverlayFromFile( vr::VROverlayHandle_t overlayHandle, const auto overlayPath = paths::binaryDirectoryFindFile( fileName ); if ( !overlayPath.has_value() ) { - LOG( ERROR ) << "File not Found: " << fileName << customErrorMsg; + qCritical() << "File not Found: " << fileName << customErrorMsg; return OverlayError::UndefinedError; } vr::VROverlayError oError = vr::VROverlay()->SetOverlayFromFile( overlayHandle, overlayPath->c_str() ); if ( oError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Error setting Overlay from file For " - << getOverlayKey( overlayHandle ) << " with error: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - oError ) - << " " << customErrorMsg; + qCritical() << "Error setting Overlay from file For " + << getOverlayKey( overlayHandle ) << " with error: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + oError ) + << " " << customErrorMsg; return OverlayError::UndefinedError; } return OverlayError::NoError; } } +OverlayError setOverlayFromQImage( vr::VROverlayHandle_t overlayHandle, + QImage& image, + std::string customErrorMsg ) +{ + image.convertTo( QImage::Format_RGBA8888 ); + vr::VROverlayError oError = vr::VROverlay()->SetOverlayRaw( + overlayHandle, image.bits(), image.width(), image.height(), 4 ); + if ( oError != vr::VROverlayError_None ) + { + qCritical() << "Error setting Overlay from" << image << "For" + << getOverlayKey( overlayHandle ) << "with error:" + << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) + << customErrorMsg; + return OverlayError::UndefinedError; + } + return OverlayError::NoError; +} + OverlayError showOverlay( vr::VROverlayHandle_t overlayHandle, std::string customErrorMsg ) { vr::VROverlayError oError = vr::VROverlay()->ShowOverlay( overlayHandle ); if ( oError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Error showing overlay For " - << getOverlayKey( overlayHandle ) << " with error: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) - << " " << customErrorMsg; + qCritical() << "Error showing overlay For " + << getOverlayKey( overlayHandle ) << " with error: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) + << " " << customErrorMsg; return OverlayError::UndefinedError; } return OverlayError::NoError; @@ -120,10 +140,10 @@ OverlayError hideOverlay( vr::VROverlayHandle_t overlayHandle, vr::VROverlayError oError = vr::VROverlay()->HideOverlay( overlayHandle ); if ( oError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Error hiding overlay For " - << getOverlayKey( overlayHandle ) << " with error: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) - << " " << customErrorMsg; + qCritical() << "Error hiding overlay For " + << getOverlayKey( overlayHandle ) << " with error: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) + << " " << customErrorMsg; return OverlayError::UndefinedError; } return OverlayError::NoError; @@ -139,10 +159,10 @@ OverlayError setOverlayTransformAbsolute( overlayHandle, trackingOrigin, trackingOriginToOverlayTransform ); if ( oError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Error setting Overlay Position For " - << getOverlayKey( overlayHandle ) << " with error: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) - << " " << customErrorMsg; + qCritical() << "Error setting Overlay Position For " + << getOverlayKey( overlayHandle ) << " with error: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( oError ) + << " " << customErrorMsg; return OverlayError::UndefinedError; } return OverlayError::NoError; diff --git a/src/openvr/ovr_overlay_wrapper.h b/src/openvr/ovr_overlay_wrapper.h index 3152946a..ed6df73d 100644 --- a/src/openvr/ovr_overlay_wrapper.h +++ b/src/openvr/ovr_overlay_wrapper.h @@ -3,9 +3,9 @@ #include #include #include -#include #include #include +#include #include "../utils/paths.h" /* Wrapper For OpenVR's IVR settings class, allows us to do our error logging @@ -43,6 +43,9 @@ OverlayError setOverlayWidthInMeters( vr::VROverlayHandle_t overlayHandle, OverlayError setOverlayFromFile( vr::VROverlayHandle_t overlayHandle, std::string fileName, std::string customErrorMsg = "" ); +OverlayError setOverlayFromQImage( vr::VROverlayHandle_t overlayHandle, + QImage& image, + std::string customErrorMsg = "" ); OverlayError showOverlay( vr::VROverlayHandle_t overlayHandle, std::string customErrorMsg = "" ); OverlayError hideOverlay( vr::VROverlayHandle_t overlayHandle, diff --git a/src/openvr/ovr_settings_wrapper.cpp b/src/openvr/ovr_settings_wrapper.cpp index 589c510c..410fcccb 100644 --- a/src/openvr/ovr_settings_wrapper.cpp +++ b/src/openvr/ovr_settings_wrapper.cpp @@ -1,4 +1,6 @@ #include "ovr_settings_wrapper.h" +#include +#include namespace ovr_settings_wrapper { @@ -19,9 +21,9 @@ SettingsError handleErrors( std::string settingsKey, { return SettingsError::UndefinedError; } - LOG( ERROR ) << "Could not access \"" << settingsKey << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( error ) - << " " << customErrorMsg; + qCritical() << "Could not access \"" << settingsKey << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( error ) + << " " << customErrorMsg; if ( error == vr::EVRSettingsError::VRSettingsError_UnsetSettingHasNoDefault ) { diff --git a/src/openvr/ovr_settings_wrapper.h b/src/openvr/ovr_settings_wrapper.h index fc1bac33..8c98a2b3 100644 --- a/src/openvr/ovr_settings_wrapper.h +++ b/src/openvr/ovr_settings_wrapper.h @@ -3,7 +3,6 @@ #include #include #include -#include #include /* Wrapper For OpenVR's IVR settings class, allows us to do our error logging diff --git a/src/openvr/ovr_system_wrapper.cpp b/src/openvr/ovr_system_wrapper.cpp index 6d0e17e7..45c4b468 100644 --- a/src/openvr/ovr_system_wrapper.cpp +++ b/src/openvr/ovr_system_wrapper.cpp @@ -1,4 +1,7 @@ #include "ovr_system_wrapper.h" +#include +#include +#include namespace ovr_system_wrapper { @@ -8,11 +11,11 @@ SystemError handleTrackedPropertyErrors( vr::TrackedDeviceProperty tdp, { if ( error != vr::TrackedProp_Success ) { - LOG( ERROR ) << "Could not get Property with error \"" - << vr::VRSystem()->GetPropErrorNameFromEnum( error ) - << "\" property: " - << "todo" - << " " << customErrorMsg; + qCritical() << "Could not get Property with error \"" + << vr::VRSystem()->GetPropErrorNameFromEnum( error ) + << "\" property: " + << "todo" + << " " << customErrorMsg; if ( tdp == vr::Prop_TrackedDeviceProperty_Max ) { // Just for Error OPPS todo @@ -295,7 +298,7 @@ std::string getControllerName() } if ( !isLeftCon && !isRightCon && hasHMD ) { - LOG( WARNING ) << "WARNING: No Controllers assuming based on HMD"; + qWarning() << "WARNING: No Controllers assuming based on HMD"; auto hmdName = getStringTrackedProperty( hmdIdx, vr::Prop_ControllerType_String ) .second; @@ -309,27 +312,27 @@ std::string getControllerName() } if ( hmdName == "vive_pro" ) { - LOG( WARNING ) + qWarning() << "Vive Pro Detected, Assuming Knuckles this may be wrong"; return "knuckles"; } if ( hmdName == "holographic_hmd" ) { - LOG( WARNING ) << "WMR detected, Assuming HP CONTROLLERS"; + qWarning() << "WMR detected, Assuming HP CONTROLLERS"; return "hpmotioncontroller"; } if ( hmdName == "rift" ) { return "oculus_touch"; } - LOG( WARNING ) << "Headset Not recognized Assuming touch controllers " - + hmdName; + qWarning() << "Headset Not recognized Assuming touch controllers " + + hmdName; return "oculus_touch"; } if ( right != left ) { - LOG( WARNING ) << "WARNING: Left and Right Controllers are Different, " - "Prioritizing right"; + qWarning() << "WARNING: Left and Right Controllers are Different, " + "Prioritizing right"; } if ( rightIdx == 999 ) { diff --git a/src/openvr/ovr_system_wrapper.h b/src/openvr/ovr_system_wrapper.h index f561bada..7716f428 100644 --- a/src/openvr/ovr_system_wrapper.h +++ b/src/openvr/ovr_system_wrapper.h @@ -3,9 +3,9 @@ #include #include #include -#include #include #include +#include /* Wrapper For OpenVR's IVR settings class, allows us to do our error logging * while also minimizing code diff --git a/src/overlaycontroller.cpp b/src/overlaycontroller.cpp index 382cf7a2..d57d4a41 100644 --- a/src/overlaycontroller.cpp +++ b/src/overlaycontroller.cpp @@ -11,17 +11,25 @@ #include #include #include +#include #include #include #include #include +#include +#include #include #include #include -#include +#include "openvr/ovr_overlay_wrapper.h" #include "utils/Matrix.h" #include "keyboard_input/input_sender.h" #include "settings/settings.h" +#include +#include +#include +#include +#include // application namespace namespace advsettings @@ -60,61 +68,23 @@ OverlayController::OverlayController( bool desktopMode, // Throw Error If over 16k characters in path string if ( !pathIsGood ) { - LOG( ERROR ) << "Error Finding VR Runtime Path, Attempting Recovery: "; + qCritical() << "Error Finding VR Runtime Path, Attempting Recovery: "; uint32_t maxLengthRe = requiredLength; - LOG( INFO ) << "Open VR reporting Required path length of: " - << maxLengthRe; + qInfo() << "Open VR reporting Required path length of: " << maxLengthRe; } m_runtimePathUrl = QUrl::fromLocalFile( tempRuntimePath ); - LOG( INFO ) << "VR Runtime Path: " << m_runtimePathUrl.toLocalFile(); + qInfo() << "VR Runtime Path: " << m_runtimePathUrl.toLocalFile(); const double initVol = soundVolume(); - constexpr auto clickSoundURL = "res/sounds/click.wav"; - const auto activationSoundFile - = paths::binaryDirectoryFindFile( clickSoundURL ); + m_activationSoundEffect.setSource( QUrl( "qrc:/sounds/click.wav" ) ); + m_activationSoundEffect.setVolume( initVol ); - if ( activationSoundFile.has_value() ) - { - m_activationSoundEffect.setSource( QUrl::fromLocalFile( - QString::fromStdString( ( *activationSoundFile ) ) ) ); - m_activationSoundEffect.setVolume( initVol ); - } - else - { - LOG( ERROR ) << "Could not find activation sound file " - << clickSoundURL; - } - constexpr auto focusChangedSoundURL = "res/sounds/focus.wav"; - const auto focusChangedSoundFile - = paths::binaryDirectoryFindFile( focusChangedSoundURL ); + m_focusChangedSoundEffect.setSource( QUrl( "qrc:/sounds/focus.wav" ) ); + m_focusChangedSoundEffect.setVolume( initVol ); - if ( focusChangedSoundFile.has_value() ) - { - m_focusChangedSoundEffect.setSource( QUrl::fromLocalFile( - QString::fromStdString( ( *focusChangedSoundFile ) ) ) ); - m_focusChangedSoundEffect.setVolume( initVol ); - } - else - { - LOG( ERROR ) << "Could not find focus Changed sound file " - << focusChangedSoundURL; - } - - constexpr auto alarmFileName = "res/sounds/alarm01.wav"; - const auto alarm01SoundFile - = paths::binaryDirectoryFindFile( alarmFileName ); - - if ( alarm01SoundFile.has_value() ) - { - m_alarm01SoundEffect.setSource( QUrl::fromLocalFile( - QString::fromStdString( ( *alarm01SoundFile ) ) ) ); - m_alarm01SoundEffect.setVolume( 1.0 ); - } - else - { - LOG( ERROR ) << "Could not find alarm01 sound file " << alarmFileName; - } + m_alarm01SoundEffect.setSource( QUrl( "qrc:/sounds/alarm01.wav" ) ); + m_alarm01SoundEffect.setVolume( 1.0 ); // If we have desktop mode flag ignore waht toggle says otherwise we use // toggle @@ -123,28 +93,6 @@ OverlayController::OverlayController( bool desktopMode, m_desktopMode = desktopModeToggle(); } - QSurfaceFormat format; - // Qt's QOpenGLPaintDevice is not compatible with OpenGL versions >= 3.0 - // NVIDIA does not care, but unfortunately AMD does - // Are subtle changes to the semantics of OpenGL functions actually covered - // by the compatibility profile, and this is an AMD bug? - format.setVersion( 2, 1 ); - // format.setProfile( QSurfaceFormat::CompatibilityProfile ); - format.setDepthBufferSize( 16 ); - format.setStencilBufferSize( 8 ); - format.setSamples( 16 ); - - m_openGLContext.setFormat( format ); - if ( !m_openGLContext.create() ) - { - throw std::runtime_error( "Could not create OpenGL context" ); - } - - // create an offscreen surface to attach the context and FBO to - m_offscreenSurface.setFormat( m_openGLContext.format() ); - m_offscreenSurface.create(); - m_openGLContext.makeCurrent( &m_offscreenSurface ); - if ( !vr::VROverlay() ) { QMessageBox::critical( @@ -344,11 +292,11 @@ OverlayController::OverlayController( bool desktopMode, } else { - LOG( INFO ) << "Version Check: Feature disabled. Not checking version."; + qInfo() << "Version Check: Feature disabled. Not checking version."; } - LOG( INFO ) << "OPENSSL VERSION: " - << QSslSocket::sslLibraryBuildVersionString(); + qInfo() << "OPENSSL VERSION: " + << QSslSocket::sslLibraryBuildVersionString(); } OverlayController::~OverlayController() @@ -373,7 +321,7 @@ void OverlayController::exitApp() Shutdown(); QApplication::exit(); - LOG( INFO ) << "All systems exited."; + qInfo() << "All systems exited."; exit( EXIT_SUCCESS ); // Does not fallthrough } @@ -403,7 +351,9 @@ void OverlayController::Shutdown() m_pRenderTimer->stop(); m_pRenderTimer.reset(); } - m_pFbo.reset(); + m_render_pass_descriptor.reset(); + m_render_target.reset(); + m_pFBTexture.reset(); } void OverlayController::SetWidget( QQuickItem* quickItem, @@ -439,24 +389,17 @@ void OverlayController::SetWidget( QQuickItem* quickItem, vr::VROverlayFlags_SendVRSmoothScrollEvents, true ); - constexpr auto thumbiconFilename = "res/img/icons/thumbicon.png"; - const auto thumbIconPath - = paths::binaryDirectoryFindFile( thumbiconFilename ); - if ( thumbIconPath.has_value() ) - { - vr::VROverlay()->SetOverlayFromFile( m_ulOverlayThumbnailHandle, - thumbIconPath->c_str() ); - } - else { - LOG( ERROR ) << "Could not find thumbnail icon \"" - << thumbiconFilename << "\""; + QImage thumbiconImg( QString( ":/icons/thumbicon.png" ) ); + ovr_overlay_wrapper::setOverlayFromQImage( + m_ulOverlayThumbnailHandle, thumbiconImg ); } // Too many render calls in too short time overwhelm Qt and an // assertion gets thrown. Therefore we use an timer to delay render // calls m_pRenderTimer.reset( new QTimer() ); + m_pRenderTimer->moveToThread( qApp->thread() ); m_pRenderTimer->setSingleShot( true ); m_pRenderTimer->setInterval( 5 ); connect( m_pRenderTimer.get(), @@ -464,22 +407,52 @@ void OverlayController::SetWidget( QQuickItem* quickItem, this, SLOT( renderOverlay() ) ); - QOpenGLFramebufferObjectFormat fboFormat; - fboFormat.setAttachment( - QOpenGLFramebufferObject::CombinedDepthStencil ); - fboFormat.setTextureTarget( GL_TEXTURE_2D ); - m_pFbo.reset( new QOpenGLFramebufferObject( - static_cast( quickItem->width() ), - static_cast( quickItem->height() ), - fboFormat ) ); +#if QT_CONFIG( vulkan ) + if ( m_window.graphicsApi() == QSGRendererInterface::Vulkan ) + { + m_vulkanInstance.reset( new QVulkanInstance ); + m_vulkanInstance->setExtensions( + QQuickGraphicsConfiguration::preferredInstanceExtensions() ); + if ( !m_vulkanInstance->create() ) + throw std::runtime_error( "Cannot create vulkan instance" ); + + m_window.setVulkanInstance( m_vulkanInstance.get() ); + } +#endif + + if ( !m_renderControl.initialize() ) + throw std::runtime_error( "could not initialize m_renderControl" ); + + QRhi* rhi = this->rhi(); - m_window.setRenderTarget( m_pFbo.get() ); + qInfo() << "Started with" << rhi->backendName(); + + m_pFBTexture.reset( rhi->newTexture( + QRhiTexture::RGBA8, + quickItem->size().toSize(), + 1, + QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource ) ); + if ( !m_pFBTexture->create() ) + throw std::runtime_error( "RhiTexture not created" ); + + m_render_target.reset( + rhi->newTextureRenderTarget( { m_pFBTexture.get() } ) ); + m_render_pass_descriptor.reset( + m_render_target->newCompatibleRenderPassDescriptor() ); + m_render_target->setRenderPassDescriptor( + m_render_pass_descriptor.get() ); + if ( !m_render_target->create() ) + throw std::runtime_error( "failed to create render target" ); + + auto qqrt + = QQuickRenderTarget::fromRhiRenderTarget( m_render_target.get() ); + + m_window.setRenderTarget( qqrt ); quickItem->setParentItem( m_window.contentItem() ); m_window.setGeometry( 0, 0, static_cast( quickItem->width() ), static_cast( quickItem->height() ) ); - m_renderControl.initialize( &m_openGLContext ); vr::HmdVector2_t vecWindowSize = { static_cast( quickItem->width() ), @@ -510,7 +483,7 @@ void OverlayController::SetWidget( QQuickItem* quickItem, m_steamVRTabController.initStage2( this ); m_chaperoneTabController.initStage2( this ); m_fixFloorTabController.initStage2( this ); - m_audioTabController.initStage2(); + m_audioTabController.initStage2( this ); m_statisticsTabController.initStage2( this ); m_settingsTabController.initStage2( this ); m_utilitiesTabController.initStage2( this ); @@ -526,7 +499,7 @@ void OverlayController::SetWidget( QQuickItem* quickItem, autoApplyChaperoneName() ); if ( chapindex.first ) { - LOG( INFO ) << "Auto Applying Chaperone"; + qInfo() << "Auto Applying Chaperone"; m_chaperoneTabController.applyChaperoneProfile( chapindex.second ); // This should be the way to stop room-setup from starting... as it // sends steamvr a signal that it is completed @@ -534,7 +507,7 @@ void OverlayController::SetWidget( QQuickItem* quickItem, vr::EChaperoneConfigFile_Live ); return; } - LOG( WARNING ) << "Profile Not Found for Auto Apply Chaperone!"; + qWarning() << "Profile Not Found for Auto Apply Chaperone!"; } } @@ -546,6 +519,51 @@ void OverlayController::OnRenderRequest() } } +void OverlayController::SetOverlayFromQRhiTexture( QRhiTexture& tex ) +{ + vr::Texture_t vrTex = {}; + QRhi* rhi = this->rhi(); + + switch ( rhi->backend() ) + { + case QRhi::OpenGLES2: + { + vrTex.handle = reinterpret_cast( tex.nativeTexture().object ); + vrTex.eType = vr::TextureType_OpenGL; + vrTex.eColorSpace = vr::ColorSpace_Auto; + } + break; +#if QT_CONFIG( vulkan ) + case QRhi::Vulkan: + { + const QRhiVulkanNativeHandles* vulkan_handles + = reinterpret_cast( + rhi->nativeHandles() ); + vr::VRVulkanTextureData_t vulkan = { + .m_nImage = tex.nativeTexture().object, + .m_pDevice = vulkan_handles->dev, + .m_pPhysicalDevice = vulkan_handles->physDev, + .m_pInstance = vulkan_handles->inst->vkInstance(), + .m_pQueue = vulkan_handles->gfxQueue, + .m_nQueueFamilyIndex = vulkan_handles->gfxQueueIdx, + .m_nWidth = static_cast( tex.pixelSize().width() ), + .m_nHeight = static_cast( tex.pixelSize().height() ), + .m_nFormat = static_cast(tex.format()), + .m_nSampleCount = static_cast( tex.sampleCount() ), + }; + vrTex.handle = &vulkan; + vrTex.eType = vr::TextureType_Vulkan; + vrTex.eColorSpace = vr::ColorSpace_Auto; + } + break; +#endif + default: + qFatal() << "unimplemented backend:" << rhi->backend(); + throw std::runtime_error( "unimplemented backend" ); + } + vr::VROverlay()->SetOverlayTexture( m_ulOverlayHandle, &vrTex ); +} + void OverlayController::renderOverlay() { if ( !m_desktopMode ) @@ -557,28 +575,12 @@ void OverlayController::renderOverlay() m_ulOverlayThumbnailHandle ) ) ) return; m_renderControl.polishItems(); + m_renderControl.beginFrame(); m_renderControl.sync(); m_renderControl.render(); + m_renderControl.endFrame(); - GLuint unTexture = m_pFbo->texture(); - if ( unTexture != 0 ) - { -#if defined _WIN64 || defined _LP64 - // To avoid any compiler warning because of cast to a larger - // pointer type (warning C4312 on VC) - vr::Texture_t texture = { reinterpret_cast( - static_cast( unTexture ) ), - vr::TextureType_OpenGL, - vr::ColorSpace_Auto }; -#else - vr::Texture_t texture = { reinterpret_cast( unTexture ), - vr::TextureType_OpenGL, - vr::ColorSpace_Auto }; -#endif - vr::VROverlay()->SetOverlayTexture( m_ulOverlayHandle, &texture ); - } - m_openGLContext.functions()->glFlush(); // We need to flush otherwise - // the texture may be empty.*/ + SetOverlayFromQRhiTexture( *m_pFBTexture ); } } @@ -596,14 +598,14 @@ bool OverlayController::pollNextEvent( vr::VROverlayHandle_t ulOverlayHandle, } } -QPoint OverlayController::getMousePositionForEvent( vr::VREvent_Mouse_t mouse ) +QPointF OverlayController::getMousePositionForEvent( vr::VREvent_Mouse_t mouse ) { float y = mouse.y; #ifdef __linux__ float h = static_cast( m_window.height() ); y = h - y; #endif - return QPoint( static_cast( mouse.x ), static_cast( y ) ); + return { mouse.x, y }; } void OverlayController::processMediaKeyBindings() @@ -988,7 +990,7 @@ QString OverlayController::versionCheckText() const void OverlayController::setVersionCheckText( QString value, bool notify ) { m_versionCheckText = value; - LOG( INFO ) << "m_versionCheckText = " << m_versionCheckText; + qInfo() << "m_versionCheckText = " << m_versionCheckText; if ( notify ) { emit versionCheckTextChanged( m_versionCheckText ); @@ -1109,7 +1111,7 @@ void OverlayController::mainEventLoop() { case vr::VREvent_MouseMove: { - QPoint ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); + QPointF ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); if ( ptNewMouse != m_ptLastMouse ) { QMouseEvent mouseEvent( QEvent::MouseMove, @@ -1117,7 +1119,7 @@ void OverlayController::mainEventLoop() m_window.mapToGlobal( ptNewMouse ), Qt::NoButton, m_lastMouseButtons, - nullptr ); + Qt::NoModifier ); m_ptLastMouse = ptNewMouse; QCoreApplication::sendEvent( &m_window, &mouseEvent ); OnRenderRequest(); @@ -1127,7 +1129,7 @@ void OverlayController::mainEventLoop() case vr::VREvent_MouseButtonDown: { - QPoint ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); + QPointF ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); Qt::MouseButton button = vrEvent.data.mouse.button == vr::VRMouseButton_Right ? Qt::RightButton @@ -1138,14 +1140,14 @@ void OverlayController::mainEventLoop() m_window.mapToGlobal( ptNewMouse ), button, m_lastMouseButtons, - nullptr ); + Qt::NoModifier ); QCoreApplication::sendEvent( &m_window, &mouseEvent ); } break; case vr::VREvent_MouseButtonUp: { - QPoint ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); + QPointF ptNewMouse = getMousePositionForEvent( vrEvent.data.mouse ); Qt::MouseButton button = vrEvent.data.mouse.button == vr::VRMouseButton_Right ? Qt::RightButton @@ -1156,7 +1158,7 @@ void OverlayController::mainEventLoop() m_window.mapToGlobal( ptNewMouse ), button, m_lastMouseButtons, - nullptr ); + Qt::NoModifier ); QCoreApplication::sendEvent( &m_window, &mouseEvent ); } break; @@ -1172,10 +1174,10 @@ void OverlayController::mainEventLoop() * ( 360.0f * 8.0f ) ), static_cast( vrEvent.data.scroll.ydelta * ( 360.0f * 8.0f ) ) ), - 0, - Qt::Vertical, m_lastMouseButtons, - nullptr ); + Qt::KeyboardModifiers::fromInt( 0 ), + Qt::ScrollPhase::NoScrollPhase, + false ); QCoreApplication::sendEvent( &m_window, &wheelEvent ); } break; @@ -1188,7 +1190,7 @@ void OverlayController::mainEventLoop() case vr::VREvent_Quit: { - LOG( INFO ) << "Received quit request."; + qInfo() << "Received quit request."; vr::VRSystem()->AcknowledgeQuit_Exiting(); // Let us buy some // time just in case @@ -1200,14 +1202,14 @@ void OverlayController::mainEventLoop() case vr::VREvent_DashboardActivated: { - LOG( DEBUG ) << "Dashboard activated"; + qDebug() << "Dashboard activated"; m_dashboardVisible = true; } break; case vr::VREvent_DashboardDeactivated: { - LOG( DEBUG ) << "Dashboard deactivated"; + qDebug() << "Dashboard deactivated"; m_dashboardVisible = false; settings::saveChangedSettings(); } @@ -1243,9 +1245,8 @@ void OverlayController::mainEventLoop() = vrEvent.data.chaperone.m_nPreviousUniverse; uint64_t currentUniverseId = vrEvent.data.chaperone.m_nCurrentUniverse; - LOG( INFO ) - << "(VREvent) ChaperoneUniverseHasChanged... Previous : " - << previousUniverseId << " Current:" << currentUniverseId; + qInfo() << "(VREvent) ChaperoneUniverseHasChanged... Previous : " + << previousUniverseId << " Current:" << currentUniverseId; if ( !chaperoneDataAlreadyUpdated ) { m_chaperoneUtils.loadChaperoneData(); @@ -1260,7 +1261,7 @@ void OverlayController::mainEventLoop() break; case vr::VREvent_Input_ActionManifestReloaded: { - // LOG( WARNING ) << "Action Manifest Reloaded"; + // qWarning() << "Action Manifest Reloaded"; if ( m_steamVRTabController.perAppBindEnabled() ) { m_steamVRTabController.applyAllCustomBindings(); @@ -1274,7 +1275,7 @@ void OverlayController::mainEventLoop() if ( m_incomingReset ) { m_incomingReset = false; - LOG( INFO ) << "Reset zero event recorded"; + qInfo() << "Reset zero event recorded"; m_moveCenterTabController.incomingZeroReset(); } @@ -1641,7 +1642,7 @@ void OverlayController::OnNetworkReply( QNetworkReply* reply ) if ( reply->error() == QNetworkReply::NoError ) { QByteArray replyByteData = reply->readAll(); - LOG( INFO ) << "Version Check: Recieved Data: " << replyByteData; + qInfo() << "Version Check: Recieved Data: " << replyByteData; QJsonParseError parseError; m_remoteVersionJsonDocument = QJsonDocument::fromJson( replyByteData, &parseError ); @@ -1684,10 +1685,9 @@ void OverlayController::OnNetworkReply( QNetworkReply* reply ) + QString::number( m_remoteVersionPatch ) + ") available." ); } - LOG( INFO ) - << "Version Check: Newer version (" << m_remoteVersionMajor - << "." << m_remoteVersionMinor << "." - << m_remoteVersionPatch << ") available."; + qInfo() << "Version Check: Newer version (" + << m_remoteVersionMajor << "." << m_remoteVersionMinor + << "." << m_remoteVersionPatch << ") available."; } else { @@ -1696,22 +1696,22 @@ void OverlayController::OnNetworkReply( QNetworkReply* reply ) setVersionCheckText( m_optionalMessage ); } setNewVersionDetected( false ); - LOG( INFO ) << "Version Check: Installed version is latest " - "release."; + qInfo() << "Version Check: Installed version is latest " + "release."; } } else { - LOG( ERROR ) + qCritical() << "Version Check: Error parsing json. QJsonParseError = " << parseError.error; } } else { - LOG( ERROR ) << "Version Check: Error connecting to network. " - "QNetworkReply::NetworkError = " - << reply->error(); + qCritical() << "Version Check: Error connecting to network. " + "QNetworkReply::NetworkError = " + << reply->error(); } reply->deleteLater(); } diff --git a/src/overlaycontroller.h b/src/overlaycontroller.h index 24b26d3c..96f74cbf 100644 --- a/src/overlaycontroller.h +++ b/src/overlaycontroller.h @@ -1,10 +1,10 @@ #pragma once +#include #include #include // because of incompatibilities with QtOpenGL and GLEW we need to cherry pick // includes -#include #include #include #include @@ -22,8 +22,10 @@ #include #include #include +#include #include -#include +#include +#include #include "openvr/openvr_init.h" @@ -106,18 +108,30 @@ class OverlayController : public QObject vr::VROverlayHandle_t m_ulOverlayThumbnailHandle = vr::k_ulOverlayHandleInvalid; +#if QT_CONFIG( vulkan ) + std::unique_ptr m_vulkanInstance = nullptr; +#endif QQuickRenderControl m_renderControl; QQuickWindow m_window{ &m_renderControl }; + + std::optional m_cached_vr_texture_type; + std::unique_ptr m_pFBTexture; + std::unique_ptr m_render_target; + std::unique_ptr m_render_pass_descriptor; + + /* std::unique_ptr m_pFbo; + QQuickRenderTarget m_pRenderTarget; QOpenGLContext m_openGLContext; QOffscreenSurface m_offscreenSurface; + */ QTimer m_pumpEventsTimer; std::unique_ptr m_pRenderTimer; bool m_dashboardVisible = false; - QPoint m_ptLastMouse; - Qt::MouseButtons m_lastMouseButtons = nullptr; + QPointF m_ptLastMouse; + Qt::MouseButtons m_lastMouseButtons; bool m_desktopMode; bool m_noSound; @@ -154,8 +168,9 @@ class OverlayController : public QObject QJsonDocument m_remoteVersionJsonDocument = QJsonDocument(); QJsonObject m_remoteVersionJsonObject; -public: // I know it's an ugly hack to make them public to enable external - // access, but I am too lazy to implement getters. +public: + // I know it's an ugly hack to make them public to enable external + // access, but I am too lazy to implement getters. SteamVRTabController m_steamVRTabController; ChaperoneTabController m_chaperoneTabController; MoveCenterTabController m_moveCenterTabController; @@ -169,7 +184,7 @@ class OverlayController : public QObject bool m_incomingReset = false; private: - QPoint getMousePositionForEvent( vr::VREvent_Mouse_t mouse ); + QPointF getMousePositionForEvent( vr::VREvent_Mouse_t mouse ); void processInputBindings(); void processMediaKeyBindings(); void processMotionBindings(); @@ -179,11 +194,17 @@ class OverlayController : public QObject void processRotationBindings(); void processExclusiveInputBinding(); + inline QRhi* rhi() + { + return m_renderControl.rhi(); + } + bool m_exclusiveState = false; bool m_keyPressOneState = false; bool m_keyPressTwoState = false; public: + void SetOverlayFromQRhiTexture( QRhiTexture& tex ); OverlayController( bool desktopMode, bool noSound, QQmlEngine& qmlEngine ); virtual ~OverlayController(); diff --git a/src/res/qml/ChaperoneWarningsPage.qml b/src/res/qml/ChaperoneWarningsPage.qml index 2ad9fdbf..ab19ba4b 100644 --- a/src/res/qml/ChaperoneWarningsPage.qml +++ b/src/res/qml/ChaperoneWarningsPage.qml @@ -1,7 +1,7 @@ import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 -import QtQuick.Dialogs 1.2 +import QtQuick.Dialogs import ovras.advsettings 1.0 import "." // QTBUG-34418, singletons require explicit import to load qmldir file import "common" @@ -415,43 +415,43 @@ MyStackViewPage { Connections { target: ChaperoneTabController - onChaperoneSwitchToBeginnerEnabledChanged: { + function onChaperoneSwitchToBeginnerEnabledChanged() { switchBeginnerToggle.checked = ChaperoneTabController.chaperoneSwitchToBeginnerEnabled } - onChaperoneSwitchToBeginnerDistanceChanged: { + function onChaperoneSwitchToBeginnerDistanceChanged() { var d = ChaperoneTabController.chaperoneSwitchToBeginnerDistance.toFixed(2) if (d <= switchBeginnerDistanceSlider.to && Math.abs(switchBeginnerDistanceSlider.value - d) > 0.0008) { switchBeginnerDistanceSlider.value = d } switchBeginnerDistanceText.text = d } - onChaperoneHapticFeedbackEnabledChanged: { + function onChaperoneHapticFeedbackEnabledChanged() { hapticFeedbackToggle.checked = ChaperoneTabController.chaperoneHapticFeedbackEnabled } - onChaperoneHapticFeedbackDistanceChanged: { + function onChaperoneHapticFeedbackDistanceChanged() { var d = ChaperoneTabController.chaperoneHapticFeedbackDistance.toFixed(2) if (d <= hapticFeedbackDistanceSlider.to && Math.abs(hapticFeedbackDistanceSlider.value - d) > 0.0008) { hapticFeedbackDistanceSlider.value = d } hapticFeedbackDistanceText.text = d } - onChaperoneAlarmSoundEnabledChanged: { + function onChaperoneAlarmSoundEnabledChanged() { audioWarningToggle.checked = ChaperoneTabController.chaperoneAlarmSoundEnabled } - onChaperoneAlarmSoundLoopingChanged: { + function onChaperoneAlarmSoundLoopingChanged() { audioWarningLoopingToggle.checked = ChaperoneTabController.chaperoneAlarmSoundLooping } - onChaperoneAlarmSoundDistanceChanged: { + function onChaperoneAlarmSoundDistanceChanged() { var d = ChaperoneTabController.chaperoneAlarmSoundDistance.toFixed(2) if (d <= audioWarningDistanceSlider.to && Math.abs(audioWarningDistanceSlider.value - d) > 0.0008) { audioWarningDistanceSlider.value = d } audioWarningDistanceText.text = d } - onChaperoneShowDashboardEnabledChanged: { + function onChaperoneShowDashboardEnabledChanged() { openDashboardToggle.checked = ChaperoneTabController.chaperoneShowDashboardEnabled } - onChaperoneShowDashboardDistanceChanged: { + function onChaperoneShowDashboardDistanceChanged() { var d = ChaperoneTabController.chaperoneShowDashboardDistance.toFixed(2) if (d <= openDashboardDistanceSlider.to && Math.abs(openDashboardDistanceSlider.value - d) > 0.0008) { openDashboardDistanceSlider.value = d diff --git a/src/res/qml/FixFloorPage.qml b/src/res/qml/FixFloorPage.qml index c19bdc78..42643322 100644 --- a/src/res/qml/FixFloorPage.qml +++ b/src/res/qml/FixFloorPage.qml @@ -140,7 +140,7 @@ MyStackViewPage { Connections { target: FixFloorTabController - onStatusMessageSignal: { + function onStatusMessageSignal() { if (statusMessageTimer.running) { statusMessageTimer.stop() } @@ -148,15 +148,15 @@ MyStackViewPage { statusMessageTimer.interval = FixFloorTabController.currentStatusMessageTimeout() * 1000 statusMessageTimer.start() } - onMeasureStartSignal: { + function onMeasureStartSignal() { fixButton.enabled = false undoFixButton.enabled = false } - onMeasureEndSignal: { + function onMeasureEndSignal() { fixButton.enabled = true // undoFixButton.enabled = FixFloorTabController.canUndo } - onCanUndoChanged: { + function onCanUndoChanged() { //undoFixButton.enabled = FixFloorTabController.canUndo // revert below to this -^ undoFixButton.enabled = false @@ -165,7 +165,7 @@ MyStackViewPage { Connections { target: MoveCenterTabController - onTrackingUniverseChanged: { + function onTrackingUniverseChanged() { if (MoveCenterTabController.trackingUniverse === 0) { fixButton.enabled = false recenterButton.enabled = false diff --git a/src/res/qml/PlayspacePage.qml b/src/res/qml/PlayspacePage.qml index fae19d56..3693822e 100644 --- a/src/res/qml/PlayspacePage.qml +++ b/src/res/qml/PlayspacePage.qml @@ -524,33 +524,33 @@ MyStackViewPage { Connections { target: MoveCenterTabController - onOffsetXChanged: { + function onOffsetXChanged() { spaceMoveXText.text = MoveCenterTabController.offsetX.toFixed(2) } - onOffsetYChanged: { + function onOffsetYChanged() { spaceMoveYText.text = MoveCenterTabController.offsetY.toFixed(2) } - onOffsetZChanged: { + function onOffsetZChanged() { spaceMoveZText.text = MoveCenterTabController.offsetZ.toFixed(2) } - onRotationChanged: { + function onRotationChanged() { spaceRotationSlider.value = ( MoveCenterTabController.rotation / 100 ) } - onTempRotationChanged: { + function onTempRotationChanged() { var intTempRotation = MoveCenterTabController.tempRotation spaceRotationSlider.value = ( intTempRotation / 100 ) spaceRotationText.text = ( intTempRotation / 100 ) + "°" } - onLockXToggleChanged: { + function onLockXToggleChanged() { lockXToggle.checked = MoveCenterTabController.lockXToggle } - onLockYToggleChanged: { + function onLockYToggleChanged() { lockYToggle.checked = MoveCenterTabController.lockYToggle } - onLockZToggleChanged: { + function onLockZToggleChanged() { lockZToggle.checked = MoveCenterTabController.lockZToggle } - onTrackingUniverseChanged: { + function onTrackingUniverseChanged() { if (MoveCenterTabController.trackingUniverse === 0) { spaceModeText.text = "Sitting" spaceSeatedRecenter.visible = true @@ -560,7 +560,7 @@ MyStackViewPage { spaceModeText.text = "Unknown(" + MoveCenterTabController.trackingUniverse + ")" } } - onOffsetProfilesUpdated: { + function onOffsetProfilesUpdated() { reloadOffsetProfiles() } } diff --git a/src/res/qml/RootPage.qml b/src/res/qml/RootPage.qml index d3b1eaa5..2d062c56 100644 --- a/src/res/qml/RootPage.qml +++ b/src/res/qml/RootPage.qml @@ -473,7 +473,7 @@ MyStackViewPage { Connections { target: OverlayController - onNewVersionDetectedChanged: { + function onNewVersionDetectedChanged() { if (OverlayController.newVersionDetected) { summaryVersionCheckTextRect.color = "#ff0000" @@ -481,10 +481,10 @@ MyStackViewPage { summaryVersionCheckTextRect.color = "#2a2e35" } } - onVersionCheckTextChanged: { + function onVersionCheckTextChanged() { summaryVersionCheckText.text = OverlayController.versionCheckText } - onDisableVersionCheckChanged: { + function onDisableVersionCheckChanged() { if (OverlayController.disableVersionCheck) { summaryVersionCheckText.visible = false @@ -503,34 +503,34 @@ MyStackViewPage { Connections { target: ChaperoneTabController - onChaperoneProfilesUpdated: { + function onChaperoneProfilesUpdated() { reloadChaperoneProfiles() } } Connections { target: VideoTabController - onVideoProfilesUpdated: { + function onVideoProfilesUpdated() { reloadVideoProfiles() } } Connections { target: AudioTabController - onMicVolumeChanged: { + function onMicVolumeChanged() { summaryMicVolumeSlider.value = AudioTabController.micVolume } - onMicMutedChanged: { + function onMicMutedChanged() { summaryMicMuteToggle.checked = AudioTabController.micMuted } - onPttEnabledChanged: { + function onPttEnabledChanged() { summaryPttToggle.checked = AudioTabController.pttEnabled } } Connections { target: MoveCenterTabController - onTrackingUniverseChanged: { + function onTrackingUniverseChanged() { if (MoveCenterTabController.trackingUniverse === 0) { summaryPlaySpaceModeText.text = "Sitting" } else if (MoveCenterTabController.trackingUniverse === 1) { diff --git a/src/res/qml/SettingsPage.qml b/src/res/qml/SettingsPage.qml index b5cf9e82..ce6b8698 100644 --- a/src/res/qml/SettingsPage.qml +++ b/src/res/qml/SettingsPage.qml @@ -338,66 +338,66 @@ MyStackViewPage { Connections { target: SettingsTabController - onAutoStartEnabledChanged: { + function onAutoStartEnabledChanged() { settingsAutoStartToggle.checked = SettingsTabController.autoStartEnabled } - onNativeChaperoneToggleChanged:{ + function onNativeChaperoneToggleChanged(){ nativeChaperoneToggleButton.checked = SettingsTabController.nativeChaperoneToggle } - onOculusSdkToggleChanged:{ + function onOculusSdkToggleChanged(){ oculusSdkToggleButton.checked = SettingsTabController.oculusSdkToggle } } Connections { target: MoveCenterTabController - onUniverseCenteredRotationChanged: { + function onUniverseCenteredRotationChanged() { universeCenteredRotationToggle.checked = MoveCenterTabController.universeCenteredRotation } } Connections { target: OverlayController - onVsyncDisabledChanged: { + function onVsyncDisabledChanged() { vsyncDisabledToggle.checked = OverlayController.vsyncDisabled customTickRateText.visible = vsyncDisabledToggle.checked customTickRateLabel.visible = vsyncDisabledToggle.checked customTickRateMsLabel.visible = vsyncDisabledToggle.checked } - onCrashRecoveryDisabledChanged: { + function onCrashRecoveryDisabledChanged() { disableCrashRecoveryToggle.checked = !OverlayController.crashRecoveryDisabled } - onCustomTickRateMsChanged: { + function onCustomTickRateMsChanged() { customTickRateText.text = OverlayController.customTickRateMs } - onEnableDebugChanged: { + function onEnableDebugChanged() { debugStateRow.visible = OverlayController.enableDebug } - onDebugStateChanged: { + function onDebugStateChanged() { debugStateText.text = OverlayController.debugState } - onDisableVersionCheckChanged: { + function onDisableVersionCheckChanged() { disableVersionCheckToggle.checked = OverlayController.disableVersionCheck } - onExclusiveInputEnabledChanged:{ + function onExclusiveInputEnabledChanged(){ exclusiveInputToggleButton.checked = OverlayController.exclusiveInputEnabled } - onAutoApplyChaperoneEnabledChanged: { + function onAutoApplyChaperoneEnabledChanged() { autoApplyChaperoneToggleButton.checked = OverlayController.autoApplyChaperoneEnabled } - onSoundVolumeChanged:{ + function onSoundVolumeChanged(){ volumeSlider.value = OverlayController.soundVolume } - onDesktopModeToggleChanged:{ + function onDesktopModeToggleChanged(){ desktopModeToggleButton.checked = OverlayController.desktopModeToggle } } Connections{ target: ChaperoneTabController - onChaperoneProfilesUpdated: { + function onChaperoneProfilesUpdated() { reloadChaperoneProfiles() } } diff --git a/src/res/qml/audio_page/device_selector/AudioDeviceSelector.qml b/src/res/qml/audio_page/device_selector/AudioDeviceSelector.qml index a46528fc..92c65f52 100644 --- a/src/res/qml/audio_page/device_selector/AudioDeviceSelector.qml +++ b/src/res/qml/audio_page/device_selector/AudioDeviceSelector.qml @@ -44,14 +44,14 @@ RowLayout { Connections { target: AudioTabController - onPlaybackDeviceIndexChanged: { + function onPlaybackDeviceIndexChanged() { setShownAudioDevice(index) } - onPlaybackDeviceListChanged: { + function onPlaybackDeviceListChanged() { audioPlaybackNameCombo.devices = getAudioDeviceList() setShownAudioDevice(AudioTabController.playbackDeviceIndex) } - onPlaybackOverrideChanged: { + function onPlaybackOverrideChanged() { playbackOverrideToggle.value = AudioTabController.playbackOverride } } diff --git a/src/res/qml/audio_page/device_selector/MicDeviceSelector.qml b/src/res/qml/audio_page/device_selector/MicDeviceSelector.qml index 52a0ff9b..a1a5bc3c 100644 --- a/src/res/qml/audio_page/device_selector/MicDeviceSelector.qml +++ b/src/res/qml/audio_page/device_selector/MicDeviceSelector.qml @@ -63,14 +63,14 @@ RowLayout { } Connections { target: AudioTabController - onMicDeviceIndexChanged: { + function onMicDeviceIndexChanged() { setShownAudioDevice(index) } - onRecordingDeviceListChanged: { + function onRecordingDeviceListChanged() { devices = getAudioDeviceList() setShownAudioDevice(AudioTabController.micDeviceIndex) } - onRecordingOverrideChanged: { + function onRecordingOverrideChanged() { recordingOverrideToggle.value = AudioTabController.recordingOverride } } diff --git a/src/res/qml/audio_page/device_selector/MicVolumeSlider.qml b/src/res/qml/audio_page/device_selector/MicVolumeSlider.qml index 3119135a..e485c5a0 100644 --- a/src/res/qml/audio_page/device_selector/MicVolumeSlider.qml +++ b/src/res/qml/audio_page/device_selector/MicVolumeSlider.qml @@ -89,7 +89,7 @@ ColumnLayout { } Connections { target: AudioTabController - onMicDeviceIndexChanged: { + function onMicDeviceIndexChanged() { if (index < 0) { audioMicVolumeMinusButton.enabled = false audioMicVolumeSlider.enabled = false @@ -102,16 +102,16 @@ ColumnLayout { audioMicMuteToggle.enabled = true } } - onMicVolumeChanged: { + function onMicVolumeChanged() { audioMicVolumeSlider.value = AudioTabController.micVolume } - onMicMutedChanged: { + function onMicMutedChanged() { audioMicMuteToggle.checked = AudioTabController.micMuted } - onPlaybackDeviceListChanged: { + function onPlaybackDeviceListChanged() { } - onRecordingDeviceListChanged: { + function onRecordingDeviceListChanged() { if (AudioTabController.micDeviceIndex < 0) { audioMicVolumeMinusButton.enabled = false audioMicVolumeSlider.enabled = false diff --git a/src/res/qml/audio_page/device_selector/MirrorDeviceSelector.qml b/src/res/qml/audio_page/device_selector/MirrorDeviceSelector.qml index fb4d715d..5b178cf4 100644 --- a/src/res/qml/audio_page/device_selector/MirrorDeviceSelector.qml +++ b/src/res/qml/audio_page/device_selector/MirrorDeviceSelector.qml @@ -41,10 +41,10 @@ RowLayout { } Connections { target: AudioTabController - onMirrorDeviceIndexChanged: { + function onMirrorDeviceIndexChanged() { setShownAudioDevice(index) } - onPlaybackDeviceListChanged: { + function onPlaybackDeviceListChanged() { audioMirrorNameCombo.devices = getAudioDeviceList() setShownAudioDevice(AudioTabController.mirrorDeviceIndex) } diff --git a/src/res/qml/audio_page/device_selector/MirrorVolumeSlider.qml b/src/res/qml/audio_page/device_selector/MirrorVolumeSlider.qml index c8ff4ba0..f70f6cba 100644 --- a/src/res/qml/audio_page/device_selector/MirrorVolumeSlider.qml +++ b/src/res/qml/audio_page/device_selector/MirrorVolumeSlider.qml @@ -89,7 +89,7 @@ ColumnLayout { } Connections { target: AudioTabController - onMirrorDeviceIndexChanged: { + function onMirrorDeviceIndexChanged() { if (index < 0) { audioMirrorNameCombo.deviceIndex = 0 audioMirrorVolumeMinusButton.enabled = false @@ -104,13 +104,13 @@ ColumnLayout { audioMirrorNameCombo.deviceIndex = index + 1 } } - onMirrorVolumeChanged: { + function onMirrorVolumeChanged() { audioMirrorVolumeSlider.value = AudioTabController.mirrorVolume } - onMirrorMutedChanged: { + function onMirrorMutedChanged() { audioMirrorMuteToggle.checked = AudioTabController.mirrorMuted } - onPlaybackDeviceListChanged: { + function onPlaybackDeviceListChanged() { if (AudioTabController.mirrorDeviceIndex < 0) { audioMirrorVolumeMinusButton.enabled = false audioMirrorVolumeSlider.enabled = false diff --git a/src/res/qml/audio_page/profiles/ProfileButtons.qml b/src/res/qml/audio_page/profiles/ProfileButtons.qml index 2914e6bc..7c743f7b 100644 --- a/src/res/qml/audio_page/profiles/ProfileButtons.qml +++ b/src/res/qml/audio_page/profiles/ProfileButtons.qml @@ -98,13 +98,13 @@ ColumnLayout { } Connections { target: AudioTabController - onAudioProfilesUpdated: { + function onAudioProfilesUpdated() { reloadAudioProfiles() } - onAudioProfileAdded: { + function onAudioProfileAdded() { audioProfileComboBox.currentIndex = AudioTabController.getAudioProfileCount() } - onDefaultProfileDisplay: { + function onDefaultProfileDisplay() { audioProfileComboBox.currentIndex = AudioTabController.getDefaultAudioProfileIndex( ) + 1 } diff --git a/src/res/qml/audio_page/proximity/ProximityToggle.qml b/src/res/qml/audio_page/proximity/ProximityToggle.qml index 45cc3d16..a832cbd8 100644 --- a/src/res/qml/audio_page/proximity/ProximityToggle.qml +++ b/src/res/qml/audio_page/proximity/ProximityToggle.qml @@ -21,7 +21,7 @@ MyToggleButton { } Connections { target: AudioTabController - onMicProximitySensorCanMuteChanged: { + function onMicProximitySensorCanMuteChanged() { audioMuteProximitySensorToggle.checked = AudioTabController.micProximitySensorCanMute } } diff --git a/src/res/qml/audio_page/push_to_talk/PttButtons.qml b/src/res/qml/audio_page/push_to_talk/PttButtons.qml index 3ad93b1e..12c848c1 100644 --- a/src/res/qml/audio_page/push_to_talk/PttButtons.qml +++ b/src/res/qml/audio_page/push_to_talk/PttButtons.qml @@ -39,13 +39,13 @@ ColumnLayout { } Connections { target: AudioTabController - onPttEnabledChanged: { + function onPttEnabledChanged() { audioPttEnabledToggle.checked = AudioTabController.pttEnabled } - onMicReversePttChanged: { + function onMicReversePttChanged() { audioPttReverseToggle.checked = AudioTabController.micReversePtt } - onPttShowNotificationChanged: { + function onPttShowNotificationChanged() { audioPttShowNotificationToggle.checked = AudioTabController.pttShowNotification } } diff --git a/src/res/qml/chaperone_page/ChaperonePage.qml b/src/res/qml/chaperone_page/ChaperonePage.qml index 1adc8b10..895a9e26 100644 --- a/src/res/qml/chaperone_page/ChaperonePage.qml +++ b/src/res/qml/chaperone_page/ChaperonePage.qml @@ -1,7 +1,7 @@ import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 -import QtQuick.Dialogs 1.2 +import QtQuick.Dialogs import ovras.advsettings 1.0 import "." // QTBUG-34418, singletons require explicit import to load qmldir file import "../common" @@ -586,26 +586,26 @@ MyStackViewPage { Connections { target: ChaperoneTabController - onBoundsVisibilityChanged: { + function onBoundsVisibilityChanged() { if (Math.abs(chaperoneVisibilitySlider.value - ChaperoneTabController.boundsVisibility) > 0.008) { chaperoneVisibilitySlider.value = ChaperoneTabController.boundsVisibility } } - onFadeDistanceChanged: { + function onFadeDistanceChanged() { var d = ChaperoneTabController.fadeDistance.toFixed(1) if (d <= chaperoneFadeDistanceSlider.to && Math.abs(chaperoneFadeDistanceSlider.value - d) > 0.008) { chaperoneFadeDistanceSlider.value = d } chaperoneFadeDistanceText.text = d } - onHeightChanged: { + function onHeightChanged() { var h = ChaperoneTabController.height.toFixed(2) if (h <= chaperoneHeightSlider.to && Math.abs(chaperoneHeightSlider.value - h) > 0.008) { chaperoneHeightSlider.value = h } chaperoneHeightText.text = h } - onChaperoneDimHeightChanged: { + function onChaperoneDimHeightChanged() { var dim = ChaperoneTabController.chaperoneDimHeight if(dim > 0.0){ chaperoneDisableChaperone.enabled = false; @@ -625,16 +625,16 @@ MyStackViewPage { chaperoneFadeDistanceText.enabled = true; } } - onCenterMarkerNewChanged: { + function onCenterMarkerNewChanged() { chaperoneCenterMarkerToggle.checked = ChaperoneTabController.centerMarkerNew } - onPlaySpaceMarkerChanged: { + function onPlaySpaceMarkerChanged() { chaperonePlaySpaceToggle.checked = ChaperoneTabController.playSpaceMarker } - onForceBoundsChanged: { + function onForceBoundsChanged() { chaperoneForceBoundsToggle.checked = ChaperoneTabController.forceBounds } - onChaperoneProfilesUpdated: { + function onChaperoneProfilesUpdated() { reloadChaperoneProfiles() } } diff --git a/src/res/qml/chaperone_page/chaperone_additional/ChaperoneAdditionalPage.qml b/src/res/qml/chaperone_page/chaperone_additional/ChaperoneAdditionalPage.qml index 8f18c33c..9e4dcdcd 100644 --- a/src/res/qml/chaperone_page/chaperone_additional/ChaperoneAdditionalPage.qml +++ b/src/res/qml/chaperone_page/chaperone_additional/ChaperoneAdditionalPage.qml @@ -1,7 +1,7 @@ import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 -import QtQuick.Dialogs 1.2 +import QtQuick.Dialogs import ovras.advsettings 1.0 import "." // QTBUG-34418, singletons require explicit import to load qmldir file import "../../common" @@ -113,7 +113,7 @@ MyStackViewPage { Connections { target: ChaperoneTabController - onChaperoneDimHeightChanged: { + function onChaperoneDimHeightChanged() { var d = ChaperoneTabController.chaperoneDimHeight.toFixed(2) if (d <= dimHeightSlider.to && Math.abs(dimHeightSlider.value - d) > 0.0008) { dimHeightSlider.value = d diff --git a/src/res/qml/chaperone_page/chaperone_additional/chaperoneboundscolor/ChaperoneBoundsColorGroupBox.qml b/src/res/qml/chaperone_page/chaperone_additional/chaperoneboundscolor/ChaperoneBoundsColorGroupBox.qml index e1c48c00..9107afc4 100644 --- a/src/res/qml/chaperone_page/chaperone_additional/chaperoneboundscolor/ChaperoneBoundsColorGroupBox.qml +++ b/src/res/qml/chaperone_page/chaperone_additional/chaperoneboundscolor/ChaperoneBoundsColorGroupBox.qml @@ -180,17 +180,17 @@ GroupBox { Connections { target: ChaperoneTabController - onChaperoneColorRChanged:{ + function onChaperoneColorRChanged(){ var redValue = ChaperoneTabController.chaperoneColorR colorRedText.text = redValue chaperoneColorRedSlider.value = redValue } - onChaperoneColorGChanged:{ + function onChaperoneColorGChanged(){ var greenValue = ChaperoneTabController.chaperoneColorG colorGreenText.text = greenValue chaperoneColorGreenSlider.value = greenValue } - onChaperoneColorBChanged:{ + function onChaperoneColorBChanged(){ var blueValue = ChaperoneTabController.chaperoneColorB colorBlueText.text = blueValue chaperoneColorBlueSlider.value = blueValue diff --git a/src/res/qml/chaperone_page/chaperone_additional/chaperonemisc/ChaperoneMiscGroupBox.qml b/src/res/qml/chaperone_page/chaperone_additional/chaperonemisc/ChaperoneMiscGroupBox.qml index 43705f10..e1c6d861 100644 --- a/src/res/qml/chaperone_page/chaperone_additional/chaperonemisc/ChaperoneMiscGroupBox.qml +++ b/src/res/qml/chaperone_page/chaperone_additional/chaperonemisc/ChaperoneMiscGroupBox.qml @@ -70,10 +70,10 @@ GroupBox { Connections { target: ChaperoneTabController - onChaperoneFloorToggleChanged:{ + function onChaperoneFloorToggleChanged(){ chaperoneFloorToggleBtn.checked = ChaperoneTabController.chaperoneFloorToggle } - onCenterMarkerChanged:{ + function onCenterMarkerChanged(){ legacyCenterMarkerbtn.checked = ChaperoneTabController.centerMarker } } diff --git a/src/res/qml/chaperone_page/chaperone_additional/chaperonetype/ChaperoneTypeGroupBox.qml b/src/res/qml/chaperone_page/chaperone_additional/chaperonetype/ChaperoneTypeGroupBox.qml index 18063227..19740e3a 100644 --- a/src/res/qml/chaperone_page/chaperone_additional/chaperonetype/ChaperoneTypeGroupBox.qml +++ b/src/res/qml/chaperone_page/chaperone_additional/chaperonetype/ChaperoneTypeGroupBox.qml @@ -112,7 +112,7 @@ GroupBox { Connections { target: ChaperoneTabController - onCollisionBoundStyleChanged:{ + function onCollisionBoundStyleChanged(){ var collisiontype = ChaperoneTabController.collisionBoundStyle switch(collisiontype){ case 0: denseRadio.checked = true; break; diff --git a/src/res/qml/common/MyTextField.qml b/src/res/qml/common/MyTextField.qml index cbfd81ac..2b6d2b22 100644 --- a/src/res/qml/common/MyTextField.qml +++ b/src/res/qml/common/MyTextField.qml @@ -39,7 +39,7 @@ TextField { } Connections { target: OverlayController - onKeyBoardInputSignal: { + function onKeyBoardInputSignal() { if (userValue == keyBoardUID) { if (myTextField.text !== input) { myTextField.onInputEvent(input) diff --git a/src/res/qml/motion_page/gravity/GravityGroupBox.qml b/src/res/qml/motion_page/gravity/GravityGroupBox.qml index e0e57685..b0855f36 100644 --- a/src/res/qml/motion_page/gravity/GravityGroupBox.qml +++ b/src/res/qml/motion_page/gravity/GravityGroupBox.qml @@ -218,19 +218,19 @@ GroupBox { Connections { target: MoveCenterTabController - onGravityActiveChanged: { + function onGravityActiveChanged() { gravityToggleButton.checked = MoveCenterTabController.gravityActive } - onGravityStrengthChanged: { + function onGravityStrengthChanged() { gravityStrengthText.text = MoveCenterTabController.gravityStrength.toFixed(2) } - onMomentumSaveChanged: { + function onMomentumSaveChanged() { momentumToggleButton.checked = MoveCenterTabController.momentumSave } - onFlingStrengthChanged: { + function onFlingStrengthChanged() { flingStrengthText.text = MoveCenterTabController.flingStrength.toFixed(2) } - onFrictionPercentChanged: { + function onFrictionPercentChanged() { frictionPercentText.text = MoveCenterTabController.frictionPercent + "%" } } diff --git a/src/res/qml/motion_page/height_toggle/HeightToggleGroupBox.qml b/src/res/qml/motion_page/height_toggle/HeightToggleGroupBox.qml index d88e0d50..95c95a42 100644 --- a/src/res/qml/motion_page/height_toggle/HeightToggleGroupBox.qml +++ b/src/res/qml/motion_page/height_toggle/HeightToggleGroupBox.qml @@ -88,10 +88,10 @@ GroupBox { Connections { target: MoveCenterTabController - onHeightToggleChanged: { + function onHeightToggleChanged() { heightToggleButton.checked = MoveCenterTabController.heightToggle } - onHeightToggleOffsetChanged: { + function onHeightToggleOffsetChanged() { heightToggleOffsetText.text = MoveCenterTabController.heightToggleOffset.toFixed(2) } } diff --git a/src/res/qml/motion_page/space_drag/SpaceDragGroupBox.qml b/src/res/qml/motion_page/space_drag/SpaceDragGroupBox.qml index 5b291f4b..ea9cd7f9 100644 --- a/src/res/qml/motion_page/space_drag/SpaceDragGroupBox.qml +++ b/src/res/qml/motion_page/space_drag/SpaceDragGroupBox.qml @@ -156,19 +156,19 @@ GroupBox { Connections { target: MoveCenterTabController - onMoveShortcutLeftChanged: { + function onMoveShortcutLeftChanged() { moveShortcutLeft.checked = MoveCenterTabController.moveShortcutLeft } - onMoveShortcutRightChanged: { + function onMoveShortcutRightChanged() { moveShortcutRight.checked = MoveCenterTabController.moveShortcutRight } - onDragComfortFactorChanged: { + function onDragComfortFactorChanged() { dragComfortSlider.value = MoveCenterTabController.dragComfortFactor } - onDragBoundsChanged: { + function onDragBoundsChanged() { dragBounds.checked = MoveCenterTabController.dragBounds } - onDragMultChanged: { + function onDragMultChanged() { dragMultText.text = MoveCenterTabController.dragMult.toFixed(2) } } diff --git a/src/res/qml/rotation_page/redirected/AutoTurnGroupBox.qml b/src/res/qml/rotation_page/redirected/AutoTurnGroupBox.qml index 58d03013..0218af79 100644 --- a/src/res/qml/rotation_page/redirected/AutoTurnGroupBox.qml +++ b/src/res/qml/rotation_page/redirected/AutoTurnGroupBox.qml @@ -312,23 +312,23 @@ GroupBox { Connections { target: RotationTabController - onAutoTurnEnabledChanged: { + function onAutoTurnEnabledChanged() { autoTurn.checked = RotationTabController.autoTurnEnabled } - onAutoTurnActivationDistanceChanged: { + function onAutoTurnActivationDistanceChanged() { activationSlider.value = RotationTabController.autoTurnActivationDistance.toFixed(2) } - onAutoTurnDeactivationDistanceChanged:{ + function onAutoTurnDeactivationDistanceChanged(){ deactivationSlider.value = RotationTabController.autoTurnDeactivationDistance.toFixed(2) } - onAutoTurnUseCornerAngleChanged:{ + function onAutoTurnUseCornerAngleChanged(){ cornerAngle.checked = RotationTabController.autoTurnUseCornerAngle } - onAutoTurnSpeedChanged:{ + function onAutoTurnSpeedChanged(){ var val = RotationTabController.autoTurnSpeed speedSlider.value = ((val/100).toFixed()) } - onAutoTurnModeChanged:{ + function onAutoTurnModeChanged(){ if(RotationTabController.autoTurnMode === 1){ autoTurnModeToggle.checked = true; @@ -338,13 +338,13 @@ GroupBox { autoTurnModeToggle.checked = false; } } - onMinCordTangleChanged:{ + function onMinCordTangleChanged(){ detangleAngleStartText.text = parseInt(RotationTabController.minCordTangle*(180/Math.PI))+ "°" } - onCordDetangleAngleChanged:{ + function onCordDetangleAngleChanged(){ detangleAngleAssistText.text = parseInt(RotationTabController.cordDetangleAngle*(180/Math.PI))+ "°" } - onAutoTurnShowNotificationChanged:{ + function onAutoTurnShowNotificationChanged(){ autoTurnNotificationToggle.checked = RotationTabController.autoTurnShowNotification } } diff --git a/src/res/qml/rotation_page/redirected/RedirectedGroupBox.qml b/src/res/qml/rotation_page/redirected/RedirectedGroupBox.qml index b1bd8cea..49258bda 100644 --- a/src/res/qml/rotation_page/redirected/RedirectedGroupBox.qml +++ b/src/res/qml/rotation_page/redirected/RedirectedGroupBox.qml @@ -115,10 +115,10 @@ GroupBox { Connections { target: RotationTabController - onVestibularMotionEnabledChanged:{ + function onVestibularMotionEnabledChanged(){ redirectedModeToggle.checked = RotationTabController.vestibularMotionEnabled } - onVestibularMotionRadiusChanged:{ + function onVestibularMotionRadiusChanged(){ redirectedWalkingRadiusText.text = ((RotationTabController.vestibularMotionRadius).toFixed(2)) } } diff --git a/src/res/qml/rotation_page/snap_turn/SnapTurnGroupBox.qml b/src/res/qml/rotation_page/snap_turn/SnapTurnGroupBox.qml index 4e25dde8..b639b6ae 100644 --- a/src/res/qml/rotation_page/snap_turn/SnapTurnGroupBox.qml +++ b/src/res/qml/rotation_page/snap_turn/SnapTurnGroupBox.qml @@ -103,10 +103,10 @@ GroupBox { Connections { target: MoveCenterTabController - onSnapTurnAngleChanged: { + function onSnapTurnAngleChanged() { snapTurnAngleText.text = ( Math.round( MoveCenterTabController.snapTurnAngle / 100 ) ) + "°" } - onSmoothTurnRateChanged: { + function onSmoothTurnRateChanged() { smoothTurnRateText.text = MoveCenterTabController.smoothTurnRate + "%" } } diff --git a/src/res/qml/rotation_page/space_turn/SpaceTurnGroupBox.qml b/src/res/qml/rotation_page/space_turn/SpaceTurnGroupBox.qml index 191ab234..6301e43b 100644 --- a/src/res/qml/rotation_page/space_turn/SpaceTurnGroupBox.qml +++ b/src/res/qml/rotation_page/space_turn/SpaceTurnGroupBox.qml @@ -100,16 +100,16 @@ GroupBox { Connections { target: MoveCenterTabController - onTurnBindLeftChanged: { + function onTurnBindLeftChanged() { turnBindLeft.checked = MoveCenterTabController.turnBindLeft } - onTurnBindRightChanged: { + function onTurnBindRightChanged() { turnBindRight.checked = MoveCenterTabController.turnBindRight } - onTurnComfortFactorChanged: { + function onTurnComfortFactorChanged() { turnComfortSlider.value = MoveCenterTabController.turnComfortFactor } - onTurnBoundsChanged: { + function onTurnBoundsChanged() { turnBounds.checked = MoveCenterTabController.turnBounds } } diff --git a/src/res/qml/rotation_page/view_ratchet/ViewRatchetGroupBox.qml b/src/res/qml/rotation_page/view_ratchet/ViewRatchetGroupBox.qml index 683da3fe..6ab011b0 100644 --- a/src/res/qml/rotation_page/view_ratchet/ViewRatchetGroupBox.qml +++ b/src/res/qml/rotation_page/view_ratchet/ViewRatchetGroupBox.qml @@ -76,10 +76,10 @@ GroupBox { Connections { target: RotationTabController - onViewRatchettingEnabledChanged:{ + function onViewRatchettingEnabledChanged(){ viewRatchetToggleBtn.checked = RotationTabController.viewRatchettingEnabled } - onViewRatchettingPercentChanged:{ + function onViewRatchettingPercentChanged(){ var ratchetPercVal = RotationTabController.viewRatchettingPercent viewRatchetSlider.value = ratchetPercVal viewRatchetText.text = ratchetPercVal.toFixed(2) diff --git a/src/res/qml/steamvr_page/camera/CameraGroupBox.qml b/src/res/qml/steamvr_page/camera/CameraGroupBox.qml index 685780f8..08d3b287 100644 --- a/src/res/qml/steamvr_page/camera/CameraGroupBox.qml +++ b/src/res/qml/steamvr_page/camera/CameraGroupBox.qml @@ -92,13 +92,13 @@ GroupBox { Connections { target: SteamVRTabController - onCameraActiveChanged: { + function onCameraActiveChanged() { steamvrCameraActiveToggle.checked = SteamVRTabController.cameraActive } - onCameraContChanged: { + function onCameraContChanged() { steamvrCameraContToggle.checked = SteamVRTabController.cameraCont } - onCameraBoundsChanged: { + function onCameraBoundsChanged() { steamvrCameraBoundsToggle.checked = SteamVRTabController.cameraBounds } diff --git a/src/res/qml/steamvr_page/steamvr_additional/SteamVRTXRXPage.qml b/src/res/qml/steamvr_page/steamvr_additional/SteamVRTXRXPage.qml index 3738a844..2762c1f6 100644 --- a/src/res/qml/steamvr_page/steamvr_additional/SteamVRTXRXPage.qml +++ b/src/res/qml/steamvr_page/steamvr_additional/SteamVRTXRXPage.qml @@ -2,7 +2,7 @@ import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.3 -import QtQuick.Dialogs 1.2 +import QtQuick.Dialogs import ovras.advsettings 1.0 import "." // QTBUG-34418, singletons require explicit import to load qmldir file import "../../common" @@ -185,11 +185,11 @@ MyStackViewPage { } Connections{ target: SteamVRTabController - onPairStatusChanged: { + function onPairStatusChanged() { statusText.text = value; getRXTX() } - onUpdateRXTX:{ + function onUpdateRXTX(){ getRXTX() } diff --git a/src/res/qml/steamvr_page/steamvrbind/SteamVRBindGroupBox.qml b/src/res/qml/steamvr_page/steamvrbind/SteamVRBindGroupBox.qml index 61d55403..f3c90522 100644 --- a/src/res/qml/steamvr_page/steamvrbind/SteamVRBindGroupBox.qml +++ b/src/res/qml/steamvr_page/steamvrbind/SteamVRBindGroupBox.qml @@ -130,7 +130,7 @@ GroupBox { Connections { target: SteamVRTabController - onPerformanceGraphChanged:{ + function onPerformanceGraphChanged() { steamvrBindingToggle.checked = SteamVRTabController.perAppBindEnabled } diff --git a/src/res/qml/steamvr_page/steamvrmisc/SteamVRMiscGroupBox.qml b/src/res/qml/steamvr_page/steamvrmisc/SteamVRMiscGroupBox.qml index e0cd7ee2..6d30a0dc 100644 --- a/src/res/qml/steamvr_page/steamvrmisc/SteamVRMiscGroupBox.qml +++ b/src/res/qml/steamvr_page/steamvrmisc/SteamVRMiscGroupBox.qml @@ -131,25 +131,25 @@ GroupBox { Connections { target: SteamVRTabController - onPerformanceGraphChanged:{ + function onPerformanceGraphChanged(){ steamvrPerformanceGraphToggle.checked = SteamVRTabController.performanceGraph } - onSystemButtonChanged:{ + function onSystemButtonChanged(){ steamvrSystemButtonToggle.checked = SteamVRTabController.systemButton } - onMultipleDriverChanged:{ + function onMultipleDriverChanged(){ steamvrMultipleDriverToggle.checked = SteamVRTabController.multipleDriver } - onNoFadeToGridChanged:{ + function onNoFadeToGridChanged(){ steamvrNoFadeToGridToggle.checked = SteamVRTabController.noFadeToGrid } - onDNDChanged:{ + function onDNDChanged(){ steamvrNotificationToggle.checked = SteamVRTabController.dnd } - onNoHMDChanged:{ + function onNoHMDChanged(){ steamvrNoHMDToggle.checked = SteamVRTabController.noHMD } - onControllerPowerChanged:{ + function onControllerPowerChanged(){ steamvrControllerPowerToggle.checked = SteamVRTabController.controllerPower } diff --git a/src/res/qml/utilities_page/alarm_clock/AlarmGroupBox.qml b/src/res/qml/utilities_page/alarm_clock/AlarmGroupBox.qml index a4450822..b4a69c8f 100644 --- a/src/res/qml/utilities_page/alarm_clock/AlarmGroupBox.qml +++ b/src/res/qml/utilities_page/alarm_clock/AlarmGroupBox.qml @@ -103,10 +103,10 @@ GroupBox { } Connections { target: VrAlarm - onAlarmEnabledChanged: { + function onAlarmEnabledChanged() { alarmClockToggle.checked = VrAlarm.alarmEnabled } - onAlarmTimeChanged: { + function onAlarmTimeChanged() { alarmClockTimeAssembly.changeTimer(VrAlarm.getAlarmHour(), VrAlarm.getAlarmMinute(), VrAlarm.getAlarmSecond()) diff --git a/src/res/qml/utilities_page/keyboard_utils/KeyboardGroupBox.qml b/src/res/qml/utilities_page/keyboard_utils/KeyboardGroupBox.qml index e34c750f..a6fd7db1 100644 --- a/src/res/qml/utilities_page/keyboard_utils/KeyboardGroupBox.qml +++ b/src/res/qml/utilities_page/keyboard_utils/KeyboardGroupBox.qml @@ -45,7 +45,7 @@ GroupBox { } Connections { target: OverlayController - onKeyBoardInputSignal: { + function onKeyBoardInputSignal() { if (userValue == 601) { UtilitiesTabController.sendKeyboardInput(input) } @@ -581,7 +581,7 @@ GroupBox { } Connections { target: UtilitiesTabController - onVrcDebugChanged: { + function onVrcDebugChanged() { vrcDebugRow.visible = UtilitiesTabController.vrcDebug } } diff --git a/src/res/qml/utilities_page/misc/MiscBox.qml b/src/res/qml/utilities_page/misc/MiscBox.qml index e85e58fe..185ce5e3 100644 --- a/src/res/qml/utilities_page/misc/MiscBox.qml +++ b/src/res/qml/utilities_page/misc/MiscBox.qml @@ -53,7 +53,7 @@ GroupBox { Connections { target: UtilitiesTabController - onTrackerOvlEnabledChanged:{ + function onTrackerOvlEnabledChanged(){ trackerOvlToggle.checked = UtilitiesTabController.trackerOvlEnabled } diff --git a/src/res/qml/video_page/VideoPage.qml b/src/res/qml/video_page/VideoPage.qml index 139992f5..00e34b9e 100644 --- a/src/res/qml/video_page/VideoPage.qml +++ b/src/res/qml/video_page/VideoPage.qml @@ -47,7 +47,7 @@ MyStackViewPage { Connections { target: VideoTabController - onIsOverlayMethodActiveChanged:{ + function onIsOverlayMethodActiveChanged(){ overlayMethodGroupBox.visible = VideoTabController.isOverlayMethodActive brightnessGroupBox.visible = !(VideoTabController.isOverlayMethodActive); colorGroupBox.visible = !(VideoTabController.isOverlayMethodActive); diff --git a/src/res/qml/video_page/brightness/BrightnessGroupBox.qml b/src/res/qml/video_page/brightness/BrightnessGroupBox.qml index cd3ab294..0b1fa79b 100644 --- a/src/res/qml/video_page/brightness/BrightnessGroupBox.qml +++ b/src/res/qml/video_page/brightness/BrightnessGroupBox.qml @@ -95,12 +95,12 @@ GroupBox { Connections { target: VideoTabController - onBrightnessOpacityValueChanged: { + function onBrightnessOpacityValueChanged() { var brightvalue = VideoTabController.brightnessOpacityValue brightnessSlider.value = brightvalue brightnessValueText.text = Math.round(brightvalue*100)+ "%" } - onBrightnessEnabledChanged: { + function onBrightnessEnabledChanged() { brightnessToggle.checked = VideoTabController.brightnessEnabled } } diff --git a/src/res/qml/video_page/color/ColorGroupBox.qml b/src/res/qml/video_page/color/ColorGroupBox.qml index 06bab0cf..6aea8e43 100644 --- a/src/res/qml/video_page/color/ColorGroupBox.qml +++ b/src/res/qml/video_page/color/ColorGroupBox.qml @@ -197,17 +197,17 @@ GroupBox { Connections { target: VideoTabController - onColorRedChanged:{ + function onColorRedChanged(){ var redValue = VideoTabController.colorRed colorRedText.text = Math.round(redValue * 100) + "%" colorRedSlider.value = redValue } - onColorGreenChanged:{ + function onColorGreenChanged(){ var greenValue = VideoTabController.colorGreen colorGreenText.text = Math.round(greenValue * 100) + "%" colorGreenSlider.value = greenValue } - onColorBlueChanged:{ + function onColorBlueChanged(){ var blueValue = VideoTabController.colorBlue colorBlueText.text = Math.round(blueValue * 100) + "%" colorBlueSlider.value = blueValue diff --git a/src/res/qml/video_page/miscvid/VideoMiscGroupBox.qml b/src/res/qml/video_page/miscvid/VideoMiscGroupBox.qml index 65b0f026..ebfb98b9 100644 --- a/src/res/qml/video_page/miscvid/VideoMiscGroupBox.qml +++ b/src/res/qml/video_page/miscvid/VideoMiscGroupBox.qml @@ -73,14 +73,14 @@ GroupBox { Connections { target: VideoTabController - onAllowSupersampleFilteringChanged: { + function onAllowSupersampleFilteringChanged() { videoAllowSupersampleFilteringToggle.checked = VideoTabController.allowSupersampleFiltering } - onMotionSmoothingChanged: { + function onMotionSmoothingChanged() { videoMotionSmoothingToggle.checked = VideoTabController.motionSmoothing } - onIsOverlayMethodActiveChanged:{ + function onIsOverlayMethodActiveChanged(){ videoUseOverlayToggle.checked = VideoTabController.isOverlayMethodActive } diff --git a/src/res/qml/video_page/overlaycolorbright/OverlayMethodGroupBox.qml b/src/res/qml/video_page/overlaycolorbright/OverlayMethodGroupBox.qml index 690b4c5e..28b111c3 100644 --- a/src/res/qml/video_page/overlaycolorbright/OverlayMethodGroupBox.qml +++ b/src/res/qml/video_page/overlaycolorbright/OverlayMethodGroupBox.qml @@ -298,32 +298,33 @@ GroupBox { Connections { target: VideoTabController - onBrightnessOpacityValueChanged: { + function onBrightnessOpacityValueChanged() { var brightvalue = VideoTabController.brightnessOpacityValue brightnessSlider.value = brightvalue brightnessValueText.text = Math.round(brightvalue*100)+ "%" + brightnessSlider.value = VideoTabController.brightnessOpacityValue } - onBrightnessEnabledChanged: { + function onBrightnessEnabledChanged() { brightnessToggle.checked = VideoTabController.brightnessEnabled } - onColorOverlayOpacityChanged:{ + function onColorOverlayOpacityChanged(){ opacitySlider.value = VideoTabController.colorOverlayOpacity } - onColorOverlayEnabledChanged:{ + function onColorOverlayEnabledChanged(){ colorToggle.checked = VideoTabController.colorOverlayEnabled } - onColorRedChanged:{ + function onColorRedChanged(){ var redValue = VideoTabController.colorRed colorRedText.text = Math.round(redValue * 100) + "%" colorRedSlider.value = redValue } - onColorGreenChanged:{ + function onColorGreenChanged(){ var greenValue = VideoTabController.colorGreen colorGreenText.text = Math.round(greenValue * 100) + "%" colorGreenSlider.value = greenValue } - onColorBlueChanged:{ + function onColorBlueChanged(){ var blueValue = VideoTabController.colorBlue colorBlueText.text = Math.round(blueValue * 100) + "%" colorBlueSlider.value = blueValue diff --git a/src/res/qml/video_page/profiles/VideoProfileGroupBox.qml b/src/res/qml/video_page/profiles/VideoProfileGroupBox.qml index e79201da..23a3ceba 100644 --- a/src/res/qml/video_page/profiles/VideoProfileGroupBox.qml +++ b/src/res/qml/video_page/profiles/VideoProfileGroupBox.qml @@ -108,10 +108,10 @@ GroupBox { } Connections { target: VideoTabController - onVideoProfilesUpdated: { + function onVideoProfilesUpdated() { reloadVideoProfiles() } - onVideoProfileAdded: { + function onVideoProfileAdded() { videoProfileComboBox.currentIndex = VideoTabController.getVideoProfileCount() } diff --git a/src/res/qml/video_page/supersampling/SuperSamplingGroupBox.qml b/src/res/qml/video_page/supersampling/SuperSamplingGroupBox.qml index 6e9ecc17..37bf6aac 100644 --- a/src/res/qml/video_page/supersampling/SuperSamplingGroupBox.qml +++ b/src/res/qml/video_page/supersampling/SuperSamplingGroupBox.qml @@ -133,12 +133,12 @@ GroupBox { Connections { target: VideoTabController - onSuperSamplingChanged: { + function onSuperSamplingChanged() { var s1 = VideoTabController.superSampling videoSupersamplingSlider.value = s1 videoSupersamplingText.text = s1.toFixed(2) } - onAllowSupersampleOverrideChanged: { + function onAllowSupersampleOverrideChanged() { videoAllowSupersampleOverrideToggle.checked = VideoTabController.allowSupersampleOverride var s1 = VideoTabController.superSampling videoSupersamplingSlider.value = s1 diff --git a/src/res/resources.qrc b/src/res/resources.qrc index 7c6192dd..ff43e76c 100644 --- a/src/res/resources.qrc +++ b/src/res/resources.qrc @@ -1,34 +1,74 @@ - - - img/common/backarrow.svg - img/common/check.svg - - - img/audio/microphone/mic_on.svg - img/audio/microphone/mic_off.svg - - - img/audio/speaker/speaker_on.svg - img/audio/speaker/speaker_off.svg - - - img/audio/media_keys/outline_play_pause_white_24dp.svg - img/audio/media_keys/outline_skip_next_white_24dp.svg - img/audio/media_keys/outline_skip_previous_white_24dp.svg - img/audio/media_keys/outline_stop_white_24dp.svg - - - img/main_menu_icons/audio_tab_icon.svg - img/main_menu_icons/bindings_tab_icon.svg - img/main_menu_icons/chaperone_tab_icon.svg - img/main_menu_icons/motion_tab_icon.svg - img/main_menu_icons/offsets_tab_icon.svg - img/main_menu_icons/settings_tab_icon.svg - img/main_menu_icons/space_fix_tab_icon.svg - img/main_menu_icons/statistics_tab_icon.svg - img/main_menu_icons/steamvr_tab_icon.svg - img/main_menu_icons/utilities_tab_icon.svg - img/main_menu_icons/video_tab_icon.svg - img/main_menu_icons/rotation_tab_icon.svg - - \ No newline at end of file + + + img/common/backarrow.svg + img/common/check.svg + + + img/icons/thumbicon.png + + + img/audio/microphone/mic_on.svg + img/audio/microphone/mic_off.svg + img/audio/microphone/ptt_notification.png + img/audio/microphone/ptm_notification.png + img/audio/microphone/ptt_notification.svg + + + img/audio/speaker/speaker_on.svg + img/audio/speaker/speaker_off.svg + + + img/audio/media_keys/outline_play_pause_white_24dp.svg + img/audio/media_keys/outline_skip_next_white_24dp.svg + img/audio/media_keys/outline_skip_previous_white_24dp.svg + img/audio/media_keys/outline_stop_white_24dp.svg + + + img/main_menu_icons/audio_tab_icon.svg + img/main_menu_icons/bindings_tab_icon.svg + img/main_menu_icons/chaperone_tab_icon.svg + img/main_menu_icons/motion_tab_icon.svg + img/main_menu_icons/offsets_tab_icon.svg + img/main_menu_icons/settings_tab_icon.svg + img/main_menu_icons/space_fix_tab_icon.svg + img/main_menu_icons/statistics_tab_icon.svg + img/main_menu_icons/steamvr_tab_icon.svg + img/main_menu_icons/utilities_tab_icon.svg + img/main_menu_icons/video_tab_icon.svg + img/main_menu_icons/rotation_tab_icon.svg + + + sounds/alarm01.wav + sounds/click.wav + sounds/focus.wav + + + img/battery/battery_0.png + img/battery/battery_1.png + img/battery/battery_2.png + img/battery/battery_3.png + img/battery/battery_4.png + img/battery/battery_5.png + + + img/chaperone/centermark.png + img/chaperone/centermarkl1.png + img/chaperone/centermarkl2.png + img/chaperone/centermarkl3.png + img/chaperone/centermarkr1.png + img/chaperone/centermarkr2.png + img/chaperone/centermarkr3.png + + + img/video/color.png + img/video/dimmer.png + + + img/rotation/autoturn.png + img/rotation/noautoturn.png + img/rotation/noautoturn.svg + + + img/alarm/alarm_activated.png + + diff --git a/src/settings/internal/settings_controller.h b/src/settings/internal/settings_controller.h index 5fb5dce8..e8efb81b 100644 --- a/src/settings/internal/settings_controller.h +++ b/src/settings/internal/settings_controller.h @@ -2,7 +2,8 @@ #include #include #include -#include +#include +#include #include "../settings.h" #include "setting_value.h" #include "../../utils/setup.h" @@ -64,12 +65,12 @@ void verifySettings( std::array v ) noexcept const auto enumSettingNumber = static_cast( currentSetting ); - LOG( ERROR ) << enumName << ": at index '" << settingIndex - << "' is incorrect. Current value: '" - << enumSettingNumber - << "'. Exiting " - "with error code " - << ReturnErrorCode::SETTING_INCORRECT_INDEX << "."; + qCritical() << enumName << ": at index '" << settingIndex + << "' is incorrect. Current value: '" + << enumSettingNumber + << "'. Exiting " + "with error code " + << ReturnErrorCode::SETTING_INCORRECT_INDEX << "."; exit( ReturnErrorCode::SETTING_INCORRECT_INDEX ); } } diff --git a/src/settings/internal/settings_internal.h b/src/settings/internal/settings_internal.h index 993d725b..10bb1d9e 100644 --- a/src/settings/internal/settings_internal.h +++ b/src/settings/internal/settings_internal.h @@ -84,7 +84,7 @@ void saveQtSetting( const SettingCategory category, getQSettings().endGroup(); } -template [[nodiscard]] bool isValidQVariant( const QVariant v ) +template [[nodiscard]] bool isValidQVariant( const QVariant v ) { auto savedSettingIsValid = v.isValid() && !v.isNull(); diff --git a/src/settings/internal/settings_object_data.h b/src/settings/internal/settings_object_data.h index 3cf663a0..727610ba 100644 --- a/src/settings/internal/settings_object_data.h +++ b/src/settings/internal/settings_object_data.h @@ -1,6 +1,5 @@ #pragma once #include -#include namespace settings { diff --git a/src/settings/settings.cpp b/src/settings/settings.cpp index 1eb12451..316d6e54 100644 --- a/src/settings/settings.cpp +++ b/src/settings/settings.cpp @@ -1,5 +1,6 @@ #include -#include +#include +#include #include "../overlaycontroller.h" #include "internal/settings_controller.h" @@ -14,9 +15,9 @@ void saveChangedSettings() void saveAllSettings() { - LOG( INFO ) << "Saving all settings."; + qInfo() << "Saving all settings."; settingController.saveAllSettings(); - LOG( INFO ) << "All settings saved."; + qInfo() << "All settings saved."; } [[nodiscard]] bool getSetting( const BoolSetting setting ) diff --git a/src/tabcontrollers/AudioTabController.cpp b/src/tabcontrollers/AudioTabController.cpp index 2344b86f..898f537a 100644 --- a/src/tabcontrollers/AudioTabController.cpp +++ b/src/tabcontrollers/AudioTabController.cpp @@ -1,10 +1,13 @@ #include "AudioTabController.h" #include #include +#include +#include #include "../overlaycontroller.h" #include "../settings/settings.h" #include "../settings/settings_object.h" #include "../utils/update_rate.h" +#include "openvr/ovr_overlay_wrapper.h" #ifdef _WIN32 # include "audiomanager/AudioManagerWindows.h" #elif __linux__ @@ -39,11 +42,11 @@ void AudioTabController::initStage1() &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not read \"" - << vr::k_pch_audio_PlaybackMirrorDevice_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not read \"" + << vr::k_pch_audio_PlaybackMirrorDevice_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -63,8 +66,9 @@ void AudioTabController::initStage1() eventLoopTick(); } -void AudioTabController::initStage2() +void AudioTabController::initStage2( OverlayController* var_parent ) { + this->parent = var_parent; const auto pushToTalkOverlayKey = std::string( application_strings::applicationKey ) + ".pptnotification"; @@ -75,43 +79,28 @@ void AudioTabController::initStage2() &m_pushToTalkValues.overlayHandle ); if ( overlayError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not create ptt notification overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not create ptt notification overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); emit defaultProfileDisplay(); return; } - constexpr auto pushToTalkIconFilepath - = "/res/img/audio/microphone/ptt_notification.png"; - constexpr auto pushToMuteIconFilepath - = "/res/img/audio/microphone/ptm_notification.png"; - - const auto pushToTalkIconFilePath - = paths::verifyIconFilePath( pushToTalkIconFilepath ); - const auto pushToMuteIconFilePath - = paths::verifyIconFilePath( pushToMuteIconFilepath ); - - if ( !pushToTalkIconFilePath.has_value() - || !pushToMuteIconFilePath.has_value() ) - { - emit defaultProfileDisplay(); - return; - } - - m_pushToTalkValues.pushToTalkPath = *pushToTalkIconFilePath; - m_pushToTalkValues.pushToMutePath = *pushToMuteIconFilePath; + m_pushToTalkValues.pushToTalkImg.reset( + new QImage( QString( ":/microphone/ptt_notification.png" ) ) ); + m_pushToTalkValues.pushToMuteImg.reset( + new QImage( QString( ":/microphone/ptm_notification.png" ) ) ); - auto pushToPath = m_pushToTalkValues.pushToTalkPath.c_str(); + auto* pushToImg = m_pushToTalkValues.pushToTalkImg.get(); if ( settings::getSetting( settings::BoolSetting::AUDIO_micReversePtt ) ) { - pushToPath = m_pushToTalkValues.pushToMutePath.c_str(); + pushToImg = m_pushToTalkValues.pushToMuteImg.get(); } - vr::VROverlay()->SetOverlayFromFile( m_pushToTalkValues.overlayHandle, - pushToPath ); + ovr_overlay_wrapper::setOverlayFromQImage( m_pushToTalkValues.overlayHandle, + *pushToImg ); vr::VROverlay()->SetOverlayWidthInMeters( m_pushToTalkValues.overlayHandle, 0.02f ); vr::HmdMatrix34_t notificationTransform @@ -196,11 +185,11 @@ void AudioTabController::eventLoopTick() &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not read \"" - << vr::k_pch_audio_PlaybackMirrorDevice_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not read \"" + << vr::k_pch_audio_PlaybackMirrorDevice_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } if ( lastMirrorDevId.compare( mirrorDeviceId ) != 0 ) { @@ -356,17 +345,15 @@ void AudioTabController::setMicReversePtt( bool value, bool notify ) settings::setSetting( settings::BoolSetting::AUDIO_micReversePtt, value ); + // TODO: if reenabled use `ovr_overlay_wrapper::setOverlayFromQImage` + // instead if ( value ) { - vr::VROverlay()->SetOverlayFromFile( - m_pushToTalkValues.overlayHandle, - m_pushToTalkValues.pushToMutePath.c_str() ); + // vr::VROverlay()->SetOverlayFromFile(m_ptt_overlayHandle,/*pt_mute*/); } else { - vr::VROverlay()->SetOverlayFromFile( - m_pushToTalkValues.overlayHandle, - m_pushToTalkValues.pushToTalkPath.c_str() ); + // vr::VROverlay()->SetOverlayFromFile(m_ptt_overlayHandle,/*pt_talk*/); } if ( pttEnabled() ) @@ -447,17 +434,17 @@ bool indexIsValid( const int index, { if ( index < 0 ) { - LOG( ERROR ) << functionName - << " called with index below zero: " << index; + qCritical() << functionName + << " called with index below zero: " << index; return false; } if ( static_cast( index ) >= devices.size() ) { - LOG( ERROR ) << functionName - << " called with index greater than size of " - "devices '" - << devices.size() << "', index '" << index << "'."; + qCritical() << functionName + << " called with index greater than size of " + "devices '" + << devices.size() << "', index '" << index << "'."; return false; } @@ -571,12 +558,11 @@ void AudioTabController::setMirrorDeviceIndex( int index, bool notify ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) - << "Could not remove \"" - << vr::k_pch_audio_PlaybackMirrorDevice_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not remove \"" + << vr::k_pch_audio_PlaybackMirrorDevice_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -596,12 +582,11 @@ void AudioTabController::setMirrorDeviceIndex( int index, bool notify ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) - << "Could not write \"" - << vr::k_pch_audio_PlaybackMirrorDevice_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not write \"" + << vr::k_pch_audio_PlaybackMirrorDevice_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -883,12 +868,11 @@ void AudioTabController::deleteAudioProfile( unsigned index ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) - << "Could not remove \"" - << vr::k_pch_audio_PlaybackDeviceOverrideName_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not remove \"" + << vr::k_pch_audio_PlaybackDeviceOverrideName_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } vr::VRSettings()->RemoveKeyInSection( @@ -897,12 +881,11 @@ void AudioTabController::deleteAudioProfile( unsigned index ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) - << "Could not remove \"" - << vr::k_pch_audio_RecordingDeviceOverrideName_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not remove \"" + << vr::k_pch_audio_RecordingDeviceOverrideName_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } } audioProfiles.erase( pos ); @@ -936,9 +919,9 @@ void AudioTabController::setPlaybackOverride( bool value, bool notify ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "Could not set playback override setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qCritical() << "Could not set playback override setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } if ( notify ) { @@ -959,9 +942,9 @@ void AudioTabController::setRecordingOverride( bool value, bool notify ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "Could not set recording override setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qCritical() << "Could not set recording override setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } if ( notify ) { @@ -979,10 +962,10 @@ void AudioTabController::initOverride() &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "Could not get recording override setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); - LOG( INFO ) << "Setting recording override to false"; + qCritical() << "Could not get recording override setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); + qInfo() << "Setting recording override to false"; setRecordingOverride( false ); } else @@ -995,10 +978,10 @@ void AudioTabController::initOverride() &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "Could not get playback override setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); - LOG( INFO ) << "Setting playback override to false"; + qCritical() << "Could not get playback override setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); + qInfo() << "Setting playback override to false"; setPlaybackOverride( false ); } else @@ -1091,11 +1074,11 @@ void AudioTabController::setDefaultPlayback( int index, bool notify ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not write \"" - << vr::k_pch_audio_PlaybackDeviceOverrideName_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not write \"" + << vr::k_pch_audio_PlaybackDeviceOverrideName_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -1114,11 +1097,11 @@ void AudioTabController::setDefaultMic( int index, bool notify ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not write \"" - << vr::k_pch_audio_RecordingDeviceOverrideName_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not write \"" + << vr::k_pch_audio_RecordingDeviceOverrideName_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -1138,11 +1121,11 @@ void AudioTabController::setDefaultMirror( int index, bool notify ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not remove \"" - << vr::k_pch_audio_PlaybackMirrorDevice_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not remove \"" + << vr::k_pch_audio_PlaybackMirrorDevice_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -1159,11 +1142,11 @@ void AudioTabController::setDefaultMirror( int index, bool notify ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not write \"" - << vr::k_pch_audio_PlaybackMirrorDevice_String - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not write \"" + << vr::k_pch_audio_PlaybackMirrorDevice_String + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -1258,7 +1241,7 @@ void AudioTabController::shutdown() { setMirrorDeviceIndex( -1 ); } - LOG( INFO ) << "Audio Tab Controller Has Shut Down"; + qInfo() << "Audio Tab Controller Has Shut Down"; } bool AudioTabController::pttEnabled() const diff --git a/src/tabcontrollers/AudioTabController.h b/src/tabcontrollers/AudioTabController.h index 7729a0f4..83a1e700 100644 --- a/src/tabcontrollers/AudioTabController.h +++ b/src/tabcontrollers/AudioTabController.h @@ -5,6 +5,7 @@ #include "audiomanager/AudioManager.h" #include +#include #include "../utils/FrameRateUtils.h" #include "../settings/settings_object.h" @@ -111,11 +112,12 @@ class AudioTabController : public QObject setPttShowNotification NOTIFY pttShowNotificationChanged ) private: + OverlayController* parent; struct { vr::VROverlayHandle_t overlayHandle = vr::k_ulOverlayHandleInvalid; - std::string pushToTalkPath; - std::string pushToMutePath; + std::unique_ptr pushToTalkImg; + std::unique_ptr pushToMuteImg; } m_pushToTalkValues; int m_playbackDeviceIndex = -1; @@ -178,7 +180,7 @@ class AudioTabController : public QObject public: void initStage1(); - void initStage2(); + void initStage2( OverlayController* var_parent ); void reloadAudioSettings(); diff --git a/src/tabcontrollers/ChaperoneTabController.cpp b/src/tabcontrollers/ChaperoneTabController.cpp index 4fc2fd3e..64f28416 100644 --- a/src/tabcontrollers/ChaperoneTabController.cpp +++ b/src/tabcontrollers/ChaperoneTabController.cpp @@ -1,5 +1,7 @@ #include "ChaperoneTabController.h" #include +#include +#include #include "../overlaycontroller.h" #include "../settings/settings.h" #include "../utils/Matrix.h" @@ -182,7 +184,7 @@ void ChaperoneTabController::handleChaperoneWarnings( float distance ) // Alarm Sound if ( isChaperoneAlarmSoundEnabled() ) { - // LOG(WARNING) << "In alarm"; + qWarning() << "In alarm"; float activationDistance = chaperoneAlarmSoundDistance(); if ( distance <= activationDistance && proxSensorOverrideState ) @@ -763,12 +765,12 @@ void ChaperoneTabController::setChaperoneColorR( int value, bool notify ) if ( value > 255 ) { value = 255; - LOG( WARNING ) << "Red Channel larger than 255, setting to 255"; + qWarning() << "Red Channel larger than 255, setting to 255"; } else if ( value < 0 ) { value = 0; - LOG( WARNING ) << "Red Channel smaller than 0, setting to 0"; + qWarning() << "Red Channel smaller than 0, setting to 0"; } m_chaperoneColorR = value; ovr_settings_wrapper::setInt32( @@ -791,12 +793,12 @@ void ChaperoneTabController::setChaperoneColorG( int value, bool notify ) if ( value > 255 ) { value = 255; - LOG( WARNING ) << "Green Channel larger than 255, setting to 255"; + qWarning() << "Green Channel larger than 255, setting to 255"; } else if ( value < 0 ) { value = 0; - LOG( WARNING ) << "Green Channel smaller than 0, setting to 0"; + qWarning() << "Green Channel smaller than 0, setting to 0"; } m_chaperoneColorG = value; ovr_settings_wrapper::setInt32( @@ -819,12 +821,12 @@ void ChaperoneTabController::setChaperoneColorB( int value, bool notify ) if ( value > 255 ) { value = 255; - LOG( WARNING ) << "Blue Channel larger than 255, setting to 255"; + qWarning() << "Blue Channel larger than 255, setting to 255"; } else if ( value < 0 ) { value = 0; - LOG( WARNING ) << "Blue Channel smaller than 0, setting to 0"; + qWarning() << "Blue Channel smaller than 0, setting to 0"; } m_chaperoneColorB = value; ovr_settings_wrapper::setInt32( @@ -855,12 +857,12 @@ void ChaperoneTabController::setChaperoneColorA( int value, bool notify ) if ( value > 255 ) { value = 255; - LOG( WARNING ) << "Alpha Channel larger than 255, setting to 255"; + qWarning() << "Alpha Channel larger than 255, setting to 255"; } else if ( value < 0 ) { value = 0; - LOG( WARNING ) << "Alpha Channel smaller than 0, setting to 0"; + qWarning() << "Alpha Channel smaller than 0, setting to 0"; } m_chaperoneColorA = value; ovr_settings_wrapper::setInt32( @@ -926,14 +928,13 @@ void ChaperoneTabController::setCollisionBoundStyle( int value, if ( vr::COLLISION_BOUNDS_STYLE_COUNT < value ) { value = 0; - LOG( WARNING ) + qWarning() << "Invalid Collision Bound Value (>count), set to beginner"; } else if ( value < 0 ) { value = 0; - LOG( WARNING ) - << "Invalid Collision Bound Value (<0), set to beginner"; + qWarning() << "Invalid Collision Bound Value (<0), set to beginner"; } if ( !isTemp ) { @@ -1468,7 +1469,7 @@ void ChaperoneTabController::createNewAutosaveProfile() } else { - LOG( INFO ) + qInfo() << "[Chaperone Autosave] «Autosaved Profile (previous)» not found"; } @@ -1484,7 +1485,7 @@ void ChaperoneTabController::createNewAutosaveProfile() } else { - LOG( INFO ) << "[Chaperone Autosave] «Autosaved Profile» not found"; + qInfo() << "[Chaperone Autosave] «Autosaved Profile» not found"; } // create a new autosave from current chaperone (all options set true) @@ -1515,8 +1516,8 @@ void ChaperoneTabController::applyAutosavedProfile() } else { - LOG( WARNING ) << "Failed to apply chaperone Autosaved Profile " - "(autosave doesn't exist)"; + qWarning() << "Failed to apply chaperone Autosaved Profile " + "(autosave doesn't exist)"; } } @@ -1618,8 +1619,22 @@ void ChaperoneTabController::initCenterMarkerOverlay() "" ); if ( overlayError == ovr_overlay_wrapper::OverlayError::NoError ) { - ovr_overlay_wrapper::setOverlayFromFile( - m_chaperoneFloorOverlayHandle, m_floorMarkerFN, "" ); + m_floorMarkers[-3] = std::unique_ptr( + new QImage( QString( ":/chaperone/centermarkl3.png" ) ) ); + m_floorMarkers[-2] = std::unique_ptr( + new QImage( QString( ":/chaperone/centermarkl2.png" ) ) ); + m_floorMarkers[-1] = std::unique_ptr( + new QImage( QString( ":/chaperone/centermarkl1.png" ) ) ); + m_floorMarkers[0] = std::unique_ptr( + new QImage( QString( ":/chaperone/centermark.png" ) ) ); + m_floorMarkers[1] = std::unique_ptr( + new QImage( QString( ":/chaperone/centermarkr1.png" ) ) ); + m_floorMarkers[2] = std::unique_ptr( + new QImage( QString( ":/chaperone/centermarkr2.png" ) ) ); + m_floorMarkers[3] = std::unique_ptr( + new QImage( QString( ":/chaperone/centermarkr3.png" ) ) ); + ovr_overlay_wrapper::setOverlayFromQImage( + m_chaperoneFloorOverlayHandle, *m_floorMarkers[0], "" ); ovr_overlay_wrapper::setOverlayWidthInMeters( m_chaperoneFloorOverlayHandle, 0.5f ); updateCenterMarkerOverlayColor(); @@ -1629,7 +1644,7 @@ void ChaperoneTabController::initCenterMarkerOverlay() } else { - LOG( ERROR ) << "overlay Not initialized"; + qCritical() << "overlay Not initialized"; // TODO Set Failure variable. } } @@ -1661,57 +1676,25 @@ void ChaperoneTabController::checkCenterMarkerOverlayRotationCount() if ( rotation > 0 ) { rotation = rotation + 0.5f; - int fullRotation = static_cast( rotation ); - switch ( fullRotation ) - { - case 0: - m_floorMarkerFN = "/res/img/chaperone/centermark.png"; - rotationNext = 0; - break; - case 1: - m_floorMarkerFN = "/res/img/chaperone/centermarkr1.png"; - rotationNext = 1; - break; - case 2: - m_floorMarkerFN = "/res/img/chaperone/centermarkr2.png"; - rotationNext = 2; - break; - - default: - - m_floorMarkerFN = "/res/img/chaperone/centermarkr3.png"; + rotationNext = static_cast( rotation ); + if ( rotationNext > 3 ) rotationNext = 3; - } } else { rotation = rotation + 0.5f; - int fullRotation = static_cast( std::floor( rotation ) ); - switch ( fullRotation ) - { - case 0: - m_floorMarkerFN = "/res/img/chaperone/centermark.png"; - rotationNext = 0; - break; - case -1: - m_floorMarkerFN = "/res/img/chaperone/centermarkl1.png"; - rotationNext = -1; - break; - case -2: - m_floorMarkerFN = "/res/img/chaperone/centermarkl2.png"; - rotationNext = -2; - break; - default: - m_floorMarkerFN = "/res/img/chaperone/centermarkl3.png"; + rotationNext = static_cast( std::floor( rotation ) ); + if ( rotationNext < -3 ) rotationNext = -3; - } } if ( rotationNext != m_rotationCurrent && m_centerMarkerOverlayIsInit ) { m_rotationCurrent = rotationNext; - ovr_overlay_wrapper::setOverlayFromFile( - m_chaperoneFloorOverlayHandle, m_floorMarkerFN, "" ); + ovr_overlay_wrapper::setOverlayFromQImage( + m_chaperoneFloorOverlayHandle, + *m_floorMarkers[rotationNext], + "" ); } } else diff --git a/src/tabcontrollers/ChaperoneTabController.h b/src/tabcontrollers/ChaperoneTabController.h index a28977e1..38b31763 100644 --- a/src/tabcontrollers/ChaperoneTabController.h +++ b/src/tabcontrollers/ChaperoneTabController.h @@ -2,6 +2,7 @@ #pragma once #include +#include #include #include #include @@ -379,7 +380,7 @@ class ChaperoneTabController : public QObject std::vector chaperoneProfiles; - std::string m_floorMarkerFN = "/res/img/chaperone/centermark.png"; + std::map> m_floorMarkers; void initCenterMarkerOverlay(); void updateCenterMarkerOverlayColor(); void checkCenterMarkerOverlayRotationCount(); diff --git a/src/tabcontrollers/FixFloorTabController.cpp b/src/tabcontrollers/FixFloorTabController.cpp index 80f1ecfb..7ea11dbe 100644 --- a/src/tabcontrollers/FixFloorTabController.cpp +++ b/src/tabcontrollers/FixFloorTabController.cpp @@ -1,5 +1,7 @@ #include "FixFloorTabController.h" #include +#include +#include #include "../overlaycontroller.h" // application namespace @@ -153,7 +155,7 @@ void FixFloorTabController::dashboardLoopTick( /* floorOffsetY = static_cast(tempOffsetY); - LOG(INFO) << "Offset For Knuckles up is: " << + qInfo() << "Offset For Knuckles up is: " << floorOffsetY; */ } @@ -183,7 +185,7 @@ void FixFloorTabController::dashboardLoopTick( /* floorOffsetY = static_cast(tempOffsetY); - LOG(INFO) << "Offset For Knuckles up is: " << + qInfo() << "Offset For Knuckles up is: " << floorOffsetY; */ } @@ -196,10 +198,9 @@ void FixFloorTabController::dashboardLoopTick( floorOffsetX = static_cast( tempOffsetX ); floorOffsetZ = static_cast( tempOffsetZ ); - LOG( INFO ) - << "Fix Floor and adjust space center: Floor Offset = [" - << floorOffsetX << ", " << floorOffsetY << ", " - << floorOffsetZ << "]"; + qInfo() << "Fix Floor and adjust space center: Floor Offset = [" + << floorOffsetX << ", " << floorOffsetY << ", " + << floorOffsetZ << "]"; float offset[3] = { 0, 0, 0 }; offset[1] = floorOffsetY; if ( state == 2 ) @@ -243,12 +244,12 @@ int FixFloorTabController::getControllerType( &error ); if ( error != vr::TrackedProp_Success ) { - LOG( ERROR ) << "Error With Controller Type: " - << vr::VRSystem()->GetPropErrorNameFromEnum( error ); + qCritical() << "Error With Controller Type: " + << vr::VRSystem()->GetPropErrorNameFromEnum( error ); } else if ( stringLength == 0 ) { - LOG( ERROR ) << "Device Index not valid"; + qCritical() << "Device Index not valid"; } else if ( strcmp( controllerTypeString, "knuckles" ) == 0 ) { @@ -308,8 +309,8 @@ void FixFloorTabController::undoFixFloorClicked() { float off[3] = { -floorOffsetX, -floorOffsetY, -floorOffsetZ }; parent->m_moveCenterTabController.addOffset( off ); - LOG( INFO ) << "Fix Floor: Undo Floor Offset = [" << -floorOffsetX << ", " - << -floorOffsetY << ", " << -floorOffsetZ << "]"; + qInfo() << "Fix Floor: Undo Floor Offset = [" << -floorOffsetX << ", " + << -floorOffsetY << ", " << -floorOffsetZ << "]"; floorOffsetY = 0.0f; statusMessage = "Undo ... OK"; statusMessageTimeout = 1.0; diff --git a/src/tabcontrollers/MoveCenterTabController.cpp b/src/tabcontrollers/MoveCenterTabController.cpp index 565edcaa..d38064c7 100644 --- a/src/tabcontrollers/MoveCenterTabController.cpp +++ b/src/tabcontrollers/MoveCenterTabController.cpp @@ -1,5 +1,7 @@ #include "MoveCenterTabController.h" #include +#include +#include #include "../overlaycontroller.h" #include "../quaternion/quaternion.h" #include "../settings/settings.h" @@ -116,10 +118,10 @@ void MoveCenterTabController::applyOffsetProfile( unsigned index ) emit offsetXChanged( m_offsetX ); emit offsetYChanged( m_offsetY ); emit offsetZChanged( m_offsetZ ); - LOG( INFO ) << "Applying Offset Profile:" << profile.profileName - << " X:" << m_offsetX << " Y:" << m_offsetY - << " Z:" << m_offsetZ << " Rotation:" - << ( static_cast( m_rotation ) / 100 ); + qInfo() << "Applying Offset Profile:" << profile.profileName + << " X:" << m_offsetX << " Y:" << m_offsetY + << " Z:" << m_offsetZ + << " Rotation:" << ( static_cast( m_rotation ) / 100 ); } } @@ -168,10 +170,10 @@ void MoveCenterTabController::outputLogPoses() vr::HmdMatrix34_t hmdStanding = devicePosesStanding[0].mDeviceToAbsoluteTracking; - LOG( INFO ) << ""; - LOG( INFO ) << " ____Begin Matrices Log Ouput__________"; - LOG( INFO ) << "|"; - LOG( INFO ) << "HMD POSE (standing universe)"; + qInfo() << ""; + qInfo() << " ____Begin Matrices Log Ouput__________"; + qInfo() << "|"; + qInfo() << "HMD POSE (standing universe)"; outputLogHmdMatrix( hmdStanding ); vr::TrackedDevicePose_t devicePosesSeated[vr::k_unMaxTrackedDeviceCount]; @@ -185,7 +187,7 @@ void MoveCenterTabController::outputLogPoses() vr::HmdMatrix34_t hmdSeated = devicePosesSeated[0].mDeviceToAbsoluteTracking; - LOG( INFO ) << "HMD POSE (seated universe)"; + qInfo() << "HMD POSE (seated universe)"; outputLogHmdMatrix( hmdSeated ); auto leftHand = vr::VRSystem()->GetTrackedDeviceIndexForControllerRole( @@ -198,70 +200,65 @@ void MoveCenterTabController::outputLogPoses() vr::HmdMatrix34_t rightHandMatrix = devicePosesStanding[rightHand].mDeviceToAbsoluteTracking; - LOG( INFO ) << "LEFT Hand Controller Pose (standing universe)"; + qInfo() << "LEFT Hand Controller Pose (standing universe)"; outputLogHmdMatrix( leftHandMatrix ); - LOG( INFO ) << "RIGHT Hand Controller Pose (standing universe)"; + qInfo() << "RIGHT Hand Controller Pose (standing universe)"; outputLogHmdMatrix( rightHandMatrix ); vr::HmdMatrix34_t standingZero; vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose( &standingZero ); - LOG( INFO ) << "GetWorkingStandingZeroPoseToRawTrackingPose"; + qInfo() << "GetWorkingStandingZeroPoseToRawTrackingPose"; outputLogHmdMatrix( standingZero ); vr::HmdMatrix34_t seatedZero; vr::VRChaperoneSetup()->GetWorkingSeatedZeroPoseToRawTrackingPose( &seatedZero ); - LOG( INFO ) << "GetWorkingSeatedZeroPoseToRawTrackingPose"; + qInfo() << "GetWorkingSeatedZeroPoseToRawTrackingPose"; outputLogHmdMatrix( seatedZero ); vr::HmdMatrix34_t seatedZeroLive; vr::VRChaperoneSetup()->GetLiveSeatedZeroPoseToRawTrackingPose( &seatedZeroLive ); - LOG( INFO ) << "GetLiveSeatedZeroPoseToRawTrackingPose"; + qInfo() << "GetLiveSeatedZeroPoseToRawTrackingPose"; outputLogHmdMatrix( seatedZeroLive ); vr::HmdMatrix34_t seatedToStandingAbsolute = vr::VRSystem()->GetSeatedZeroPoseToStandingAbsoluteTrackingPose(); - LOG( INFO ) << "GetSeatedZeroPoseToStandingAbsoluteTrackingPose"; + qInfo() << "GetSeatedZeroPoseToStandingAbsoluteTrackingPose"; outputLogHmdMatrix( seatedToStandingAbsolute ); - LOG( INFO ) << "m_universeCenterForReset"; + qInfo() << "m_universeCenterForReset"; outputLogHmdMatrix( m_universeCenterForReset ); - LOG( INFO ) << "m_seatedCenterForReset"; + qInfo() << "m_seatedCenterForReset"; outputLogHmdMatrix( m_seatedCenterForReset ); - LOG( INFO ) << "|____End Matrices Log Ouput____________"; - LOG( INFO ) << ""; + qInfo() << "|____End Matrices Log Ouput____________"; + qInfo() << ""; } void MoveCenterTabController::outputLogHmdMatrix( vr::HmdMatrix34_t hmdMatrix ) { - LOG( INFO ) << hmdMatrix.m[0][0] << "\t\t\t" << hmdMatrix.m[0][1] - << "\t\t\t" << hmdMatrix.m[0][2] << "\t\t\t" - << hmdMatrix.m[0][3]; - LOG( INFO ) << hmdMatrix.m[1][0] << "\t\t\t" << hmdMatrix.m[1][1] - << "\t\t\t" << hmdMatrix.m[1][2] << "\t\t\t" - << hmdMatrix.m[1][3]; - LOG( INFO ) << hmdMatrix.m[2][0] << "\t\t\t" << hmdMatrix.m[2][1] - << "\t\t\t" << hmdMatrix.m[2][2] << "\t\t\t" - << hmdMatrix.m[2][3]; + qInfo() << hmdMatrix.m[0][0] << "\t\t\t" << hmdMatrix.m[0][1] << "\t\t\t" + << hmdMatrix.m[0][2] << "\t\t\t" << hmdMatrix.m[0][3]; + qInfo() << hmdMatrix.m[1][0] << "\t\t\t" << hmdMatrix.m[1][1] << "\t\t\t" + << hmdMatrix.m[1][2] << "\t\t\t" << hmdMatrix.m[1][3]; + qInfo() << hmdMatrix.m[2][0] << "\t\t\t" << hmdMatrix.m[2][1] << "\t\t\t" + << hmdMatrix.m[2][2] << "\t\t\t" << hmdMatrix.m[2][3]; float atan2Yaw = std::atan2( hmdMatrix.m[0][2], hmdMatrix.m[2][2] ); - LOG( INFO ) << "atan2 Yaw Calculation: " << atan2Yaw << "radians " - << ( ( static_cast( atan2Yaw ) - * k_radiansToCentidegrees ) - / 100 ) - << "degrees"; + qInfo() << "atan2 Yaw Calculation: " << atan2Yaw << "radians " + << ( ( static_cast( atan2Yaw ) * k_radiansToCentidegrees ) + / 100 ) + << "degrees"; vr::HmdQuaternion_t hmdQuat = quaternion::fromHmdMatrix34( hmdMatrix ); double hmdQuatYaw = quaternion::getYaw( hmdQuat ); - LOG( INFO ) << "Quaternion Yaw Calculation: " << hmdQuatYaw << "radians " - << ( ( hmdQuatYaw * k_radiansToCentidegrees ) / 100 ) - << "degrees"; - LOG( INFO ) << ""; + qInfo() << "Quaternion Yaw Calculation: " << hmdQuatYaw << "radians " + << ( ( hmdQuatYaw * k_radiansToCentidegrees ) / 100 ) << "degrees"; + qInfo() << ""; } int MoveCenterTabController::trackingUniverse() const @@ -283,7 +280,7 @@ void MoveCenterTabController::setTrackingUniverse( int value, bool notify ) if ( notify ) { emit trackingUniverseChanged( m_trackingUniverse ); - LOG( INFO ) << "Tracking Universe: " << m_trackingUniverse; + qInfo() << "Tracking Universe: " << m_trackingUniverse; } } } @@ -914,19 +911,19 @@ void MoveCenterTabController::incomingZeroReset() // aspects) IN mixed tracking environments I get this issue, the check if // there is an error and apply autosaved profile is hopefully a workaround auto calState = vr::VRChaperone()->GetCalibrationState(); - LOG( INFO ) << "Calibration State on Zero Reset is: " << calState; + qInfo() << "Calibration State on Zero Reset is: " << calState; // If we detect a seated Recenter and are not currently in process // we reload chaperone from disk if ( m_recenterStages < 1 ) { - LOG( INFO ) << "Re-Center Stage 1, reload from disk"; + qInfo() << "Re-Center Stage 1, reload from disk"; m_recenterStages++; if ( calState > 199 && m_initComplete ) { - LOG( INFO ) << "Chaperone calibration state is error, attempting " - "to apply autosaved profile to fix issue"; + qInfo() << "Chaperone calibration state is error, attempting " + "to apply autosaved profile to fix issue"; parent->m_chaperoneTabController.applyAutosavedProfile(); } @@ -940,7 +937,7 @@ void MoveCenterTabController::incomingZeroReset() // and reseting our stage counter if ( m_recenterStages == 1 ) { - LOG( INFO ) << "Recenter Stage 2 re-set zero pos, and reset offsets"; + qInfo() << "Recenter Stage 2 re-set zero pos, and reset offsets"; vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose( &m_universeCenterForReset ); vr::VRChaperoneSetup()->GetWorkingSeatedZeroPoseToRawTrackingPose( @@ -956,12 +953,12 @@ void MoveCenterTabController::reset() // DO NOT attempt to apply autosaved profile on reset, as it is triggered by // the apply chaperone profile Side effects are bad! auto calState = vr::VRChaperone()->GetCalibrationState(); - LOG( INFO ) << "Calibration State on Reset is: " << calState; + qInfo() << "Calibration State on Reset is: " << calState; if ( !m_chaperoneBasisAcquired ) { - LOG( WARNING ) << "WARNING: Attempted reset offsets before chaperone " - "basis is acquired!"; + qWarning() << "WARNING: Attempted reset offsets before chaperone " + "basis is acquired!"; return; } m_heightToggle = false; @@ -1035,65 +1032,62 @@ void MoveCenterTabController::zeroOffsets() - ( m_rotation * k_centidegreesToRadians ) ); if ( abs( currentCenterXyz[0] ) > k_maxOpenvrCommitOffset ) { - LOG( INFO ) << "Attempted Zero Offsets out of commit bounds ( X: " - << currentCenterXyz[0] << " )"; - LOG( INFO ) << "GetWorkingStandingZeroPoseToRawTrackingPose"; + qInfo() << "Attempted Zero Offsets out of commit bounds ( X: " + << currentCenterXyz[0] << " )"; + qInfo() << "GetWorkingStandingZeroPoseToRawTrackingPose"; outputLogHmdMatrix( currentCenter ); // if reset happens before init is complete we set the universe // center to the raw tracking zero point reset(); if ( !m_chaperoneBasisAcquired ) { - LOG( WARNING ) - << "<[!]><[!]>EXECUTED RESET BEFORE BASIS " - "ACQUIRED<[!]><[!]> " - "Setting universe center to raw tracking zero point."; + qWarning() << "<[!]><[!]>EXECUTED RESET BEFORE BASIS " + "ACQUIRED<[!]><[!]> " + "Setting universe center to raw tracking zero point."; } else { - LOG( INFO ) << "-Resetting offsets-"; + qInfo() << "-Resetting offsets-"; } } else if ( abs( currentCenterXyz[1] ) > k_maxOpenvrCommitOffset ) { - LOG( INFO ) << "Attempted Zero Offsets out of commit bounds ( Y: " - << currentCenterXyz[1] << " )"; - LOG( INFO ) << "GetWorkingStandingZeroPoseToRawTrackingPose"; + qInfo() << "Attempted Zero Offsets out of commit bounds ( Y: " + << currentCenterXyz[1] << " )"; + qInfo() << "GetWorkingStandingZeroPoseToRawTrackingPose"; outputLogHmdMatrix( currentCenter ); // if reset happens before init is complete we set the universe // center to the raw tracking zero point reset(); if ( !m_chaperoneBasisAcquired ) { - LOG( WARNING ) - << "<[!]><[!]>EXECUTED RESET BEFORE BASIS " - "ACQUIRED<[!]><[!]> " - "Setting universe center to raw tracking zero point."; + qWarning() << "<[!]><[!]>EXECUTED RESET BEFORE BASIS " + "ACQUIRED<[!]><[!]> " + "Setting universe center to raw tracking zero point."; } else { - LOG( INFO ) << "-Resetting offsets-"; + qInfo() << "-Resetting offsets-"; } } else if ( abs( currentCenterXyz[2] ) > k_maxOpenvrCommitOffset ) { - LOG( INFO ) << "Attempted Zero Offsets out of commit bounds ( Z: " - << currentCenterXyz[2] << " )"; - LOG( INFO ) << "GetWorkingStandingZeroPoseToRawTrackingPose"; + qInfo() << "Attempted Zero Offsets out of commit bounds ( Z: " + << currentCenterXyz[2] << " )"; + qInfo() << "GetWorkingStandingZeroPoseToRawTrackingPose"; outputLogHmdMatrix( currentCenter ); // if reset happens before init is complete we set the universe // center to the raw tracking zero point reset(); if ( !m_chaperoneBasisAcquired ) { - LOG( WARNING ) - << "<[!]><[!]>EXECUTED RESET BEFORE BASIS " - "ACQUIRED<[!]><[!]> " - "Setting universe center to raw tracking zero point."; + qWarning() << "<[!]><[!]>EXECUTED RESET BEFORE BASIS " + "ACQUIRED<[!]><[!]> " + "Setting universe center to raw tracking zero point."; } else { - LOG( INFO ) << "-Resetting offsets-"; + qInfo() << "-Resetting offsets-"; } } m_oldOffsetX = 0.0f; @@ -1121,7 +1115,7 @@ void MoveCenterTabController::zeroOffsets() auto calState = vr::VRChaperone()->GetCalibrationState(); if ( calState == 200 ) { - LOG( WARNING ) + qWarning() << "Chaperone State Does Not Exist Yet, will wait for " "universe change to finish initialization"; } @@ -1135,13 +1129,13 @@ void MoveCenterTabController::zeroOffsets() else { // shutdown was unsafe last session! - LOG( WARNING ) << "DETECTED UNSAFE SHUTDOWN FROM LAST SESSION"; + qWarning() << "DETECTED UNSAFE SHUTDOWN FROM LAST SESSION"; m_initComplete = false; if ( !parent->crashRecoveryDisabled() ) { parent->m_chaperoneTabController.applyAutosavedProfile(); - LOG( INFO ) << "Applying last good chaperone " - "profile autosave"; + qInfo() << "Applying last good chaperone " + "profile autosave"; } } // Now mark previous shutdown as unsafe in case we crash @@ -1154,11 +1148,11 @@ void MoveCenterTabController::zeroOffsets() } if ( m_roomSetupModeDetected ) { - LOG( INFO ) << "room setup EXIT detected"; + qInfo() << "room setup EXIT detected"; m_roomSetupModeDetected = false; } - LOG( INFO ) << "SUCCESS: Chaperone Data Updated and Offsets zeroed out"; + qInfo() << "SUCCESS: Chaperone Data Updated and Offsets zeroed out"; } void MoveCenterTabController::sendSeatedRecenter() @@ -1196,8 +1190,8 @@ void MoveCenterTabController::updateChaperoneResetData() auto cstate = vr::VRChaperone()->GetCalibrationState(); if ( cstate > 199 ) { - LOG( WARNING ) << "Chaperone Calibration State is error: " << cstate - << " While Trying to Update Reset Data"; + qWarning() << "Chaperone Calibration State is error: " << cstate + << " While Trying to Update Reset Data"; } else { @@ -1905,11 +1899,11 @@ void MoveCenterTabController::resetOffsets( bool resetOffsetsJustPressed ) emit rotationChanged( m_rotation ); updateSpace( true ); auto calState = vr::VRChaperone()->GetCalibrationState(); - LOG( INFO ) << "Calibration State on Reset Offsets is: " << calState; + qInfo() << "Calibration State on Reset Offsets is: " << calState; // if ( calState > 199 && m_initComplete ) // { - // LOG( INFO ) << "Chaperone calibration state is error, + // qInfo() << "Chaperone calibration state is error, // attempting " // "to apply autosaved profile to fix issue"; // parent->m_chaperoneTabController.applyAutosavedProfile(); @@ -2139,8 +2133,8 @@ void MoveCenterTabController::updateHmdRotationCounter( } else { - LOG( WARNING ) << "HMD Was Inverted during a Turn Count, Turn " - "counter may be in-accurate"; + qWarning() << "HMD Was Inverted during a Turn Count, Turn " + "counter may be in-accurate"; } } @@ -2586,16 +2580,16 @@ void MoveCenterTabController::updateSpace( bool forceUpdate ) > k_maxOvrasUniverseCenteredTurningOffset && universeCenteredRotation() ) ) { - LOG( INFO ) << "Raw universe center out of bounds ( X: " - << offsetUniverseCenterXyz[0] << " )"; + qInfo() << "Raw universe center out of bounds ( X: " + << offsetUniverseCenterXyz[0] << " )"; vr::HmdMatrix34_t standingZero; vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose( &standingZero ); - LOG( INFO ) << "GetWorkingStandingZeroPoseToRawTrackingPose"; + qInfo() << "GetWorkingStandingZeroPoseToRawTrackingPose"; outputLogHmdMatrix( standingZero ); reset(); parent->m_chaperoneTabController.applyAutosavedProfile(); - LOG( INFO ) << "-Resetting to autosaved chaperone profile-"; + qInfo() << "-Resetting to autosaved chaperone profile-"; return; } if ( abs( offsetUniverseCenterXyz[1] ) > k_maxOpenvrWorkingSetOffest @@ -2603,16 +2597,16 @@ void MoveCenterTabController::updateSpace( bool forceUpdate ) > k_maxOvrasUniverseCenteredTurningOffset && universeCenteredRotation() ) ) { - LOG( INFO ) << "Raw universe center out of bounds ( Y: " - << offsetUniverseCenterXyz[1] << " )"; + qInfo() << "Raw universe center out of bounds ( Y: " + << offsetUniverseCenterXyz[1] << " )"; vr::HmdMatrix34_t standingZero; vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose( &standingZero ); - LOG( INFO ) << "GetWorkingStandingZeroPoseToRawTrackingPose"; + qInfo() << "GetWorkingStandingZeroPoseToRawTrackingPose"; outputLogHmdMatrix( standingZero ); reset(); parent->m_chaperoneTabController.applyAutosavedProfile(); - LOG( INFO ) << "-Resetting to autosaved chaperone profile-"; + qInfo() << "-Resetting to autosaved chaperone profile-"; return; } if ( abs( offsetUniverseCenterXyz[2] ) > k_maxOpenvrWorkingSetOffest @@ -2620,16 +2614,16 @@ void MoveCenterTabController::updateSpace( bool forceUpdate ) > k_maxOvrasUniverseCenteredTurningOffset && universeCenteredRotation() ) ) { - LOG( INFO ) << "Raw universe center out of bounds ( Z: " - << offsetUniverseCenterXyz[2] << " )"; + qInfo() << "Raw universe center out of bounds ( Z: " + << offsetUniverseCenterXyz[2] << " )"; vr::HmdMatrix34_t standingZero; vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose( &standingZero ); - LOG( INFO ) << "GetWorkingStandingZeroPoseToRawTrackingPose"; + qInfo() << "GetWorkingStandingZeroPoseToRawTrackingPose"; outputLogHmdMatrix( standingZero ); reset(); parent->m_chaperoneTabController.applyAutosavedProfile(); - LOG( INFO ) << "-Resetting to autosaved chaperone profile-"; + qInfo() << "-Resetting to autosaved chaperone profile-"; return; } @@ -2751,7 +2745,7 @@ void MoveCenterTabController::eventLoopTick( // the middle of room setup. m_pendingZeroOffsets = false; - LOG( INFO ) << "room setup ENTRY detected"; + qInfo() << "room setup ENTRY detected"; vr::VRChaperoneSetup()->HideWorkingSetPreview(); reset(); vr::VRChaperoneSetup()->RevertWorkingCopy(); @@ -2765,7 +2759,7 @@ void MoveCenterTabController::eventLoopTick( if ( universe == vr::TrackingUniverseSeated && !m_seatedModeDetected ) { m_seatedModeDetected = true; - LOG( INFO ) << "seated mode ENTRY detected"; + qInfo() << "seated mode ENTRY detected"; } // detect exiting seated mode @@ -2773,7 +2767,7 @@ void MoveCenterTabController::eventLoopTick( { m_seatedModeDetected = false; reset(); - LOG( INFO ) << "seated mode EXIT detected"; + qInfo() << "seated mode EXIT detected"; } // If we're trying to redifine the origin point, but can't becaues of diff --git a/src/tabcontrollers/RotationTabController.cpp b/src/tabcontrollers/RotationTabController.cpp index 07301f9f..8e31aa5c 100644 --- a/src/tabcontrollers/RotationTabController.cpp +++ b/src/tabcontrollers/RotationTabController.cpp @@ -1,5 +1,7 @@ #include "RotationTabController.h" #include +#include +#include #include "../overlaycontroller.h" #include "../settings/settings.h" #include "../utils/Matrix.h" @@ -17,6 +19,8 @@ void RotationTabController::initStage1() void RotationTabController::initStage2( OverlayController* var_parent ) { + this->parent = var_parent; + const auto autoturnOverlayKey = std::string( application_strings::applicationKey ) + ".autoturnnotification"; @@ -27,37 +31,22 @@ void RotationTabController::initStage2( OverlayController* var_parent ) &m_autoturnValues.overlayHandle ); if ( overlayError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not create autoturn notification overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not create autoturn notification overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); emit defaultProfileDisplay(); return; } + m_autoturnValues.autoturnImg.reset( + new QImage( QString( ":/rotation/autoturn.png" ) ) ); + m_autoturnValues.noautoturnImg.reset( + new QImage( QString( ":/rotation/noautoturn.png" ) ) ); - constexpr auto autoturnIconFilepath = "/res/img/rotation/autoturn.png"; - constexpr auto noautoturnIconFilepath = "/res/img/rotation/noautoturn.png"; - - const auto autoturnIconFilePath - = paths::verifyIconFilePath( autoturnIconFilepath ); - const auto noautoturnIconFilePath - = paths::verifyIconFilePath( noautoturnIconFilepath ); - - if ( !autoturnIconFilePath.has_value() - || !noautoturnIconFilePath.has_value() ) - { - emit defaultProfileDisplay(); - return; - } - - m_autoturnValues.autoturnPath = *autoturnIconFilePath; - m_autoturnValues.noautoturnPath = *noautoturnIconFilePath; + ovr_overlay_wrapper::setOverlayFromQImage( m_autoturnValues.overlayHandle, + *m_autoturnValues.autoturnImg ); - auto pushToPath = m_autoturnValues.autoturnPath.c_str(); - - vr::VROverlay()->SetOverlayFromFile( m_autoturnValues.overlayHandle, - pushToPath ); vr::VROverlay()->SetOverlayWidthInMeters( m_autoturnValues.overlayHandle, 0.02f ); vr::HmdMatrix34_t notificationTransform @@ -70,8 +59,6 @@ void RotationTabController::initStage2( OverlayController* var_parent ) ¬ificationTransform ); emit defaultProfileDisplay(); - - this->parent = var_parent; } void RotationTabController::eventLoopTick( @@ -401,9 +388,9 @@ void RotationTabController::doAutoTurn( // Ignore if the wall we encountered is behind us if ( std::abs( hmdToWallYaw ) >= M_PI / 2 ) { - LOG( DEBUG ) << "Ignoring turn in opposite " - "direction (angle " - << std::abs( hmdToWallYaw ) << ")"; + qDebug() << "Ignoring turn in opposite " + "direction (angle " + << std::abs( hmdToWallYaw ) << ")"; break; } @@ -426,7 +413,7 @@ void RotationTabController::doAutoTurn( // previous wall than the left. turnLeft = m_autoTurnWallActive[circularIndex( i, false, chaperoneDistances.size() )]; - LOG( DEBUG ) << "turning away from shared corner"; + qDebug() << "turning away from shared corner"; } // If within m_cordDetanglingAngle degrees of // 'straight at a wall', start in whatever direction @@ -440,19 +427,19 @@ void RotationTabController::doAutoTurn( turnLeft = ( parent->m_moveCenterTabController .getHmdYawTotal() < 0.0 ); - LOG( DEBUG ) << "turning to detangle cord"; + qDebug() << "turning to detangle cord"; } // Turn the closest angle to the wall else { turnLeft = hmdToWallYaw > 0.0; - LOG( DEBUG ) << "turning closest angle to wall"; + qDebug() << "turning closest angle to wall"; } - LOG( DEBUG ) << "hmd yaw " << hmdYaw - << ", hmd position to wall angle " - << hmdPositionToWallYaw; - LOG( DEBUG ) << "hmd to wall angle " << hmdToWallYaw; + qDebug() << "hmd yaw " << hmdYaw + << ", hmd position to wall angle " + << hmdPositionToWallYaw; + qDebug() << "hmd to wall angle " << hmdToWallYaw; // Positive hmd-to-wall is facing left, negative is // facing right (relative to the wall) double delta_degrees @@ -488,17 +475,17 @@ void RotationTabController::doAutoTurn( = static_cast( std::atan2( middleCorner.v[0] - touchingWallCorner.v[0], middleCorner.v[2] - touchingWallCorner.v[2] ) ); - LOG( DEBUG ) << "twa: " << touchingWallAngle - << ", nwa: " << newWallAngle << ", diff: " - << ( newWallAngle - touchingWallAngle ); + qDebug() << "twa: " << touchingWallAngle + << ", nwa: " << newWallAngle << ", diff: " + << ( newWallAngle - touchingWallAngle ); delta_degrees = ( newWallAngle - touchingWallAngle + ( turnLeft ? M_PI : -M_PI ) ) * k_radiansToCentidegrees; delta_degrees = reduceAngle<>( delta_degrees, -18000.0, 18000.0 ); } - LOG( DEBUG ) << "rotating space " << ( delta_degrees / 100 ) - << " degrees"; + qDebug() << "rotating space " << ( delta_degrees / 100 ) + << " degrees"; switch ( RotationTabController::autoTurnModeType() ) { case AutoTurnModes::SNAP: @@ -675,22 +662,21 @@ void RotationTabController::setAutoTurnEnabled( bool value, bool notify ) emit autoTurnEnabledChanged( value ); } - if ( !value ) - { - vr::VROverlay()->SetOverlayFromFile( - m_autoturnValues.overlayHandle, - m_autoturnValues.noautoturnPath.c_str() ); - } - else - { - vr::VROverlay()->SetOverlayFromFile( - m_autoturnValues.overlayHandle, - m_autoturnValues.autoturnPath.c_str() ); - } - if ( autoTurnShowNotification() && getNotificationOverlayHandle() != vr::k_ulOverlayHandleInvalid ) { + if ( !value ) + { + ovr_overlay_wrapper::setOverlayFromQImage( + m_autoturnValues.overlayHandle, + *m_autoturnValues.noautoturnImg ); + } + else + { + ovr_overlay_wrapper::setOverlayFromQImage( + m_autoturnValues.overlayHandle, *m_autoturnValues.autoturnImg ); + } + vr::VROverlay()->SetOverlayAlpha( getNotificationOverlayHandle(), 1.0f ); vr::VROverlay()->ShowOverlay( getNotificationOverlayHandle() ); diff --git a/src/tabcontrollers/RotationTabController.h b/src/tabcontrollers/RotationTabController.h index de8253a5..ca20fe31 100644 --- a/src/tabcontrollers/RotationTabController.h +++ b/src/tabcontrollers/RotationTabController.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -99,8 +100,8 @@ class RotationTabController : public QObject struct { vr::VROverlayHandle_t overlayHandle = vr::k_ulOverlayHandleInvalid; - std::string autoturnPath; - std::string noautoturnPath; + std::unique_ptr autoturnImg; + std::unique_ptr noautoturnImg; } m_autoturnValues; virtual vr::VROverlayHandle_t getNotificationOverlayHandle() diff --git a/src/tabcontrollers/SettingsTabController.cpp b/src/tabcontrollers/SettingsTabController.cpp index 98645139..699b04d0 100644 --- a/src/tabcontrollers/SettingsTabController.cpp +++ b/src/tabcontrollers/SettingsTabController.cpp @@ -1,5 +1,7 @@ #include "SettingsTabController.h" #include +#include +#include #include "../overlaycontroller.h" #include "../utils/update_rate.h" @@ -105,9 +107,9 @@ void SettingsTabController::setAutoStartEnabled( bool value, bool notify ) application_strings::applicationKey, m_autoStartEnabled ); if ( apperror != vr::VRApplicationError_None ) { - LOG( ERROR ) << "Could not set auto start: " - << vr::VRApplications() - ->GetApplicationsErrorNameFromEnum( apperror ); + qCritical() << "Could not set auto start: " + << vr::VRApplications() + ->GetApplicationsErrorNameFromEnum( apperror ); } if ( notify ) { diff --git a/src/tabcontrollers/SteamVRTabController.cpp b/src/tabcontrollers/SteamVRTabController.cpp index 05de1be3..2bbf87b1 100644 --- a/src/tabcontrollers/SteamVRTabController.cpp +++ b/src/tabcontrollers/SteamVRTabController.cpp @@ -1,5 +1,7 @@ #include "SteamVRTabController.h" #include +#include +#include #include "../overlaycontroller.h" #include "../utils/update_rate.h" #include @@ -504,7 +506,7 @@ void SteamVRTabController::launchBindingUI() &inputHandle ); if ( error2 != vr::VRInputError_None ) { - LOG( ERROR ) + qCritical() << "failed to get input handle? is your right controller on?"; } if ( parent->isDesktopMode() ) @@ -517,7 +519,7 @@ void SteamVRTabController::launchBindingUI() application_strings::applicationKey, actionHandle, inputHandle, false ); if ( error != vr::VRInputError_None ) { - LOG( ERROR ) << "Input Error: " << error; + qCritical() << "Input Error: " << error; } } void SteamVRTabController::restartSteamVR() @@ -525,7 +527,7 @@ void SteamVRTabController::restartSteamVR() QString cmd = QString( "cmd.exe /C restartvrserver.bat \"" ) + parent->getVRRuntimePathUrl().toLocalFile() + QString( "\"" ); - LOG( INFO ) << "SteamVR Restart Command: " << cmd; + qInfo() << "SteamVR Restart Command: " << cmd; QProcess::startDetached( cmd ); } @@ -561,8 +563,8 @@ Q_INVOKABLE void SteamVRTabController::pairDevice( QString sn ) { if ( !isSteamVRTracked( sn ) ) { - LOG( WARNING ) << sn.toStdString() - << " Is Not a SteamVR Dongle, skipping Pair"; + qWarning() << sn.toStdString() + << " Is Not a SteamVR Dongle, skipping Pair"; return; } m_last_pair_sn = sn; @@ -603,26 +605,26 @@ void SteamVRTabController::onConnected() emit pairStatusChanged( QString( "Pairing..." ) ); if ( m_last_pair_sn == "" ) { - LOG( ERROR ) << "No Last SN to pair, this shouldn't happen"; + qCritical() << "No Last SN to pair, this shouldn't happen"; } m_webSocket.sendTextMessage( messageout ); // m_webSocket.close(); } void SteamVRTabController::onDisconnect() { - LOG( INFO ) << "Pair WS disconnect"; + qInfo() << "Pair WS disconnect"; m_webSocket.close(); } void SteamVRTabController::onMsgRec( QString Msg ) { if ( Msg.contains( "success" ) ) { - LOG( INFO ) << "Pair Success"; + qInfo() << "Pair Success"; emit pairStatusChanged( QString( "Success" ) ); } if ( Msg.contains( "timeout" ) ) { - LOG( INFO ) << "Pair Timeout"; + qInfo() << "Pair Timeout"; emit pairStatusChanged( QString( "Timeout" ) ); } m_webSocket.close(); @@ -691,15 +693,15 @@ void SteamVRTabController::onGetBindingUrlResponse( QNetworkReply* reply ) std::string controllerName = ovr_system_wrapper::getControllerName(); if ( controllerName == "" ) { - LOG( WARNING ) << "No Controller Detected Skipping Bindings"; + qWarning() << "No Controller Detected Skipping Bindings"; return; } json jsonfull = json::parse( data.toStdString() ); - // LOG( INFO ) << "URL RESPOSNE XXXXXXX"; - // LOG( INFO ) << jsonfull.dump().c_str(); + // qInfo () << "URL RESPOSNE XXXXXXX"; + // qInfo () << jsonfull.dump().c_str(); std::string filepath = jsonfull["current_binding_url"][controllerName].get(); - LOG( INFO ) << "binding url at " << filepath; + qInfo() << "binding url at " << filepath; // TODO perhaps some form of error checking if packet wrong? reply->close(); getBindingDataReq( filepath, m_lastAppID, controllerName ); @@ -738,24 +740,24 @@ void SteamVRTabController::onGetBindingDataResponse( QNetworkReply* reply ) { return; } - // LOG( WARNING ) << "DATA RESPONSE"; - // LOG( WARNING ) << data.toStdString(); + // qWarning () << "DATA RESPONSE"; + // qWarning () << data.toStdString(); json jsonfull = json::parse( data.toStdString() ); if ( !jsonfull.contains( "success" ) ) { - LOG( ERROR ) << "Binding Data Packet Mal-Formed?"; + qCritical() << "Binding Data Packet Mal-Formed?"; } if ( !jsonfull["success"].get() ) { // TODO better error handling? - LOG( ERROR ) << "Binding Data Request Failed"; + qCritical() << "Binding Data Request Failed"; } reply->close(); output = jsonfull["binding_config"]; std::string sceneAppID = ovr_application_wrapper::getSceneAppID(); if ( sceneAppID == "error" ) { - LOG( ERROR ) << "aborting bind save, could not find scene app ID"; + qCritical() << "aborting bind save, could not find scene app ID"; return; } std::string ctrl = ovr_system_wrapper::getControllerName(); @@ -795,11 +797,11 @@ bool SteamVRTabController::saveBind( std::string appID, bindFile.close(); if ( bindFile.exists() ) { - LOG( INFO ) << ( def ? "Default " : ( sceneAppID + " " ) ) - + "Binding File saved at:" - << absPath.toStdString(); + qInfo() << ( def ? "Default " : ( sceneAppID + " " ) ) + + "Binding File saved at:" + << absPath.toStdString(); std::string jsonstring = binds.dump().c_str(); - LOG( INFO ) << jsonstring; + qInfo() << jsonstring; return true; } return false; @@ -861,7 +863,7 @@ void SteamVRTabController::applyBindingReq( std::string appID ) std::string sceneAppID = ovr_application_wrapper::getSceneAppID(); if ( sceneAppID == "" ) { - LOG( ERROR ) << "NO Scene App Detected unable to apply bindings"; + qCritical() << "NO Scene App Detected unable to apply bindings"; return; } @@ -870,14 +872,14 @@ void SteamVRTabController::applyBindingReq( std::string appID ) + ctrlType + ".json" ); if ( !QFileInfo::exists( fi.absolutePath() + QString( "/" ) + Fn ) ) { - LOG( INFO ) << "No Specific Binding Detected for: " + appID - + "for Scene: " + sceneAppID + " Checking Default"; + qInfo() << "No Specific Binding Detected for: " + appID + + "for Scene: " + sceneAppID + " Checking Default"; Fn = QString::fromStdString( "defovl" + appID + "ctrl" + ctrlType + ".json" ); if ( !QFileInfo::exists( fi.absolutePath() + QString( "/" ) + Fn ) ) { - LOG( INFO ) << "No Def Binding Detected for: " + appID - + " Not Adjusting Bindings"; + qInfo() << "No Def Binding Detected for: " + appID + + " Not Adjusting Bindings"; return; } } @@ -886,14 +888,13 @@ void SteamVRTabController::applyBindingReq( std::string appID ) QUrl urlized = QUrl::fromLocalFile( absPath ); // std::string filePath = "file:///" + absPath.toStdString(); std::string url = "http://localhost:27062/input/selectconfig.action"; - // LOG( INFO ) << urlized.toEncoded().toStdString(); + // qInfo () << urlized.toEncoded().toStdString(); QUrl urls = QUrl( url.c_str() ); QNetworkRequest request; request.setUrl( urls ); - LOG( INFO ) << "Attempting to Apply Binding at: " - << urlized - .toEncoded( QUrl::EncodeSpaces | QUrl::EncodeReserved ) - .toStdString(); + qInfo() << "Attempting to Apply Binding at: " + << urlized.toEncoded( QUrl::EncodeSpaces | QUrl::EncodeReserved ) + .toStdString(); // This is Important as otherwise Valve's VRWebServerWillIgnore the Request // If referrer is wrong request.setHeader( QNetworkRequest::ContentTypeHeader, @@ -909,8 +910,8 @@ void SteamVRTabController::applyBindingReq( std::string appID ) .toStdString() + "\"}" ) .c_str(); - // LOG( INFO ) << "Sending Binding Set Request"; - // LOG( INFO ) << data.toStdString(); + // qInfo () << "Sending Binding Set Request"; + // qInfo () << data.toStdString(); connect( &m_networkManagerApply, SIGNAL( finished( QNetworkReply* ) ), this, @@ -926,21 +927,21 @@ void SteamVRTabController::onApplyBindingResponse( QNetworkReply* reply ) { return; } - // LOG( INFO ) << "APPLY RESPONSE"; - // LOG( INFO ) << data.toStdString(); + // qInfo () << "APPLY RESPONSE"; + // qInfo () << data.toStdString(); reply->close(); json jsonfull = json::parse( data.toStdString() ); if ( !jsonfull.contains( "success" ) ) { - LOG( ERROR ) << "Apply Binding Packet Mal-Formed?"; + qCritical() << "Apply Binding Packet Mal-Formed?"; return; } if ( !jsonfull["success"].get() ) { // TODO better error handling? - LOG( ERROR ) << "Binding Failed To Apply"; + qCritical() << "Binding Failed To Apply"; } - LOG( INFO ) << "New Binding Applied"; + qInfo() << "New Binding Applied"; return; } diff --git a/src/tabcontrollers/UtilitiesTabController.cpp b/src/tabcontrollers/UtilitiesTabController.cpp index 80ca3ba8..46310ecd 100644 --- a/src/tabcontrollers/UtilitiesTabController.cpp +++ b/src/tabcontrollers/UtilitiesTabController.cpp @@ -1,11 +1,15 @@ #include "UtilitiesTabController.h" #include #include +#include +#include #include "../overlaycontroller.h" #include "../keyboard_input/input_sender.h" #include "../settings/settings.h" #include "../utils/update_rate.h" +#include "openvr/ovr_overlay_wrapper.h" #include +#include #include // application namespace @@ -236,8 +240,8 @@ QString getBatteryIconPath( int batteryState ) if ( !batteryPath.has_value() ) { - LOG( ERROR ) << "Unable to find battery image number '" << batteryState - << "'."; + qCritical() << "Unable to find battery image number '" << batteryState + << "'."; return ""; } @@ -255,40 +259,42 @@ vr::VROverlayHandle_t UtilitiesTabController::createBatteryOverlay( batteryKey.c_str(), batteryKey.c_str(), &handle ); if ( overlayError == vr::VROverlayError_None ) { - QString batteryIconPath = getBatteryIconPath( 0 ); - if ( QFile::exists( batteryIconPath ) ) + m_batteryImgs[0] = std::unique_ptr( + new QImage( QString( ":/battery/battery_0.png" ) ) ); + m_batteryImgs[1] = std::unique_ptr( + new QImage( QString( ":/battery/battery_1.png" ) ) ); + m_batteryImgs[2] = std::unique_ptr( + new QImage( QString( ":/battery/battery_2.png" ) ) ); + m_batteryImgs[3] = std::unique_ptr( + new QImage( QString( ":/battery/battery_3.png" ) ) ); + m_batteryImgs[4] = std::unique_ptr( + new QImage( QString( ":/battery/battery_4.png" ) ) ); + m_batteryImgs[5] = std::unique_ptr( + new QImage( QString( ":/battery/battery_5.png" ) ) ); + ovr_overlay_wrapper::setOverlayFromQImage( handle, *m_batteryImgs[0] ); + vr::VROverlay()->SetOverlayWidthInMeters( handle, 0.045f ); + vr::HmdMatrix34_t notificationTransform; + if ( style == 1 ) { - vr::VROverlay()->SetOverlayFromFile( - handle, batteryIconPath.toStdString().c_str() ); - vr::VROverlay()->SetOverlayWidthInMeters( handle, 0.045f ); - vr::HmdMatrix34_t notificationTransform; - if ( style == 1 ) - { - notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.00f }, - { 0.0f, -1.0f, 0.0f, 0.0081f }, - { 0.0f, 0.0f, -1.0f, -0.028f } } }; - } - else - { - notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.00f }, - { 0.0f, -1.0f, 0.0f, 0.0081f }, - { 0.0f, 0.0f, -1.0f, -0.0178f } } }; - } - vr::VROverlay()->SetOverlayTransformTrackedDeviceRelative( - handle, index, ¬ificationTransform ); - LOG( INFO ) << "Created battery overlay for device " << index; + notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.00f }, + { 0.0f, -1.0f, 0.0f, 0.0081f }, + { 0.0f, 0.0f, -1.0f, -0.028f } } }; } else { - LOG( ERROR ) << "Could not find battery icon \"" << batteryIconPath - << "\""; + notificationTransform = { { { 1.0f, 0.0f, 0.0f, 0.00f }, + { 0.0f, -1.0f, 0.0f, 0.0081f }, + { 0.0f, 0.0f, -1.0f, -0.0178f } } }; } + vr::VROverlay()->SetOverlayTransformTrackedDeviceRelative( + handle, index, ¬ificationTransform ); + qInfo() << "Created battery overlay for device " << index; } else { - LOG( ERROR ) << "Could not create ptt notification overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not create ptt notification overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); } return handle; @@ -306,8 +312,8 @@ void UtilitiesTabController::destroyBatteryOverlays() el = 0; if ( err != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not Delete Battery Overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( err ); + qCritical() << "Could not Delete Battery Overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( err ); } } } @@ -337,7 +343,7 @@ void UtilitiesTabController::handleTrackerBatOvl() } } - LOG( INFO ) << "Creating battery overlay for device " << i; + qInfo() << "Creating battery overlay for device " << i; m_batteryOverlayHandles[i] = createBatteryOverlay( i, style ); m_batteryVisible[i] = true; } @@ -373,23 +379,12 @@ void UtilitiesTabController::handleTrackerBatOvl() if ( batteryState != m_batteryState[i] ) { - LOG( INFO ) - << "Updating battery overlay for device " << i << " to " - << batteryState << "(" << battery << ")" - << QString::number( m_batteryOverlayHandles[i] ); - QString batteryIconPath - = getBatteryIconPath( batteryState ); - if ( QFile::exists( batteryIconPath ) ) - { - vr::VROverlay()->SetOverlayFromFile( - m_batteryOverlayHandles[i], - batteryIconPath.toStdString().c_str() ); - } - else - { - LOG( ERROR ) << "Could not find battery icon \"" - << batteryIconPath << "\""; - } + qInfo() << "Updating battery overlay for device " << i + << " to " << batteryState << "(" << battery << ")" + << QString::number( m_batteryOverlayHandles[i] ); + ovr_overlay_wrapper::setOverlayFromQImage( + m_batteryOverlayHandles[i], + *m_batteryImgs[batteryState] ); m_batteryState[i] = batteryState; } } diff --git a/src/tabcontrollers/UtilitiesTabController.h b/src/tabcontrollers/UtilitiesTabController.h index 8dc0ffff..4bd57d13 100644 --- a/src/tabcontrollers/UtilitiesTabController.h +++ b/src/tabcontrollers/UtilitiesTabController.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include "src/keyboard_input/keyboard_input.h" @@ -29,6 +30,7 @@ class UtilitiesTabController : public QObject unsigned settingsUpdateCounter = 0; + std::array, 6> m_batteryImgs; vr::VROverlayHandle_t m_batteryOverlayHandles[vr::k_unMaxTrackedDeviceCount] = { 0 }; int m_batteryState[vr::k_unMaxTrackedDeviceCount]; diff --git a/src/tabcontrollers/VideoTabController.cpp b/src/tabcontrollers/VideoTabController.cpp index ff79ff84..8a6165d0 100644 --- a/src/tabcontrollers/VideoTabController.cpp +++ b/src/tabcontrollers/VideoTabController.cpp @@ -1,6 +1,8 @@ #include "VideoTabController.h" #include #include +#include +#include #include "../settings/settings.h" #include "../overlaycontroller.h" #include "../utils/update_rate.h" @@ -50,36 +52,27 @@ void VideoTabController::initBrightnessOverlay() notifKey.c_str(), notifKey.c_str(), &m_brightnessOverlayHandle ); if ( overlayError == vr::VROverlayError_None ) { - const auto notifIconPath = paths::binaryDirectoryFindFile( - video_keys::k_brightnessOverlayFilename ); - if ( notifIconPath.has_value() ) - { - vr::VROverlay()->SetOverlayFromFile( m_brightnessOverlayHandle, - notifIconPath->c_str() ); - vr::VROverlay()->SetOverlayWidthInMeters( m_brightnessOverlayHandle, - k_overlayWidth ); - vr::HmdMatrix34_t notificationTransform - = { { { 1.0f, 0.0f, 0.0f, 0.00f }, - { 0.0f, 1.0f, 0.0f, 0.00f }, - { 0.0f, 0.0f, 1.0f, k_hmdDistance } } }; - vr::VROverlay()->SetOverlayTransformTrackedDeviceRelative( - m_brightnessOverlayHandle, - vr::k_unTrackedDeviceIndex_Hmd, - ¬ificationTransform ); - vr::VROverlay()->SetOverlaySortOrder( m_brightnessOverlayHandle, - sortMax ); - } - else - { - LOG( ERROR ) << "Could not find brightness overlay \"" - << video_keys::k_brightnessOverlayFilename << "\""; - } + QImage notifIcon( QString( ":/video/dimmer.png" ) ); + ovr_overlay_wrapper::setOverlayFromQImage( m_brightnessOverlayHandle, + notifIcon ); + vr::VROverlay()->SetOverlayWidthInMeters( m_brightnessOverlayHandle, + k_overlayWidth ); + vr::HmdMatrix34_t notificationTransform + = { { { 1.0f, 0.0f, 0.0f, 0.00f }, + { 0.0f, 1.0f, 0.0f, 0.00f }, + { 0.0f, 0.0f, 1.0f, k_hmdDistance } } }; + vr::VROverlay()->SetOverlayTransformTrackedDeviceRelative( + m_brightnessOverlayHandle, + vr::k_unTrackedDeviceIndex_Hmd, + ¬ificationTransform ); + vr::VROverlay()->SetOverlaySortOrder( m_brightnessOverlayHandle, + sortMax ); } else { - LOG( ERROR ) << "Could not create brightness overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not create brightness overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); } setBrightnessOpacityValue( brightnessOpacityValue(), false ); } @@ -93,38 +86,29 @@ void VideoTabController::initColorOverlay() notifKey.c_str(), notifKey.c_str(), &m_colorOverlayHandle ); if ( overlayError == vr::VROverlayError_None ) { - const auto notifIconPath = paths::binaryDirectoryFindFile( - video_keys::k_colorOverlayFilename ); - if ( notifIconPath.has_value() ) - { - vr::VROverlay()->SetOverlayFromFile( m_colorOverlayHandle, - notifIconPath->c_str() ); - vr::VROverlay()->SetOverlayWidthInMeters( m_colorOverlayHandle, - k_overlayWidth ); - // position it just slightly further out so we don't have to worry - // about render order. - vr::HmdMatrix34_t notificationTransform - = { { { 1.0f, 0.0f, 0.0f, 0.00f }, - { 0.0f, 1.0f, 0.0f, 0.00f }, - { 0.0f, 0.0f, 1.0f, ( k_hmdDistance - 0.01f ) } } }; - vr::VROverlay()->SetOverlayTransformTrackedDeviceRelative( - m_colorOverlayHandle, - vr::k_unTrackedDeviceIndex_Hmd, - ¬ificationTransform ); - vr::VROverlay()->SetOverlaySortOrder( m_brightnessOverlayHandle, - sortMax ); - } - else - { - LOG( ERROR ) << "Could not find Base color overlay: \"" - << video_keys::k_colorOverlayFilename << "\""; - } + QImage notifIcon( QString( ":/video/color.png" ) ); + ovr_overlay_wrapper::setOverlayFromQImage( m_colorOverlayHandle, + notifIcon ); + vr::VROverlay()->SetOverlayWidthInMeters( m_colorOverlayHandle, + k_overlayWidth ); + // position it just slightly further out so we don't have to worry + // about render order. + vr::HmdMatrix34_t notificationTransform + = { { { 1.0f, 0.0f, 0.0f, 0.00f }, + { 0.0f, 1.0f, 0.0f, 0.00f }, + { 0.0f, 0.0f, 1.0f, ( k_hmdDistance - 0.01f ) } } }; + vr::VROverlay()->SetOverlayTransformTrackedDeviceRelative( + m_colorOverlayHandle, + vr::k_unTrackedDeviceIndex_Hmd, + ¬ificationTransform ); + vr::VROverlay()->SetOverlaySortOrder( m_brightnessOverlayHandle, + sortMax ); } else { - LOG( ERROR ) << "Could not create color overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not create color overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); } } @@ -134,18 +118,18 @@ void VideoTabController::loadColorOverlay() m_colorOverlayHandle, colorRed(), colorGreen(), colorBlue() ); if ( overlayError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not set Colors for color overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not set Colors for color overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); } overlayError = vr::VROverlay()->SetOverlayAlpha( m_colorOverlayHandle, colorOverlayOpacity() ); if ( overlayError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not set alpha: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not set alpha: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); } emit colorOverlayOpacityChanged( true ); } @@ -214,7 +198,7 @@ void VideoTabController::setBrightnessEnabled( bool value, setBrightnessOpacityValue( brightnessOpacityValue(), false ); ovr_overlay_wrapper::showOverlay( getBrightnessOverlayHandle() ); - LOG( INFO ) << "Brightness Overlay toggled on"; + qInfo() << "Brightness Overlay toggled on"; } } else @@ -223,7 +207,7 @@ void VideoTabController::setBrightnessEnabled( bool value, { ovr_overlay_wrapper::hideOverlay( getBrightnessOverlayHandle() ); - LOG( INFO ) << "Brightness Overlay toggled off"; + qInfo() << "Brightness Overlay toggled off"; } } @@ -247,7 +231,7 @@ void VideoTabController::setBrightnessOpacityValue( float percvalue, if ( realvalue >= 0.9999f || realvalue < 0.00f ) { - LOG( WARNING ) << "alpha value is invalid setting to 1.0"; + qWarning() << "alpha value is invalid setting to 1.0"; settings::setSetting( settings::DoubleSetting::VIDEO_brightnessOpacityValue, 1.0 ); realvalue = 0; @@ -346,7 +330,7 @@ void VideoTabController::setColorOverlayEnabled( bool value, if ( overlayHandle != vr::k_ulOverlayHandleInvalid ) { ovr_overlay_wrapper::showOverlay( getColorOverlayHandle() ); - LOG( INFO ) << "Color Overlay toggled on"; + qInfo() << "Color Overlay toggled on"; } } else @@ -354,7 +338,7 @@ void VideoTabController::setColorOverlayEnabled( bool value, if ( overlayHandle != vr::k_ulOverlayHandleInvalid ) { ovr_overlay_wrapper::hideOverlay( getColorOverlayHandle() ); - LOG( INFO ) << "Color Overlay toggled off"; + qInfo() << "Color Overlay toggled off"; } } @@ -397,11 +381,11 @@ void VideoTabController::synchGain( bool setValue ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not read \"" - << vr::k_pch_SteamVR_HmdDisplayColorGainR_Float - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not read \"" + << vr::k_pch_SteamVR_HmdDisplayColorGainR_Float + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -418,11 +402,11 @@ void VideoTabController::synchGain( bool setValue ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not read \"" - << vr::k_pch_SteamVR_HmdDisplayColorGainB_Float - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not read \"" + << vr::k_pch_SteamVR_HmdDisplayColorGainB_Float + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -439,11 +423,11 @@ void VideoTabController::synchGain( bool setValue ) &vrSettingsError ); if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not read \"" - << vr::k_pch_SteamVR_HmdDisplayColorGainG_Float - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not read \"" + << vr::k_pch_SteamVR_HmdDisplayColorGainG_Float + << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } else { @@ -473,9 +457,9 @@ void VideoTabController::setColorRed( float value, bool notify, bool keepValue ) m_colorOverlayHandle, colorRed(), colorGreen(), colorBlue() ); if ( overlayError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not set Red for color overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not set Red for color overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); } } else @@ -489,13 +473,13 @@ void VideoTabController::setColorRed( float value, bool notify, bool keepValue ) if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "could not set Red Gain Value, Error: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qCritical() << "could not set Red Gain Value, Error: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } } - LOG( DEBUG ) << "Changed Red Value to: " << colorRed(); + qDebug() << "Changed Red Value to: " << colorRed(); if ( notify ) { @@ -523,9 +507,9 @@ void VideoTabController::setColorGreen( float value, m_colorOverlayHandle, colorRed(), colorGreen(), colorBlue() ); if ( overlayError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not set Green for color overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not set Green for color overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); } } else @@ -539,13 +523,13 @@ void VideoTabController::setColorGreen( float value, if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "could not set Green Gain Value, Error: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qCritical() << "could not set Green Gain Value, Error: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } } - LOG( DEBUG ) << "Changed Green Value to: " << colorGreen(); + qDebug() << "Changed Green Value to: " << colorGreen(); if ( notify ) { @@ -572,9 +556,9 @@ void VideoTabController::setColorBlue( float value, m_colorOverlayHandle, colorRed(), colorGreen(), colorBlue() ); if ( overlayError != vr::VROverlayError_None ) { - LOG( ERROR ) << "Could not set Blue for color overlay: " - << vr::VROverlay()->GetOverlayErrorNameFromEnum( - overlayError ); + qCritical() << "Could not set Blue for color overlay: " + << vr::VROverlay()->GetOverlayErrorNameFromEnum( + overlayError ); } } else @@ -588,13 +572,13 @@ void VideoTabController::setColorBlue( float value, if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "could not set Blue Gain Value, Error: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qCritical() << "could not set Blue Gain Value, Error: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } } - LOG( DEBUG ) << "Changed Blue Value to: " << colorBlue(); + qDebug() << "Changed Blue Value to: " << colorBlue(); if ( notify ) { @@ -613,9 +597,9 @@ void VideoTabController::resetGain() if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "could not set Red Gain Value, Error: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qCritical() << "could not set Red Gain Value, Error: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } vr::VRSettings()->SetFloat( vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_HmdDisplayColorGainG_Float, @@ -624,9 +608,9 @@ void VideoTabController::resetGain() if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "could not set Green Gain Value, Error: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qCritical() << "could not set Green Gain Value, Error: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } vr::VRSettings()->SetFloat( vr::k_pch_SteamVR_Section, @@ -636,9 +620,9 @@ void VideoTabController::resetGain() if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( ERROR ) << "could not set Blue Gain Value, Error: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qCritical() << "could not set Blue Gain Value, Error: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); } } @@ -691,13 +675,12 @@ void VideoTabController::setSuperSampling( float value, const bool notify ) // Mirrors Desktop Clamp if ( value < 0.2f ) { - LOG( WARNING ) - << "Encountered a supersampling value <= 0.2, setting " - "supersampling to 1.0"; + qWarning() << "Encountered a supersampling value <= 0.2, setting " + "supersampling to 1.0"; value = 1.0f; } - LOG( DEBUG ) << "Supersampling value changed: " << m_superSampling - << " => " << value; + qDebug() << "Supersampling value changed: " << m_superSampling << " => " + << value; m_superSampling = value; ovr_settings_wrapper::setFloat( vr::k_pch_SteamVR_Section, diff --git a/src/tabcontrollers/audiomanager/AudioManagerPulse.cpp b/src/tabcontrollers/audiomanager/AudioManagerPulse.cpp index 514e6ab6..07f693c0 100644 --- a/src/tabcontrollers/audiomanager/AudioManagerPulse.cpp +++ b/src/tabcontrollers/audiomanager/AudioManagerPulse.cpp @@ -1,4 +1,3 @@ -#include #include "AudioManagerPulse.h" #include "AudioManagerPulse_internal.h" #include "../AudioTabController.h" diff --git a/src/tabcontrollers/audiomanager/AudioManagerPulse_internal.h b/src/tabcontrollers/audiomanager/AudioManagerPulse_internal.h index 82723489..a16faa62 100644 --- a/src/tabcontrollers/audiomanager/AudioManagerPulse_internal.h +++ b/src/tabcontrollers/audiomanager/AudioManagerPulse_internal.h @@ -1,7 +1,8 @@ #pragma once #include #include -#include +#include +#include #include "AudioManager.h" // Used to get the compiler to shut up about C4100: unreferenced formal @@ -66,58 +67,58 @@ void customPulseLoop() // Error function void dumpPulseAudioState() { - LOG( ERROR ) << "____"; + qCritical() << "____"; - LOG( ERROR ) << "Dumping PulseAudio state: "; - LOG( ERROR ) << "mainLoop: " << pulseAudioPointers.mainLoop; - LOG( ERROR ) << "api: " << pulseAudioPointers.api; - LOG( ERROR ) << "context: " << pulseAudioPointers.context; + qCritical() << "Dumping PulseAudio state: "; + qCritical() << "mainLoop: " << pulseAudioPointers.mainLoop; + qCritical() << "api: " << pulseAudioPointers.api; + qCritical() << "context: " << pulseAudioPointers.context; - LOG( ERROR ) << ""; + qCritical() << ""; - LOG( ERROR ) << "Data:"; - LOG( ERROR ) << "\tdefaultSinkOutputDeviceId: " - << pulseAudioData.defaultSinkOutputDeviceId; - LOG( ERROR ) << "\tdefaultSourceInputDeviceId: " - << pulseAudioData.defaultSourceInputDeviceId; + qCritical() << "Data:"; + qCritical() << "\tdefaultSinkOutputDeviceId: " + << pulseAudioData.defaultSinkOutputDeviceId; + qCritical() << "\tdefaultSourceInputDeviceId: " + << pulseAudioData.defaultSourceInputDeviceId; - LOG( ERROR ) << ""; + qCritical() << ""; - LOG( ERROR ) << "\tcurrentDefaultSinkInfo name: " - << pulseAudioData.currentDefaultSinkInfo.name; - LOG( ERROR ) << "\tcurrentDefaultSourceInfo name: " - << pulseAudioData.currentDefaultSourceInfo.name; + qCritical() << "\tcurrentDefaultSinkInfo name: " + << pulseAudioData.currentDefaultSinkInfo.name; + qCritical() << "\tcurrentDefaultSourceInfo name: " + << pulseAudioData.currentDefaultSourceInfo.name; - LOG( ERROR ) << ""; + qCritical() << ""; - LOG( ERROR ) << "sinkOutputDevices: "; - LOG_IF( pulseAudioData.sinkOutputDevices.size() == 0, ERROR ) - << "\tOutput devices size zero."; + qCritical() << "sinkOutputDevices: "; + if ( pulseAudioData.sinkOutputDevices.size() == 0 ) + qCritical() << "\tOutput devices size zero."; for ( const auto& device : pulseAudioData.sinkOutputDevices ) { - LOG( ERROR ) << "\tDevice Name: " << device.name(); - LOG( ERROR ) << "\tDevice Id: " << device.id(); + qCritical() << "\tDevice Name: " << device.name(); + qCritical() << "\tDevice Id: " << device.id(); } - LOG( ERROR ) << ""; + qCritical() << ""; - LOG( ERROR ) << "sourceInputDevices: "; - LOG_IF( pulseAudioData.sourceInputDevices.size() == 0, ERROR ) - << "\tInput devices size zero."; + qCritical() << "sourceInputDevices: "; + if ( pulseAudioData.sourceInputDevices.size() == 0 ) + qCritical() << "\tInput devices size zero."; for ( const auto& device : pulseAudioData.sourceInputDevices ) { - LOG( ERROR ) << "\tDevice Name: " << device.name(); - LOG( ERROR ) << "\tDevice Id: " << device.id(); + qCritical() << "\tDevice Name: " << device.name(); + qCritical() << "\tDevice Id: " << device.id(); } - LOG( ERROR ) << "____"; + qCritical() << "____"; } PulseAudioIsLastMeaning getIsLastMeaning( const int isLast ) noexcept { if ( isLast < 0 ) { - LOG( ERROR ) << "Error in isLast."; + qCritical() << "Error in isLast."; dumpPulseAudioState(); return PulseAudioIsLastMeaning::Error; } @@ -134,14 +135,14 @@ std::string getDeviceName( pa_proplist* p ) { if ( !p ) { - LOG( ERROR ) << "proplist not valid."; + qCritical() << "proplist not valid."; } constexpr auto deviceDescription = "device.description"; if ( !pa_proplist_contains( p, deviceDescription ) ) { - LOG( ERROR ) << "proplist does not contain '" << deviceDescription - << "'."; + qCritical() << "proplist does not contain '" << deviceDescription + << "'."; return "ERROR"; } @@ -166,7 +167,7 @@ template void deviceCallback( const T* i, const int isLast ) } else if ( deviceState == PulseAudioIsLastMeaning::Error ) { - LOG( ERROR ) << "Error in deviceCallback function."; + qCritical() << "Error in deviceCallback function."; dumpPulseAudioState(); loopControl = PulseAudioLoopControl::Stop; return; @@ -179,8 +180,10 @@ template void deviceCallback( const T* i, const int isLast ) pulseAudioData.currentDefaultSourceInfo = *i; } - LOG( DEBUG ) << "Adding device to input: '" << i->name << "', '" - << getDeviceName( i->proplist ) << "'."; + /* + qDebug() << "Adding device to input: '" << i->name << "', '" + << getDeviceName( i->proplist ) << "'."; + */ pulseAudioData.sourceInputDevices.push_back( AudioDevice( i->name, getDeviceName( i->proplist ) ) ); } @@ -192,8 +195,10 @@ template void deviceCallback( const T* i, const int isLast ) pulseAudioData.currentDefaultSinkInfo = *i; } - LOG( DEBUG ) << "Adding device to output: '" << i->name << "', '" - << getDeviceName( i->proplist ) << "'."; + /* + qDebug() << "Adding device to output: '" << i->name << "', '" + << getDeviceName( i->proplist ) << "'."; + */ pulseAudioData.sinkOutputDevices.push_back( AudioDevice( i->name, getDeviceName( i->proplist ) ) ); } @@ -230,7 +235,7 @@ void getDefaultDevicesCallback( pa_context* c, if ( !i ) { - LOG( ERROR ) << "i == 0"; + qCritical() << "i == 0"; pulseAudioData.defaultSinkOutputDeviceId = "DDO:ERROR"; pulseAudioData.defaultSourceInputDeviceId = "DDI:ERROR"; return; @@ -242,10 +247,12 @@ void getDefaultDevicesCallback( pa_context* c, loopControl = PulseAudioLoopControl::Stop; - LOG( DEBUG ) << "getDefaultDevicesCallback done with sink output device: '" - << pulseAudioData.defaultSinkOutputDeviceId - << "' and source input '" - << pulseAudioData.defaultSourceInputDeviceId << "'."; + /* + qDebug() << "getDefaultDevicesCallback done with sink output device: '" + << pulseAudioData.defaultSinkOutputDeviceId + << "' and source input '" + << pulseAudioData.defaultSourceInputDeviceId << "'."; + */ } void stateCallbackFunction( pa_context* c, void* userdata ) @@ -256,27 +263,27 @@ void stateCallbackFunction( pa_context* c, void* userdata ) switch ( pa_context_get_state( c ) ) { case PA_CONTEXT_TERMINATED: - LOG( ERROR ) << "PA_CONTEXT_TERMINATED in stateCallbackFunction"; + qCritical() << "PA_CONTEXT_TERMINATED in stateCallbackFunction"; dumpPulseAudioState(); return; case PA_CONTEXT_CONNECTING: - LOG( DEBUG ) << "PA_CONTEXT_CONNECTING"; + qDebug() << "PA_CONTEXT_CONNECTING"; return; case PA_CONTEXT_AUTHORIZING: - LOG( DEBUG ) << "PA_CONTEXT_AUTHORIZING"; + qDebug() << "PA_CONTEXT_AUTHORIZING"; return; case PA_CONTEXT_SETTING_NAME: - LOG( DEBUG ) << "PA_CONTEXT_SETTING_NAME"; + qDebug() << "PA_CONTEXT_SETTING_NAME"; return; case PA_CONTEXT_UNCONNECTED: - LOG( DEBUG ) << "PA_CONTEXT_UNCONNECTED"; + qDebug() << "PA_CONTEXT_UNCONNECTED"; return; case PA_CONTEXT_FAILED: - LOG( DEBUG ) << "PA_CONTEXT_FAILED"; + qDebug() << "PA_CONTEXT_FAILED"; return; case PA_CONTEXT_READY: - LOG( DEBUG ) << "PA_CONTEXT_READY"; + qDebug() << "PA_CONTEXT_READY"; loopControl = PulseAudioLoopControl::Stop; return; } @@ -302,7 +309,7 @@ void updateAllPulseData() pulseAudioPointers.context, setInputDevicesCallback, noCustomUserdata ); customPulseLoop(); - LOG( DEBUG ) << "updateAllPulseData done."; + qDebug() << "updateAllPulseData done."; } void successCallback( pa_context* c, int success, void* successVariable ) @@ -316,7 +323,7 @@ void successCallback( pa_context* c, int success, void* successVariable ) if ( !success ) { - LOG( ERROR ) << "Non successful callback operation."; + qCritical() << "Non successful callback operation."; dumpPulseAudioState(); } @@ -335,12 +342,12 @@ void setPlaybackDeviceInternal( const std::string& id ) if ( !success ) { - LOG( ERROR ) << "setPlaybackDeviceInternal failed to set default sink " - "for device '" - << id << "'."; + qCritical() << "setPlaybackDeviceInternal failed to set default sink " + "for device '" + << id << "'."; } - LOG( DEBUG ) << "setPlaybackDeviceInternal done with id: " << id; + qDebug() << "setPlaybackDeviceInternal done with id: " << id; } std::string getCurrentDefaultPlaybackDeviceName() @@ -351,12 +358,12 @@ std::string getCurrentDefaultPlaybackDeviceName() { if ( dev.id() == pulseAudioData.defaultSinkOutputDeviceId ) { - LOG( DEBUG ) << "getCurrentDefaultPlaybackDeviceName done with " - << dev.name(); + qDebug() << "getCurrentDefaultPlaybackDeviceName done with " + << dev.name(); return dev.name(); } } - LOG( ERROR ) << "Unable to find default playback device."; + qCritical() << "Unable to find default playback device."; return "ERROR"; } @@ -365,8 +372,8 @@ std::string getCurrentDefaultPlaybackDeviceId() { updateAllPulseData(); - LOG( DEBUG ) << "getCurrentDefaultPlaybackDeviceId done with " - << pulseAudioData.defaultSinkOutputDeviceId; + qDebug() << "getCurrentDefaultPlaybackDeviceId done with " + << pulseAudioData.defaultSinkOutputDeviceId; return pulseAudioData.defaultSinkOutputDeviceId; } @@ -379,12 +386,12 @@ std::string getCurrentDefaultRecordingDeviceName() { if ( dev.id() == pulseAudioData.defaultSourceInputDeviceId ) { - LOG( DEBUG ) << "getCurrentDefaultRecordingDeviceName done with: " - << dev.name(); + qDebug() << "getCurrentDefaultRecordingDeviceName done with: " + << dev.name(); return dev.name(); } } - LOG( ERROR ) << "Unable to find default playback device."; + qCritical() << "Unable to find default playback device."; return "ERROR"; } @@ -393,8 +400,8 @@ std::string getCurrentDefaultRecordingDeviceId() { updateAllPulseData(); - LOG( DEBUG ) << "getCurrentDefaultRecordingDeviceId done with " - << pulseAudioData.defaultSourceInputDeviceId; + qDebug() << "getCurrentDefaultRecordingDeviceId done with " + << pulseAudioData.defaultSourceInputDeviceId; return pulseAudioData.defaultSourceInputDeviceId; } @@ -452,7 +459,7 @@ void sourceOutputCallback( pa_context* c, } else if ( deviceState == PulseAudioIsLastMeaning::Error ) { - LOG( ERROR ) << "Error in sourceOutputCallback function."; + qCritical() << "Error in sourceOutputCallback function."; dumpPulseAudioState(); return; } @@ -460,9 +467,9 @@ void sourceOutputCallback( pa_context* c, const auto sourceOutputIndex = i->index; const auto sourceIndex = pulseAudioData.currentDefaultSourceInfo.index; - LOG( DEBUG ) << "Attempting to move sourceOutputIndex: '" - << sourceOutputIndex << "' to sourceIndex '" << sourceIndex - << "' with source output name " << i->name << "."; + qDebug() << "Attempting to move sourceOutputIndex: '" << sourceOutputIndex + << "' to sourceIndex '" << sourceIndex + << "' with source output name " << i->name << "."; pa_context_move_source_output_by_index( c, sourceOutputIndex, sourceIndex, successCallback, &success ); @@ -470,7 +477,7 @@ void sourceOutputCallback( pa_context* c, void setMicrophoneDevice( const std::string& id ) { - LOG( DEBUG ) << "setMicrophoneDevice called with 'id': " << id; + qDebug() << "setMicrophoneDevice called with 'id': " << id; updateAllPulseData(); @@ -482,7 +489,7 @@ void setMicrophoneDevice( const std::string& id ) if ( !success ) { - LOG( ERROR ) << "Error setting microphone device for '" << id << "'."; + qCritical() << "Error setting microphone device for '" << id << "'."; } updateAllPulseData(); @@ -494,17 +501,17 @@ void setMicrophoneDevice( const std::string& id ) if ( !success ) { - LOG( ERROR ) << "Error in moving source outputs to new source."; + qCritical() << "Error in moving source outputs to new source."; } updateAllPulseData(); - LOG( DEBUG ) << "setMicrophoneDevice done."; + qDebug() << "setMicrophoneDevice done."; } bool setPlaybackVolume( const float volume ) { - LOG( DEBUG ) << "setPlaybackVolume called with 'volume': " << volume; + qDebug() << "setPlaybackVolume called with 'volume': " << volume; updateAllPulseData(); @@ -525,19 +532,19 @@ bool setPlaybackVolume( const float volume ) if ( !success ) { - LOG( ERROR ) << "setPlaybackVolume failed to set volume '" << volume - << "' for device '" - << pulseAudioData.defaultSinkOutputDeviceId << "'."; + qCritical() << "setPlaybackVolume failed to set volume '" << volume + << "' for device '" + << pulseAudioData.defaultSinkOutputDeviceId << "'."; } - LOG( DEBUG ) << "setPlaybackVolume done with 'success': " << success; + qDebug() << "setPlaybackVolume done with 'success': " << success; return success; } bool setMicrophoneVolume( const float volume ) { - LOG( DEBUG ) << "setMicrophoneVolume called with 'volume': " << volume; + qDebug() << "setMicrophoneVolume called with 'volume': " << volume; updateAllPulseData(); @@ -558,19 +565,19 @@ bool setMicrophoneVolume( const float volume ) if ( !success ) { - LOG( ERROR ) << "seMicrophoneVolume failed to set volume '" << volume - << "' for device '" - << pulseAudioData.defaultSourceInputDeviceId << "'."; + qCritical() << "seMicrophoneVolume failed to set volume '" << volume + << "' for device '" + << pulseAudioData.defaultSourceInputDeviceId << "'."; } - LOG( DEBUG ) << "setMicrophoneVolume done with 'success': " << success; + qDebug() << "setMicrophoneVolume done with 'success': " << success; return success; } bool setMicMuteState( const bool muted ) { - LOG( DEBUG ) << "setMicMuteState called with 'muted': " << muted; + qDebug() << "setMicMuteState called with 'muted': " << muted; bool success = false; pa_context_set_source_mute_by_name( @@ -584,19 +591,19 @@ bool setMicMuteState( const bool muted ) if ( !success ) { - LOG( ERROR ) << "setMicMuteState failed to set muted '" << muted - << "' for device '" - << pulseAudioData.defaultSourceInputDeviceId << "'."; + qCritical() << "setMicMuteState failed to set muted '" << muted + << "' for device '" + << pulseAudioData.defaultSourceInputDeviceId << "'."; } - LOG( DEBUG ) << "setMicMuteState done with 'success': " << success; + qDebug() << "setMicMuteState done with 'success': " << success; return success; } void restorePulseAudioState() { - LOG( DEBUG ) << "restorePulseAudioState called."; + qDebug() << "restorePulseAudioState called."; setPlaybackDeviceInternal( pulseAudioData.originalDefaultOutputDeviceId ); setPlaybackVolume( pulseAudioData.originalDefaultOutputDeviceVolume ); @@ -604,12 +611,12 @@ void restorePulseAudioState() setMicrophoneDevice( pulseAudioData.originalDefaultInputDeviceId ); setMicrophoneVolume( pulseAudioData.originalDefaultInputDeviceVolume ); - LOG( DEBUG ) << "restorePulseAudioState done."; + qDebug() << "restorePulseAudioState done."; } void initializePulseAudio() { - LOG( DEBUG ) << "initializePulseAudio called."; + qDebug() << "initializePulseAudio called."; pulseAudioPointers.mainLoop = pa_mainloop_new(); @@ -644,6 +651,6 @@ void initializePulseAudio() = static_cast( pa_sw_volume_to_linear( pa_cvolume_avg( &pulseAudioData.currentDefaultSinkInfo.volume ) ) ); - LOG( DEBUG ) << "initializePulseAudio finished."; + qDebug() << "initializePulseAudio finished."; } } // namespace advsettings diff --git a/src/tabcontrollers/audiomanager/AudioManagerWindows.cpp b/src/tabcontrollers/audiomanager/AudioManagerWindows.cpp index 21334a52..603383ec 100644 --- a/src/tabcontrollers/audiomanager/AudioManagerWindows.cpp +++ b/src/tabcontrollers/audiomanager/AudioManagerWindows.cpp @@ -1,6 +1,7 @@ #include "AudioManagerWindows.h" #include -#include "easylogging++.h" +#include +#include #include "../AudioTabController.h" #include @@ -48,7 +49,7 @@ void AudioManagerWindows::init( AudioTabController* var_controller ) playbackAudioDevice = getDefaultPlaybackDevice( audioDeviceEnumerator ); if ( !playbackAudioDevice ) { - LOG( WARNING ) << "Could not find a default recording device."; + qWarning() << "Could not find a default recording device."; } micAudioDevice = getDefaultRecordingDevice( audioDeviceEnumerator ); if ( micAudioDevice ) @@ -57,7 +58,7 @@ void AudioManagerWindows::init( AudioTabController* var_controller ) } else { - LOG( WARNING ) << "Could not find a default recording device."; + qWarning() << "Could not find a default recording device."; } this->controller = var_controller; audioDeviceEnumerator->RegisterEndpointNotificationCallback( @@ -65,7 +66,7 @@ void AudioManagerWindows::init( AudioTabController* var_controller ) policyConfig = getPolicyConfig(); if ( !policyConfig ) { - LOG( ERROR ) << "Could not find PolicyConfig interface"; + qCritical() << "Could not find PolicyConfig interface"; } } @@ -78,8 +79,7 @@ void AudioManagerWindows::setPlaybackDevice( const std::string& id, auto dev = getDevice( audioDeviceEnumerator, id ); if ( !dev ) { - LOG( WARNING ) << "Could not find playback device \"" << id - << "\"."; + qWarning() << "Could not find playback device \"" << id << "\"."; } else { @@ -142,7 +142,7 @@ void AudioManagerWindows::setMirrorDevice( const std::string& id, bool notify ) } else { - LOG( WARNING ) << "Could not find mirror device \"" << id << "\"."; + qWarning() << "Could not find mirror device \"" << id << "\"."; } } if ( notify ) @@ -258,8 +258,7 @@ void AudioManagerWindows::setMicDevice( const std::string& id, bool notify ) auto dev = getDevice( audioDeviceEnumerator, id ); if ( !dev ) { - LOG( WARNING ) << "Could not find recording device \"" << id - << "\"."; + qWarning() << "Could not find recording device \"" << id << "\"."; } else { @@ -617,7 +616,7 @@ AudioManagerWindows::OnDefaultDeviceChanged( EDataFlow flow, } else if ( !pwstrDefaultDeviceId ) { - LOG( WARNING ) << "No recording device available."; + qWarning() << "No recording device available."; } else { @@ -625,8 +624,8 @@ AudioManagerWindows::OnDefaultDeviceChanged( EDataFlow flow, converter; std::string name = converter.to_bytes( pwstrDefaultDeviceId ); - LOG( WARNING ) << "Could not find recording device \"" - << name << "\"."; + qWarning() << "Could not find recording device \"" << name + << "\"."; } controller->onNewRecordingDevice(); } @@ -647,7 +646,7 @@ AudioManagerWindows::OnDefaultDeviceChanged( EDataFlow flow, playbackAudioDevice = device; if ( !pwstrDefaultDeviceId ) { - LOG( WARNING ) << "No playback device available."; + qWarning() << "No playback device available."; } else if ( !playbackAudioDevice ) { @@ -655,7 +654,7 @@ AudioManagerWindows::OnDefaultDeviceChanged( EDataFlow flow, converter; std::string name = converter.to_bytes( pwstrDefaultDeviceId ); - LOG( WARNING ) + qWarning() << "Could not find playback device \"" << name << "\"."; } controller->onNewPlaybackDevice(); diff --git a/src/utils/ChaperoneUtils.h b/src/utils/ChaperoneUtils.h index 0eff735e..8e81948b 100644 --- a/src/utils/ChaperoneUtils.h +++ b/src/utils/ChaperoneUtils.h @@ -82,14 +82,14 @@ class ChaperoneUtils return ret; } - return *std::min_element( distances.begin(), - distances.end(), - []( const ChaperoneQuadData& quadA, - const ChaperoneQuadData& quadB ) { - return std::isnan( quadA.distance ) - || ( quadA.distance - < quadB.distance ); - } ); + return *std::min_element( + distances.begin(), + distances.end(), + []( const ChaperoneQuadData& quadA, const ChaperoneQuadData& quadB ) + { + return std::isnan( quadA.distance ) + || ( quadA.distance < quadB.distance ); + } ); } }; diff --git a/src/utils/FrameRateUtils.cpp b/src/utils/FrameRateUtils.cpp index 68a1779d..6df0779c 100644 --- a/src/utils/FrameRateUtils.cpp +++ b/src/utils/FrameRateUtils.cpp @@ -1,5 +1,6 @@ #include "FrameRateUtils.h" -#include +#include +#include namespace utils { @@ -18,11 +19,10 @@ unsigned int adjustUpdateRate( const unsigned int baseRefreshKey ) if ( vrSettingsError != vr::VRSettingsError_None ) { - LOG( WARNING ) << "Could not read \"" - << vr::k_pch_SteamVR_PreferredRefreshRate - << "\" setting: " - << vr::VRSettings()->GetSettingsErrorNameFromEnum( - vrSettingsError ); + qWarning() << "Could not read \"" + << vr::k_pch_SteamVR_PreferredRefreshRate << "\" setting: " + << vr::VRSettings()->GetSettingsErrorNameFromEnum( + vrSettingsError ); return baseRefreshKey; } diff --git a/src/utils/paths.cpp b/src/utils/paths.cpp index 9b07c268..4d762e59 100644 --- a/src/utils/paths.cpp +++ b/src/utils/paths.cpp @@ -3,7 +3,8 @@ #include #include #include -#include +#include +#include #include namespace paths @@ -14,7 +15,7 @@ optional binaryDirectory() if ( path == "" ) { - LOG( ERROR ) << "Could not find binary directory."; + qCritical() << "Could not find binary directory."; return std::nullopt; } @@ -36,8 +37,8 @@ optional binaryDirectoryFindFile( const string fileName ) if ( !file.exists() ) { - LOG( ERROR ) << "Could not find file '" << fileName.c_str() - << "' in binary directory."; + qCritical() << "Could not find file '" << fileName.c_str() + << "' in binary directory."; return std::nullopt; } @@ -50,7 +51,7 @@ optional settingsDirectory() = QStandardPaths::writableLocation( QStandardPaths::AppDataLocation ); if ( path == "" ) { - LOG( ERROR ) << "Could not find settings directory."; + qCritical() << "Could not find settings directory."; return std::nullopt; } @@ -62,7 +63,7 @@ std::optional verifyIconFilePath( std::string filename ) const auto notifIconPath = paths::binaryDirectoryFindFile( filename ); if ( !notifIconPath.has_value() ) { - LOG( ERROR ) << "Could not find icon \"" << filename << "\""; + qCritical() << "Could not find icon \"" << filename << "\""; } return notifIconPath; diff --git a/src/utils/setup.cpp b/src/utils/setup.cpp index 36ac96d1..5b6b7332 100644 --- a/src/utils/setup.cpp +++ b/src/utils/setup.cpp @@ -1,10 +1,15 @@ #include "setup.h" +#include +#include #ifdef ENABLE_DEBUG_LOGGING constexpr auto debugLoggingEnabled = true; #else constexpr auto debugLoggingEnabled = false; #endif +QtMessageHandler originalMessageHandler = nullptr; +static FILE* f; + // The default Qt message handler prints to stdout on X11 and to the debugger on // Windows. That is borderline useless for us, therefore we create our own // message handler. @@ -12,29 +17,11 @@ void mainQtMessageHandler( QtMsgType type, const QMessageLogContext& context, const QString& msg ) { - // context contains null pointers on release builds. Cast to get rid of - // unreferenced formal parameter warnings. - static_cast( context ); - - QByteArray localMsg = msg.toLocal8Bit(); - switch ( type ) - { - case QtDebugMsg: - LOG( DEBUG ) << "QTMSGH: " << localMsg.constData(); - break; - case QtInfoMsg: - LOG( INFO ) << "QTMSGH: " << localMsg.constData(); - break; - case QtWarningMsg: - LOG( WARNING ) << "QTMSGH: " << localMsg.constData(); - break; - case QtCriticalMsg: - LOG( ERROR ) << "QTMSGH: " << localMsg.constData(); - break; - case QtFatalMsg: - LOG( FATAL ) << "QTMSGH: " << localMsg.constData(); - break; - } + QString message = qFormatLogMessage( type, context, msg ); + fprintf( f, "%s\n", qPrintable( message ) ); + fflush( f ); + if ( originalMessageHandler ) + ( *originalMessageHandler )( type, context, msg ); } namespace argument @@ -74,25 +61,28 @@ CommandLineOptions returnCommandLineParser( const MyQApplication& application ) parser.process( application ); const bool desktopModeEnabled = parser.isSet( desktopMode ); - LOG_IF( desktopModeEnabled, INFO ) << "Desktop mode enabled."; + if ( desktopModeEnabled ) + qInfo() << "Desktop mode enabled."; const bool forceNoSoundEnabled = parser.isSet( forceNoSound ); - LOG_IF( forceNoSoundEnabled, INFO ) << "Sound effects disabled."; + if ( forceNoSoundEnabled ) + qInfo() << "Sound effects disabled."; const bool forceNoManifestEnabled = parser.isSet( forceNoManifest ); - LOG_IF( forceNoManifestEnabled, INFO ) - << "Running without applications manifest."; + if ( forceNoManifestEnabled ) + qInfo() << "Running without applications manifest."; const bool forceInstallManifestEnabled = parser.isSet( forceInstallManifest ); - LOG_IF( forceInstallManifestEnabled, INFO ) - << "Forcing install of applications manifest."; + if ( forceInstallManifestEnabled ) + qInfo() << "Forcing install of applications manifest."; const bool forceRemoveManifestEnabled = parser.isSet( forceRemoveManifest ); - LOG_IF( forceRemoveManifestEnabled, INFO ) - << "Forcing removal of applications manifest."; + if ( forceRemoveManifestEnabled ) + qInfo() << "Forcing removal of applications manifest."; const bool resetSettingsEnabled = parser.isSet( resetSettings ); - LOG_IF( resetSettingsEnabled, INFO ) << "Reset SteamVR Settings."; + if ( resetSettingsEnabled ) + qInfo() << "Reset SteamVR Settings."; const CommandLineOptions commandLineArgs{ desktopModeEnabled, forceNoSoundEnabled, @@ -100,7 +90,7 @@ CommandLineOptions returnCommandLineParser( const MyQApplication& application ) forceRemoveManifestEnabled, resetSettingsEnabled }; - LOG( INFO ) << "Command line arguments processed."; + qInfo() << "Command line arguments processed."; return commandLineArgs; } @@ -131,14 +121,14 @@ void installApplicationManifest( const std::string manifestPath ) if ( vr::VRApplications()->IsApplicationInstalled( application_strings::applicationKey ) ) { - LOG( INFO ) << "Manifest Is already Installed for Key " - << application_strings::applicationKey; + qInfo() << "Manifest Is already Installed for Key " + << application_strings::applicationKey; } else { const auto app_error = vr::VRApplications()->AddApplicationManifest( manifestPath.c_str() ); - LOG( INFO ) << "Manifest Installed at: " << manifestPath; + qInfo() << "Manifest Installed at: " << manifestPath; if ( app_error != vr::VRApplicationError_None ) { throw std::runtime_error( @@ -157,18 +147,18 @@ void removeApplicationManifest( const std::string manifestPath ) application_strings::applicationKey ) ) { vr::VRApplications()->RemoveApplicationManifest( manifestPath.c_str() ); - LOG( INFO ) << "Attempting to Remove Manifest At: " << manifestPath; + qInfo() << "Attempting to Remove Manifest At: " << manifestPath; } if ( vr::VRApplications()->IsApplicationInstalled( application_strings::applicationKey ) ) { - LOG( ERROR ) << "Removal Failed, run Advanced Settings from previous " - "install directory OR manually delete it in Steam " - "install at Steam\\config\\appconfig.json"; + qCritical() << "Removal Failed, run Advanced Settings from previous " + "install directory OR manually delete it in Steam " + "install at Steam\\config\\appconfig.json"; } else { - LOG( INFO ) << "Manifest Removed Successfully"; + qInfo() << "Manifest Removed Successfully"; } } @@ -178,7 +168,7 @@ void reinstallApplicationManifest( const std::string manifestPath ) if ( vr::VRApplications()->IsApplicationInstalled( application_strings::applicationKey ) ) { - LOG( INFO ) << "Manifest Previously Installed"; + qInfo() << "Manifest Previously Installed"; // String size was arbitrarily chosen by original author. constexpr auto kStringSize = 1024; char oldApplicationWorkingDir[kStringSize] = { 0 }; @@ -246,7 +236,7 @@ void forceRemoveApplicationManifest() } else { - LOG( INFO ) << "No Manifest Installed"; + qInfo() << "No Manifest Installed"; } } @@ -278,18 +268,18 @@ void forceRemoveApplicationManifest() { reinstallApplicationManifest( *manifestPath ); enableApplicationAutostart(); - LOG( INFO ) << "Manifest reinstalled."; + qInfo() << "Manifest reinstalled."; } else if ( removeManifest ) { forceRemoveApplicationManifest(); - LOG( INFO ) << "Manifest removed."; + qInfo() << "Manifest removed."; } } catch ( std::exception& e ) { exit_code = ReturnErrorCode::GENERAL_FAILURE; - LOG( ERROR ) << e.what(); + qCritical() << e.what(); } vr::VR_Shutdown(); @@ -299,57 +289,7 @@ void forceRemoveApplicationManifest() void setUpLogging() { - el::Loggers::addFlag( el::LoggingFlag::DisableApplicationAbortOnFatalLog ); - - el::Configurations conf; - conf.setToDefault(); - - using el::ConfigurationType; - using el::Level; - - conf.set( Level::Global, - ConfigurationType::Format, - "[%level] %datetime{%Y-%M-%d %H:%m:%s}: %msg" ); - constexpr auto logFileName = "AdvancedSettings.log"; - conf.set( Level::Global, ConfigurationType::Filename, logFileName ); - - constexpr auto confEnabled = "true"; - conf.set( Level::Global, ConfigurationType::Enabled, confEnabled ); - conf.set( Level::Global, ConfigurationType::ToFile, confEnabled ); - conf.set( Level::Global, ConfigurationType::ToStandardOutput, confEnabled ); - - constexpr auto TwoMegabytesInBytes = "2097152"; - conf.set( - Level::Global, ConfigurationType::MaxLogFileSize, TwoMegabytesInBytes ); - - constexpr auto confDisabled = "false"; - conf.set( Level::Trace, ConfigurationType::Enabled, confDisabled ); - - if constexpr ( debugLoggingEnabled ) - { - conf.set( Level::Debug, ConfigurationType::Enabled, confEnabled ); - } - else - { - conf.set( Level::Debug, ConfigurationType::Enabled, confDisabled ); - } - - const auto appDataLocation - = std::string( "/" ) + application_strings::applicationOrganizationName - + "/"; - const auto logFilePath - = QDir( QString::fromStdString( *paths::settingsDirectory() ) - + appDataLocation.c_str() ) - .absoluteFilePath( logFileName ); - conf.set( el::Level::Global, - el::ConfigurationType::Filename, - QDir::toNativeSeparators( logFilePath ).toStdString() ); - - conf.setRemainingToDefault(); - - el::Loggers::reconfigureAllLoggers( conf ); - - LOG( INFO ) << "Application started (Version " - << application_strings::applicationVersionString << ")"; - LOG( INFO ) << "Log File: " << logFilePath; + f = fopen( "AdvancedSettings.log", "a" ); + qSetMessagePattern("[%{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] %{time process}: %{message}"); + originalMessageHandler = qInstallMessageHandler( mainQtMessageHandler ); } diff --git a/src/utils/setup.h b/src/utils/setup.h index 9d4fd63c..2730a22b 100644 --- a/src/utils/setup.h +++ b/src/utils/setup.h @@ -8,7 +8,8 @@ #include #include #include -#include +#include +#include #include "../openvr/openvr_init.h" enum ReturnErrorCode @@ -55,8 +56,8 @@ class MyQApplication : public QApplication } catch ( std::exception& e ) { - LOG( ERROR ) << "Exception thrown from an event handler: " - << e.what(); + qCritical() << "Exception thrown from an event handler: " + << e.what(); } return false; } diff --git a/third-party/easylogging++/LICENSE-MIT b/third-party/easylogging++/LICENSE-MIT deleted file mode 100644 index 302737da..00000000 --- a/third-party/easylogging++/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2012-2018 Zuhd Web Services -Copyright (c) 2012-2018 @abumusamq - -https://github.com/zuhd-org/ -https://zuhd.org -https://muflihun.com - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/third-party/easylogging++/easylogging++.cc b/third-party/easylogging++/easylogging++.cc deleted file mode 100644 index 686e695e..00000000 --- a/third-party/easylogging++/easylogging++.cc +++ /dev/null @@ -1,3122 +0,0 @@ -// -// Bismillah ar-Rahmaan ar-Raheem -// -// Easylogging++ v9.96.7 -// Cross-platform logging library for C++ applications -// -// Copyright (c) 2012-2018 Amrayn Web Services -// Copyright (c) 2012-2018 @abumusamq -// -// This library is released under the MIT Licence. -// https://github.com/amrayn/easyloggingpp/blob/master/LICENSE -// -// https://amrayn.com -// http://muflihun.com -// - -#include "easylogging++.h" - -#if defined(AUTO_INITIALIZE_EASYLOGGINGPP) -INITIALIZE_EASYLOGGINGPP -#endif - -namespace el { - -// el::base -namespace base { -// el::base::consts -namespace consts { - -// Level log values - These are values that are replaced in place of %level format specifier -// Extra spaces after format specifiers are only for readability purposes in log files -static const base::type::char_t* kInfoLevelLogValue = ELPP_LITERAL("INFO"); -static const base::type::char_t* kDebugLevelLogValue = ELPP_LITERAL("DEBUG"); -static const base::type::char_t* kWarningLevelLogValue = ELPP_LITERAL("WARNING"); -static const base::type::char_t* kErrorLevelLogValue = ELPP_LITERAL("ERROR"); -static const base::type::char_t* kFatalLevelLogValue = ELPP_LITERAL("FATAL"); -static const base::type::char_t* kVerboseLevelLogValue = - ELPP_LITERAL("VERBOSE"); // will become VERBOSE-x where x = verbose level -static const base::type::char_t* kTraceLevelLogValue = ELPP_LITERAL("TRACE"); -static const base::type::char_t* kInfoLevelShortLogValue = ELPP_LITERAL("I"); -static const base::type::char_t* kDebugLevelShortLogValue = ELPP_LITERAL("D"); -static const base::type::char_t* kWarningLevelShortLogValue = ELPP_LITERAL("W"); -static const base::type::char_t* kErrorLevelShortLogValue = ELPP_LITERAL("E"); -static const base::type::char_t* kFatalLevelShortLogValue = ELPP_LITERAL("F"); -static const base::type::char_t* kVerboseLevelShortLogValue = ELPP_LITERAL("V"); -static const base::type::char_t* kTraceLevelShortLogValue = ELPP_LITERAL("T"); -// Format specifiers - These are used to define log format -static const base::type::char_t* kAppNameFormatSpecifier = ELPP_LITERAL("%app"); -static const base::type::char_t* kLoggerIdFormatSpecifier = ELPP_LITERAL("%logger"); -static const base::type::char_t* kThreadIdFormatSpecifier = ELPP_LITERAL("%thread"); -static const base::type::char_t* kSeverityLevelFormatSpecifier = ELPP_LITERAL("%level"); -static const base::type::char_t* kSeverityLevelShortFormatSpecifier = ELPP_LITERAL("%levshort"); -static const base::type::char_t* kDateTimeFormatSpecifier = ELPP_LITERAL("%datetime"); -static const base::type::char_t* kLogFileFormatSpecifier = ELPP_LITERAL("%file"); -static const base::type::char_t* kLogFileBaseFormatSpecifier = ELPP_LITERAL("%fbase"); -static const base::type::char_t* kLogLineFormatSpecifier = ELPP_LITERAL("%line"); -static const base::type::char_t* kLogLocationFormatSpecifier = ELPP_LITERAL("%loc"); -static const base::type::char_t* kLogFunctionFormatSpecifier = ELPP_LITERAL("%func"); -static const base::type::char_t* kCurrentUserFormatSpecifier = ELPP_LITERAL("%user"); -static const base::type::char_t* kCurrentHostFormatSpecifier = ELPP_LITERAL("%host"); -static const base::type::char_t* kMessageFormatSpecifier = ELPP_LITERAL("%msg"); -static const base::type::char_t* kVerboseLevelFormatSpecifier = ELPP_LITERAL("%vlevel"); -static const char* kDateTimeFormatSpecifierForFilename = "%datetime"; -// Date/time -static const char* kDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; -static const char* kDaysAbbrev[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; -static const char* kMonths[12] = { "January", "February", "March", "April", "May", "June", "July", "August", - "September", "October", "November", "December" - }; -static const char* kMonthsAbbrev[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; -static const char* kDefaultDateTimeFormat = "%Y-%M-%d %H:%m:%s,%g"; -static const char* kDefaultDateTimeFormatInFilename = "%Y-%M-%d_%H-%m"; -static const int kYearBase = 1900; -static const char* kAm = "AM"; -static const char* kPm = "PM"; -// Miscellaneous constants - -static const char* kNullPointer = "nullptr"; -#if ELPP_VARIADIC_TEMPLATES_SUPPORTED -#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED -static const base::type::VerboseLevel kMaxVerboseLevel = 9; -static const char* kUnknownUser = "unknown-user"; -static const char* kUnknownHost = "unknown-host"; - - -//---------------- DEFAULT LOG FILE ----------------------- - -#if defined(ELPP_NO_DEFAULT_LOG_FILE) -# if ELPP_OS_UNIX -static const char* kDefaultLogFile = "/dev/null"; -# elif ELPP_OS_WINDOWS -static const char* kDefaultLogFile = "nul"; -# endif // ELPP_OS_UNIX -#elif defined(ELPP_DEFAULT_LOG_FILE) -static const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE; -#else -static const char* kDefaultLogFile = "myeasylog.log"; -#endif // defined(ELPP_NO_DEFAULT_LOG_FILE) - - -#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) -static const char* kDefaultLogFileParam = "--default-log-file"; -#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) -#if defined(ELPP_LOGGING_FLAGS_FROM_ARG) -static const char* kLoggingFlagsParam = "--logging-flags"; -#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG) -static const char* kValidLoggerIdSymbols = - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._"; -static const char* kConfigurationComment = "##"; -static const char* kConfigurationLevel = "*"; -static const char* kConfigurationLoggerId = "--"; -} -// el::base::utils -namespace utils { - -/// @brief Aborts application due with user-defined status -static void abort(int status, const std::string& reason) { - // Both status and reason params are there for debugging with tools like gdb etc - ELPP_UNUSED(status); - ELPP_UNUSED(reason); -#if defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG) - // Ignore msvc critical error dialog - break instead (on debug mode) - _asm int 3 -#else - ::abort(); -#endif // defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG) -} - -} // namespace utils -} // namespace base - -// el - -// LevelHelper - -const char* LevelHelper::convertToString(Level level) { - // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. - if (level == Level::Global) return "GLOBAL"; - if (level == Level::Debug) return "DEBUG"; - if (level == Level::Info) return "INFO"; - if (level == Level::Warning) return "WARNING"; - if (level == Level::Error) return "ERROR"; - if (level == Level::Fatal) return "FATAL"; - if (level == Level::Verbose) return "VERBOSE"; - if (level == Level::Trace) return "TRACE"; - return "UNKNOWN"; -} - -struct StringToLevelItem { - const char* levelString; - Level level; -}; - -static struct StringToLevelItem stringToLevelMap[] = { - { "global", Level::Global }, - { "debug", Level::Debug }, - { "info", Level::Info }, - { "warning", Level::Warning }, - { "error", Level::Error }, - { "fatal", Level::Fatal }, - { "verbose", Level::Verbose }, - { "trace", Level::Trace } -}; - -Level LevelHelper::convertFromString(const char* levelStr) { - for (auto& item : stringToLevelMap) { - if (base::utils::Str::cStringCaseEq(levelStr, item.levelString)) { - return item.level; - } - } - return Level::Unknown; -} - -void LevelHelper::forEachLevel(base::type::EnumType* startIndex, const std::function& fn) { - base::type::EnumType lIndexMax = LevelHelper::kMaxValid; - do { - if (fn()) { - break; - } - *startIndex = static_cast(*startIndex << 1); - } while (*startIndex <= lIndexMax); -} - -// ConfigurationTypeHelper - -const char* ConfigurationTypeHelper::convertToString(ConfigurationType configurationType) { - // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. - if (configurationType == ConfigurationType::Enabled) return "ENABLED"; - if (configurationType == ConfigurationType::Filename) return "FILENAME"; - if (configurationType == ConfigurationType::Format) return "FORMAT"; - if (configurationType == ConfigurationType::ToFile) return "TO_FILE"; - if (configurationType == ConfigurationType::ToStandardOutput) return "TO_STANDARD_OUTPUT"; - if (configurationType == ConfigurationType::SubsecondPrecision) return "SUBSECOND_PRECISION"; - if (configurationType == ConfigurationType::PerformanceTracking) return "PERFORMANCE_TRACKING"; - if (configurationType == ConfigurationType::MaxLogFileSize) return "MAX_LOG_FILE_SIZE"; - if (configurationType == ConfigurationType::LogFlushThreshold) return "LOG_FLUSH_THRESHOLD"; - return "UNKNOWN"; -} - -struct ConfigurationStringToTypeItem { - const char* configString; - ConfigurationType configType; -}; - -static struct ConfigurationStringToTypeItem configStringToTypeMap[] = { - { "enabled", ConfigurationType::Enabled }, - { "to_file", ConfigurationType::ToFile }, - { "to_standard_output", ConfigurationType::ToStandardOutput }, - { "format", ConfigurationType::Format }, - { "filename", ConfigurationType::Filename }, - { "subsecond_precision", ConfigurationType::SubsecondPrecision }, - { "milliseconds_width", ConfigurationType::MillisecondsWidth }, - { "performance_tracking", ConfigurationType::PerformanceTracking }, - { "max_log_file_size", ConfigurationType::MaxLogFileSize }, - { "log_flush_threshold", ConfigurationType::LogFlushThreshold }, -}; - -ConfigurationType ConfigurationTypeHelper::convertFromString(const char* configStr) { - for (auto& item : configStringToTypeMap) { - if (base::utils::Str::cStringCaseEq(configStr, item.configString)) { - return item.configType; - } - } - return ConfigurationType::Unknown; -} - -void ConfigurationTypeHelper::forEachConfigType(base::type::EnumType* startIndex, const std::function& fn) { - base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid; - do { - if (fn()) { - break; - } - *startIndex = static_cast(*startIndex << 1); - } while (*startIndex <= cIndexMax); -} - -// Configuration - -Configuration::Configuration(const Configuration& c) : - m_level(c.m_level), - m_configurationType(c.m_configurationType), - m_value(c.m_value) { -} - -Configuration& Configuration::operator=(const Configuration& c) { - if (&c != this) { - m_level = c.m_level; - m_configurationType = c.m_configurationType; - m_value = c.m_value; - } - return *this; -} - -/// @brief Full constructor used to sets value of configuration -Configuration::Configuration(Level level, ConfigurationType configurationType, const std::string& value) : - m_level(level), - m_configurationType(configurationType), - m_value(value) { -} - -void Configuration::log(el::base::type::ostream_t& os) const { - os << LevelHelper::convertToString(m_level) - << ELPP_LITERAL(" ") << ConfigurationTypeHelper::convertToString(m_configurationType) - << ELPP_LITERAL(" = ") << m_value.c_str(); -} - -/// @brief Used to find configuration from configuration (pointers) repository. Avoid using it. -Configuration::Predicate::Predicate(Level level, ConfigurationType configurationType) : - m_level(level), - m_configurationType(configurationType) { -} - -bool Configuration::Predicate::operator()(const Configuration* conf) const { - return ((conf != nullptr) && (conf->level() == m_level) && (conf->configurationType() == m_configurationType)); -} - -// Configurations - -Configurations::Configurations(void) : - m_configurationFile(std::string()), - m_isFromFile(false) { -} - -Configurations::Configurations(const std::string& configurationFile, bool useDefaultsForRemaining, - Configurations* base) : - m_configurationFile(configurationFile), - m_isFromFile(false) { - parseFromFile(configurationFile, base); - if (useDefaultsForRemaining) { - setRemainingToDefault(); - } -} - -bool Configurations::parseFromFile(const std::string& configurationFile, Configurations* base) { - // We initial assertion with true because if we have assertion disabled, we want to pass this - // check and if assertion is enabled we will have values re-assigned any way. - bool assertionPassed = true; - ELPP_ASSERT((assertionPassed = base::utils::File::pathExists(configurationFile.c_str(), true)) == true, - "Configuration file [" << configurationFile << "] does not exist!"); - if (!assertionPassed) { - return false; - } - bool success = Parser::parseFromFile(configurationFile, this, base); - m_isFromFile = success; - return success; -} - -bool Configurations::parseFromText(const std::string& configurationsString, Configurations* base) { - bool success = Parser::parseFromText(configurationsString, this, base); - if (success) { - m_isFromFile = false; - } - return success; -} - -void Configurations::setFromBase(Configurations* base) { - if (base == nullptr || base == this) { - return; - } - base::threading::ScopedLock scopedLock(base->lock()); - for (Configuration*& conf : base->list()) { - set(conf); - } -} - -bool Configurations::hasConfiguration(ConfigurationType configurationType) { - base::type::EnumType lIndex = LevelHelper::kMinValid; - bool result = false; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - if (hasConfiguration(LevelHelper::castFromInt(lIndex), configurationType)) { - result = true; - } - return result; - }); - return result; -} - -bool Configurations::hasConfiguration(Level level, ConfigurationType configurationType) { - base::threading::ScopedLock scopedLock(lock()); -#if ELPP_COMPILER_INTEL - // We cant specify template types here, Intel C++ throws compilation error - // "error: type name is not allowed" - return RegistryWithPred::get(level, configurationType) != nullptr; -#else - return RegistryWithPred::get(level, configurationType) != nullptr; -#endif // ELPP_COMPILER_INTEL -} - -void Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) { - base::threading::ScopedLock scopedLock(lock()); - unsafeSet(level, configurationType, value); // This is not unsafe anymore as we have locked mutex - if (level == Level::Global) { - unsafeSetGlobally(configurationType, value, false); // Again this is not unsafe either - } -} - -void Configurations::set(Configuration* conf) { - if (conf == nullptr) { - return; - } - set(conf->level(), conf->configurationType(), conf->value()); -} - -void Configurations::setToDefault(void) { - setGlobally(ConfigurationType::Enabled, std::string("true"), true); - setGlobally(ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile), true); -#if defined(ELPP_NO_LOG_TO_FILE) - setGlobally(ConfigurationType::ToFile, std::string("false"), true); -#else - setGlobally(ConfigurationType::ToFile, std::string("true"), true); -#endif // defined(ELPP_NO_LOG_TO_FILE) - setGlobally(ConfigurationType::ToStandardOutput, std::string("true"), true); - setGlobally(ConfigurationType::SubsecondPrecision, std::string("3"), true); - setGlobally(ConfigurationType::PerformanceTracking, std::string("true"), true); - setGlobally(ConfigurationType::MaxLogFileSize, std::string("0"), true); - setGlobally(ConfigurationType::LogFlushThreshold, std::string("0"), true); - - setGlobally(ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"), true); - set(Level::Debug, ConfigurationType::Format, - std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg")); - // INFO and WARNING are set to default by Level::Global - set(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - set(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - set(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg")); - set(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg")); -} - -void Configurations::setRemainingToDefault(void) { - base::threading::ScopedLock scopedLock(lock()); -#if defined(ELPP_NO_LOG_TO_FILE) - unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("false")); -#else - unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("true")); -#endif // defined(ELPP_NO_LOG_TO_FILE) - unsafeSetIfNotExist(Level::Global, ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile)); - unsafeSetIfNotExist(Level::Global, ConfigurationType::ToStandardOutput, std::string("true")); - unsafeSetIfNotExist(Level::Global, ConfigurationType::SubsecondPrecision, std::string("3")); - unsafeSetIfNotExist(Level::Global, ConfigurationType::PerformanceTracking, std::string("true")); - unsafeSetIfNotExist(Level::Global, ConfigurationType::MaxLogFileSize, std::string("0")); - unsafeSetIfNotExist(Level::Global, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - unsafeSetIfNotExist(Level::Debug, ConfigurationType::Format, - std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg")); - // INFO and WARNING are set to default by Level::Global - unsafeSetIfNotExist(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - unsafeSetIfNotExist(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - unsafeSetIfNotExist(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg")); - unsafeSetIfNotExist(Level::Trace, ConfigurationType::Format, - std::string("%datetime %level [%logger] [%func] [%loc] %msg")); -} - -bool Configurations::Parser::parseFromFile(const std::string& configurationFile, Configurations* sender, - Configurations* base) { - sender->setFromBase(base); - std::ifstream fileStream_(configurationFile.c_str(), std::ifstream::in); - ELPP_ASSERT(fileStream_.is_open(), "Unable to open configuration file [" << configurationFile << "] for parsing."); - bool parsedSuccessfully = false; - std::string line = std::string(); - Level currLevel = Level::Unknown; - std::string currConfigStr = std::string(); - std::string currLevelStr = std::string(); - while (fileStream_.good()) { - std::getline(fileStream_, line); - parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender); - ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line); - } - return parsedSuccessfully; -} - -bool Configurations::Parser::parseFromText(const std::string& configurationsString, Configurations* sender, - Configurations* base) { - sender->setFromBase(base); - bool parsedSuccessfully = false; - std::stringstream ss(configurationsString); - std::string line = std::string(); - Level currLevel = Level::Unknown; - std::string currConfigStr = std::string(); - std::string currLevelStr = std::string(); - while (std::getline(ss, line)) { - parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender); - ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line); - } - return parsedSuccessfully; -} - -void Configurations::Parser::ignoreComments(std::string* line) { - std::size_t foundAt = 0; - std::size_t quotesStart = line->find("\""); - std::size_t quotesEnd = std::string::npos; - if (quotesStart != std::string::npos) { - quotesEnd = line->find("\"", quotesStart + 1); - while (quotesEnd != std::string::npos && line->at(quotesEnd - 1) == '\\') { - // Do not erase slash yet - we will erase it in parseLine(..) while loop - quotesEnd = line->find("\"", quotesEnd + 2); - } - } - if ((foundAt = line->find(base::consts::kConfigurationComment)) != std::string::npos) { - if (foundAt < quotesEnd) { - foundAt = line->find(base::consts::kConfigurationComment, quotesEnd + 1); - } - *line = line->substr(0, foundAt); - } -} - -bool Configurations::Parser::isLevel(const std::string& line) { - return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLevel)); -} - -bool Configurations::Parser::isComment(const std::string& line) { - return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationComment)); -} - -bool Configurations::Parser::isConfig(const std::string& line) { - std::size_t assignment = line.find('='); - return line != "" && - ((line[0] >= 'A' && line[0] <= 'Z') || (line[0] >= 'a' && line[0] <= 'z')) && - (assignment != std::string::npos) && - (line.size() > assignment); -} - -bool Configurations::Parser::parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, - Level* currLevel, - Configurations* conf) { - ConfigurationType currConfig = ConfigurationType::Unknown; - std::string currValue = std::string(); - *line = base::utils::Str::trim(*line); - if (isComment(*line)) return true; - ignoreComments(line); - *line = base::utils::Str::trim(*line); - if (line->empty()) { - // Comment ignored - return true; - } - if (isLevel(*line)) { - if (line->size() <= 2) { - return true; - } - *currLevelStr = line->substr(1, line->size() - 2); - *currLevelStr = base::utils::Str::toUpper(*currLevelStr); - *currLevelStr = base::utils::Str::trim(*currLevelStr); - *currLevel = LevelHelper::convertFromString(currLevelStr->c_str()); - return true; - } - if (isConfig(*line)) { - std::size_t assignment = line->find('='); - *currConfigStr = line->substr(0, assignment); - *currConfigStr = base::utils::Str::toUpper(*currConfigStr); - *currConfigStr = base::utils::Str::trim(*currConfigStr); - currConfig = ConfigurationTypeHelper::convertFromString(currConfigStr->c_str()); - currValue = line->substr(assignment + 1); - currValue = base::utils::Str::trim(currValue); - std::size_t quotesStart = currValue.find("\"", 0); - std::size_t quotesEnd = std::string::npos; - if (quotesStart != std::string::npos) { - quotesEnd = currValue.find("\"", quotesStart + 1); - while (quotesEnd != std::string::npos && currValue.at(quotesEnd - 1) == '\\') { - currValue = currValue.erase(quotesEnd - 1, 1); - quotesEnd = currValue.find("\"", quotesEnd + 2); - } - } - if (quotesStart != std::string::npos && quotesEnd != std::string::npos) { - // Quote provided - check and strip if valid - ELPP_ASSERT((quotesStart < quotesEnd), "Configuration error - No ending quote found in [" - << currConfigStr << "]"); - ELPP_ASSERT((quotesStart + 1 != quotesEnd), "Empty configuration value for [" << currConfigStr << "]"); - if ((quotesStart != quotesEnd) && (quotesStart + 1 != quotesEnd)) { - // Explicit check in case if assertion is disabled - currValue = currValue.substr(quotesStart + 1, quotesEnd - 1); - } - } - } - ELPP_ASSERT(*currLevel != Level::Unknown, "Unrecognized severity level [" << *currLevelStr << "]"); - ELPP_ASSERT(currConfig != ConfigurationType::Unknown, "Unrecognized configuration [" << *currConfigStr << "]"); - if (*currLevel == Level::Unknown || currConfig == ConfigurationType::Unknown) { - return false; // unrecognizable level or config - } - conf->set(*currLevel, currConfig, currValue); - return true; -} - -void Configurations::unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value) { - Configuration* conf = RegistryWithPred::get(level, configurationType); - if (conf == nullptr) { - unsafeSet(level, configurationType, value); - } -} - -void Configurations::unsafeSet(Level level, ConfigurationType configurationType, const std::string& value) { - Configuration* conf = RegistryWithPred::get(level, configurationType); - if (conf == nullptr) { - registerNew(new Configuration(level, configurationType, value)); - } else { - conf->setValue(value); - } - if (level == Level::Global) { - unsafeSetGlobally(configurationType, value, false); - } -} - -void Configurations::setGlobally(ConfigurationType configurationType, const std::string& value, - bool includeGlobalLevel) { - if (includeGlobalLevel) { - set(Level::Global, configurationType, value); - } - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - set(LevelHelper::castFromInt(lIndex), configurationType, value); - return false; // Do not break lambda function yet as we need to set all levels regardless - }); -} - -void Configurations::unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, - bool includeGlobalLevel) { - if (includeGlobalLevel) { - unsafeSet(Level::Global, configurationType, value); - } - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - unsafeSet(LevelHelper::castFromInt(lIndex), configurationType, value); - return false; // Do not break lambda function yet as we need to set all levels regardless - }); -} - -// LogBuilder - -void LogBuilder::convertToColoredOutput(base::type::string_t* logLine, Level level) { - if (!m_termSupportsColor) return; - const base::type::char_t* resetColor = ELPP_LITERAL("\x1b[0m"); - if (level == Level::Error || level == Level::Fatal) - *logLine = ELPP_LITERAL("\x1b[31m") + *logLine + resetColor; - else if (level == Level::Warning) - *logLine = ELPP_LITERAL("\x1b[33m") + *logLine + resetColor; - else if (level == Level::Debug) - *logLine = ELPP_LITERAL("\x1b[32m") + *logLine + resetColor; - else if (level == Level::Info) - *logLine = ELPP_LITERAL("\x1b[36m") + *logLine + resetColor; - else if (level == Level::Trace) - *logLine = ELPP_LITERAL("\x1b[35m") + *logLine + resetColor; -} - -// Logger - -Logger::Logger(const std::string& id, base::LogStreamsReferenceMapPtr logStreamsReference) : - m_id(id), - m_typedConfigurations(nullptr), - m_parentApplicationName(std::string()), - m_isConfigured(false), - m_logStreamsReference(logStreamsReference) { - initUnflushedCount(); -} - -Logger::Logger(const std::string& id, const Configurations& configurations, - base::LogStreamsReferenceMapPtr logStreamsReference) : - m_id(id), - m_typedConfigurations(nullptr), - m_parentApplicationName(std::string()), - m_isConfigured(false), - m_logStreamsReference(logStreamsReference) { - initUnflushedCount(); - configure(configurations); -} - -Logger::Logger(const Logger& logger) { - base::utils::safeDelete(m_typedConfigurations); - m_id = logger.m_id; - m_typedConfigurations = logger.m_typedConfigurations; - m_parentApplicationName = logger.m_parentApplicationName; - m_isConfigured = logger.m_isConfigured; - m_configurations = logger.m_configurations; - m_unflushedCount = logger.m_unflushedCount; - m_logStreamsReference = logger.m_logStreamsReference; -} - -Logger& Logger::operator=(const Logger& logger) { - if (&logger != this) { - base::utils::safeDelete(m_typedConfigurations); - m_id = logger.m_id; - m_typedConfigurations = logger.m_typedConfigurations; - m_parentApplicationName = logger.m_parentApplicationName; - m_isConfigured = logger.m_isConfigured; - m_configurations = logger.m_configurations; - m_unflushedCount = logger.m_unflushedCount; - m_logStreamsReference = logger.m_logStreamsReference; - } - return *this; -} - -void Logger::configure(const Configurations& configurations) { - m_isConfigured = false; // we set it to false in case if we fail - initUnflushedCount(); - if (m_typedConfigurations != nullptr) { - Configurations* c = const_cast(m_typedConfigurations->configurations()); - if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) { - flush(); - } - } - base::threading::ScopedLock scopedLock(lock()); - if (m_configurations != configurations) { - m_configurations.setFromBase(const_cast(&configurations)); - } - base::utils::safeDelete(m_typedConfigurations); - m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference); - resolveLoggerFormatSpec(); - m_isConfigured = true; -} - -void Logger::reconfigure(void) { - ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]"); - configure(m_configurations); -} - -bool Logger::isValidId(const std::string& id) { - for (std::string::const_iterator it = id.begin(); it != id.end(); ++it) { - if (!base::utils::Str::contains(base::consts::kValidLoggerIdSymbols, *it)) { - return false; - } - } - return true; -} - -void Logger::flush(void) { - ELPP_INTERNAL_INFO(3, "Flushing logger [" << m_id << "] all levels"); - base::threading::ScopedLock scopedLock(lock()); - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - flush(LevelHelper::castFromInt(lIndex), nullptr); - return false; - }); -} - -void Logger::flush(Level level, base::type::fstream_t* fs) { - if (fs == nullptr && m_typedConfigurations->toFile(level)) { - fs = m_typedConfigurations->fileStream(level); - } - if (fs != nullptr) { - fs->flush(); - std::unordered_map::iterator iter = m_unflushedCount.find(level); - if (iter != m_unflushedCount.end()) { - iter->second = 0; - } - Helpers::validateFileRolling(this, level); - } -} - -void Logger::initUnflushedCount(void) { - m_unflushedCount.clear(); - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - m_unflushedCount.insert(std::make_pair(LevelHelper::castFromInt(lIndex), 0)); - return false; - }); -} - -void Logger::resolveLoggerFormatSpec(void) const { - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - base::LogFormat* logFormat = - const_cast(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex))); - base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id); - return false; - }); -} - -// el::base -namespace base { - -// el::base::utils -namespace utils { - -// File - -base::type::fstream_t* File::newFileStream(const std::string& filename) { - base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(), - base::type::fstream_t::out -#if !defined(ELPP_FRESH_LOG_FILE) - | base::type::fstream_t::app -#endif - ); -#if defined(ELPP_UNICODE) - std::locale elppUnicodeLocale(""); -# if ELPP_OS_WINDOWS - std::locale elppUnicodeLocaleWindows(elppUnicodeLocale, new std::codecvt_utf8_utf16); - elppUnicodeLocale = elppUnicodeLocaleWindows; -# endif // ELPP_OS_WINDOWS - fs->imbue(elppUnicodeLocale); -#endif // defined(ELPP_UNICODE) - if (fs->is_open()) { - fs->flush(); - } else { - base::utils::safeDelete(fs); - ELPP_INTERNAL_ERROR("Bad file [" << filename << "]", true); - } - return fs; -} - -std::size_t File::getSizeOfFile(base::type::fstream_t* fs) { - if (fs == nullptr) { - return 0; - } - // Since the file stream is appended to or truncated, the current - // offset is the file size. - std::size_t size = static_cast(fs->tellg()); - return size; -} - -bool File::pathExists(const char* path, bool considerFile) { - if (path == nullptr) { - return false; - } -#if ELPP_OS_UNIX - ELPP_UNUSED(considerFile); - struct stat st; - return (stat(path, &st) == 0); -#elif ELPP_OS_WINDOWS - DWORD fileType = GetFileAttributesA(path); - if (fileType == INVALID_FILE_ATTRIBUTES) { - return false; - } - return considerFile ? true : ((fileType & FILE_ATTRIBUTE_DIRECTORY) == 0 ? false : true); -#endif // ELPP_OS_UNIX -} - -bool File::createPath(const std::string& path) { - if (path.empty()) { - return false; - } - if (base::utils::File::pathExists(path.c_str())) { - return true; - } - int status = -1; - - char* currPath = const_cast(path.c_str()); - std::string builtPath = std::string(); -#if ELPP_OS_UNIX - if (path[0] == '/') { - builtPath = "/"; - } - currPath = STRTOK(currPath, base::consts::kFilePathSeparator, 0); -#elif ELPP_OS_WINDOWS - // Use secure functions API - char* nextTok_ = nullptr; - currPath = STRTOK(currPath, base::consts::kFilePathSeparator, &nextTok_); - ELPP_UNUSED(nextTok_); -#endif // ELPP_OS_UNIX - while (currPath != nullptr) { - builtPath.append(currPath); - builtPath.append(base::consts::kFilePathSeparator); -#if ELPP_OS_UNIX - status = mkdir(builtPath.c_str(), ELPP_LOG_PERMS); - currPath = STRTOK(nullptr, base::consts::kFilePathSeparator, 0); -#elif ELPP_OS_WINDOWS - status = _mkdir(builtPath.c_str()); - currPath = STRTOK(nullptr, base::consts::kFilePathSeparator, &nextTok_); -#endif // ELPP_OS_UNIX - } - if (status == -1) { - ELPP_INTERNAL_ERROR("Error while creating path [" << path << "]", true); - return false; - } - return true; -} - -std::string File::extractPathFromFilename(const std::string& fullPath, const char* separator) { - if ((fullPath == "") || (fullPath.find(separator) == std::string::npos)) { - return fullPath; - } - std::size_t lastSlashAt = fullPath.find_last_of(separator); - if (lastSlashAt == 0) { - return std::string(separator); - } - return fullPath.substr(0, lastSlashAt + 1); -} - -void File::buildStrippedFilename(const char* filename, char buff[], std::size_t limit) { - std::size_t sizeOfFilename = strlen(filename); - if (sizeOfFilename >= limit) { - filename += (sizeOfFilename - limit); - if (filename[0] != '.' && filename[1] != '.') { // prepend if not already - filename += 3; // 3 = '..' - STRCAT(buff, "..", limit); - } - } - STRCAT(buff, filename, limit); -} - -void File::buildBaseFilename(const std::string& fullPath, char buff[], std::size_t limit, const char* separator) { - const char *filename = fullPath.c_str(); - std::size_t lastSlashAt = fullPath.find_last_of(separator); - filename += lastSlashAt ? lastSlashAt+1 : 0; - std::size_t sizeOfFilename = strlen(filename); - if (sizeOfFilename >= limit) { - filename += (sizeOfFilename - limit); - if (filename[0] != '.' && filename[1] != '.') { // prepend if not already - filename += 3; // 3 = '..' - STRCAT(buff, "..", limit); - } - } - STRCAT(buff, filename, limit); -} - -// Str - -bool Str::wildCardMatch(const char* str, const char* pattern) { - while (*pattern) { - switch (*pattern) { - case '?': - if (!*str) - return false; - ++str; - ++pattern; - break; - case '*': - if (wildCardMatch(str, pattern + 1)) - return true; - if (*str && wildCardMatch(str + 1, pattern)) - return true; - return false; - default: - if (*str++ != *pattern++) - return false; - break; - } - } - return !*str && !*pattern; -} - -std::string& Str::ltrim(std::string& str) { - str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](char c) { - return !std::isspace(c); - } )); - return str; -} - -std::string& Str::rtrim(std::string& str) { - str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) { - return !std::isspace(c); - }).base(), str.end()); - return str; -} - -std::string& Str::trim(std::string& str) { - return ltrim(rtrim(str)); -} - -bool Str::startsWith(const std::string& str, const std::string& start) { - return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0); -} - -bool Str::endsWith(const std::string& str, const std::string& end) { - return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0); -} - -std::string& Str::replaceAll(std::string& str, char replaceWhat, char replaceWith) { - std::replace(str.begin(), str.end(), replaceWhat, replaceWith); - return str; -} - -std::string& Str::replaceAll(std::string& str, const std::string& replaceWhat, - const std::string& replaceWith) { - if (replaceWhat == replaceWith) - return str; - std::size_t foundAt = std::string::npos; - while ((foundAt = str.find(replaceWhat, foundAt + 1)) != std::string::npos) { - str.replace(foundAt, replaceWhat.length(), replaceWith); - } - return str; -} - -void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, - const base::type::string_t& replaceWith) { - std::size_t foundAt = base::type::string_t::npos; - while ((foundAt = str.find(replaceWhat, foundAt + 1)) != base::type::string_t::npos) { - if (foundAt > 0 && str[foundAt - 1] == base::consts::kFormatSpecifierChar) { - str.erase(foundAt - 1, 1); - ++foundAt; - } else { - str.replace(foundAt, replaceWhat.length(), replaceWith); - return; - } - } -} -#if defined(ELPP_UNICODE) -void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, - const std::string& replaceWith) { - replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end())); -} -#endif // defined(ELPP_UNICODE) - -std::string& Str::toUpper(std::string& str) { - std::transform(str.begin(), str.end(), str.begin(), - [](char c) { - return static_cast(::toupper(c)); - }); - return str; -} - -bool Str::cStringEq(const char* s1, const char* s2) { - if (s1 == nullptr && s2 == nullptr) return true; - if (s1 == nullptr || s2 == nullptr) return false; - return strcmp(s1, s2) == 0; -} - -bool Str::cStringCaseEq(const char* s1, const char* s2) { - if (s1 == nullptr && s2 == nullptr) return true; - if (s1 == nullptr || s2 == nullptr) return false; - - // With thanks to cygwin for this code - int d = 0; - - while (true) { - const int c1 = toupper(*s1++); - const int c2 = toupper(*s2++); - - if (((d = c1 - c2) != 0) || (c2 == '\0')) { - break; - } - } - - return d == 0; -} - -bool Str::contains(const char* str, char c) { - for (; *str; ++str) { - if (*str == c) - return true; - } - return false; -} - -char* Str::convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded) { - char localBuff[10] = ""; - char* p = localBuff + sizeof(localBuff) - 2; - if (n > 0) { - for (; n > 0 && p > localBuff && len > 0; n /= 10, --len) - *--p = static_cast(n % 10 + '0'); - } else { - *--p = '0'; - --len; - } - if (zeroPadded) - while (p > localBuff && len-- > 0) *--p = static_cast('0'); - return addToBuff(p, buf, bufLim); -} - -char* Str::addToBuff(const char* str, char* buf, const char* bufLim) { - while ((buf < bufLim) && ((*buf = *str++) != '\0')) - ++buf; - return buf; -} - -char* Str::clearBuff(char buff[], std::size_t lim) { - STRCPY(buff, "", lim); - ELPP_UNUSED(lim); // For *nix we dont have anything using lim in above STRCPY macro - return buff; -} - -/// @brief Converts wchar* to char* -/// NOTE: Need to free return value after use! -char* Str::wcharPtrToCharPtr(const wchar_t* line) { - std::size_t len_ = wcslen(line) + 1; - char* buff_ = static_cast(malloc(len_ + 1)); -# if ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS) - std::wcstombs(buff_, line, len_); -# elif ELPP_OS_WINDOWS - std::size_t convCount_ = 0; - mbstate_t mbState_; - ::memset(static_cast(&mbState_), 0, sizeof(mbState_)); - wcsrtombs_s(&convCount_, buff_, len_, &line, len_, &mbState_); -# endif // ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS) - return buff_; -} - -// OS - -#if ELPP_OS_WINDOWS -/// @brief Gets environment variables for Windows based OS. -/// We are not using getenv(const char*) because of CRT deprecation -/// @param varname Variable name to get environment variable value for -/// @return If variable exist the value of it otherwise nullptr -const char* OS::getWindowsEnvironmentVariable(const char* varname) { - const DWORD bufferLen = 50; - static char buffer[bufferLen]; - if (GetEnvironmentVariableA(varname, buffer, bufferLen)) { - return buffer; - } - return nullptr; -} -#endif // ELPP_OS_WINDOWS -#if ELPP_OS_ANDROID -std::string OS::getProperty(const char* prop) { - char propVal[PROP_VALUE_MAX + 1]; - int ret = __system_property_get(prop, propVal); - return ret == 0 ? std::string() : std::string(propVal); -} - -std::string OS::getDeviceName(void) { - std::stringstream ss; - std::string manufacturer = getProperty("ro.product.manufacturer"); - std::string model = getProperty("ro.product.model"); - if (manufacturer.empty() || model.empty()) { - return std::string(); - } - ss << manufacturer << "-" << model; - return ss.str(); -} -#endif // ELPP_OS_ANDROID - -const std::string OS::getBashOutput(const char* command) { -#if (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN) - if (command == nullptr) { - return std::string(); - } - FILE* proc = nullptr; - if ((proc = popen(command, "r")) == nullptr) { - ELPP_INTERNAL_ERROR("\nUnable to run command [" << command << "]", true); - return std::string(); - } - char hBuff[4096]; - if (fgets(hBuff, sizeof(hBuff), proc) != nullptr) { - pclose(proc); - const std::size_t buffLen = strlen(hBuff); - if (buffLen > 0 && hBuff[buffLen - 1] == '\n') { - hBuff[buffLen - 1] = '\0'; - } - return std::string(hBuff); - } else { - pclose(proc); - } - return std::string(); -#else - ELPP_UNUSED(command); - return std::string(); -#endif // (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN) -} - -std::string OS::getEnvironmentVariable(const char* variableName, const char* defaultVal, - const char* alternativeBashCommand) { -#if ELPP_OS_UNIX - const char* val = getenv(variableName); -#elif ELPP_OS_WINDOWS - const char* val = getWindowsEnvironmentVariable(variableName); -#endif // ELPP_OS_UNIX - if ((val == nullptr) || ((strcmp(val, "") == 0))) { -#if ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH) - // Try harder on unix-based systems - std::string valBash = base::utils::OS::getBashOutput(alternativeBashCommand); - if (valBash.empty()) { - return std::string(defaultVal); - } else { - return valBash; - } -#elif ELPP_OS_WINDOWS || ELPP_OS_UNIX - ELPP_UNUSED(alternativeBashCommand); - return std::string(defaultVal); -#endif // ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH) - } - return std::string(val); -} - -std::string OS::currentUser(void) { -#if ELPP_OS_UNIX && !ELPP_OS_ANDROID - return getEnvironmentVariable("USER", base::consts::kUnknownUser, "whoami"); -#elif ELPP_OS_WINDOWS - return getEnvironmentVariable("USERNAME", base::consts::kUnknownUser); -#elif ELPP_OS_ANDROID - ELPP_UNUSED(base::consts::kUnknownUser); - return std::string("android"); -#else - return std::string(); -#endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID -} - -std::string OS::currentHost(void) { -#if ELPP_OS_UNIX && !ELPP_OS_ANDROID - return getEnvironmentVariable("HOSTNAME", base::consts::kUnknownHost, "hostname"); -#elif ELPP_OS_WINDOWS - return getEnvironmentVariable("COMPUTERNAME", base::consts::kUnknownHost); -#elif ELPP_OS_ANDROID - ELPP_UNUSED(base::consts::kUnknownHost); - return getDeviceName(); -#else - return std::string(); -#endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID -} - -bool OS::termSupportsColor(void) { - std::string term = getEnvironmentVariable("TERM", ""); - return term == "xterm" || term == "xterm-color" || term == "xterm-256color" - || term == "screen" || term == "linux" || term == "cygwin" - || term == "screen-256color"; -} - -// DateTime - -void DateTime::gettimeofday(struct timeval* tv) { -#if ELPP_OS_WINDOWS - if (tv != nullptr) { -# if ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS) - const unsigned __int64 delta_ = 11644473600000000Ui64; -# else - const unsigned __int64 delta_ = 11644473600000000ULL; -# endif // ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS) - const double secOffSet = 0.000001; - const unsigned long usecOffSet = 1000000; - FILETIME fileTime; - GetSystemTimeAsFileTime(&fileTime); - unsigned __int64 present = 0; - present |= fileTime.dwHighDateTime; - present = present << 32; - present |= fileTime.dwLowDateTime; - present /= 10; // mic-sec - // Subtract the difference - present -= delta_; - tv->tv_sec = static_cast(present * secOffSet); - tv->tv_usec = static_cast(present % usecOffSet); - } -#else - ::gettimeofday(tv, nullptr); -#endif // ELPP_OS_WINDOWS -} - -std::string DateTime::getDateTime(const char* format, const base::SubsecondPrecision* ssPrec) { - struct timeval currTime; - gettimeofday(&currTime); - return timevalToString(currTime, format, ssPrec); -} - -std::string DateTime::timevalToString(struct timeval tval, const char* format, - const el::base::SubsecondPrecision* ssPrec) { - struct ::tm timeInfo; - buildTimeInfo(&tval, &timeInfo); - const int kBuffSize = 30; - char buff_[kBuffSize] = ""; - parseFormat(buff_, kBuffSize, format, &timeInfo, static_cast(tval.tv_usec / ssPrec->m_offset), - ssPrec); - return std::string(buff_); -} - -base::type::string_t DateTime::formatTime(unsigned long long time, base::TimestampUnit timestampUnit) { - base::type::EnumType start = static_cast(timestampUnit); - const base::type::char_t* unit = base::consts::kTimeFormats[start].unit; - for (base::type::EnumType i = start; i < base::consts::kTimeFormatsCount - 1; ++i) { - if (time <= static_cast(base::consts::kTimeFormats[i].value)) { - break; - } - if (base::consts::kTimeFormats[i].value == 1000.0 && static_cast(time) / 1000.0f < 1.9f) { - break; - } - time /= static_cast(base::consts::kTimeFormats[i].value); - unit = base::consts::kTimeFormats[i + 1].unit; - } - base::type::stringstream_t ss; - ss << time << " " << unit; - return ss.str(); -} - -unsigned long long DateTime::getTimeDifference(const struct timeval& endTime, const struct timeval& startTime, - base::TimestampUnit timestampUnit) { - if (timestampUnit == base::TimestampUnit::Microsecond) { - return static_cast(static_cast(1000000 * endTime.tv_sec + endTime.tv_usec) - - static_cast(1000000 * startTime.tv_sec + startTime.tv_usec)); - } - // milliseconds - auto conv = [](const struct timeval& tim) { - return static_cast((tim.tv_sec * 1000) + (tim.tv_usec / 1000)); - }; - return static_cast(conv(endTime) - conv(startTime)); -} - -struct ::tm* DateTime::buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo) { -#if ELPP_OS_UNIX - time_t rawTime = currTime->tv_sec; - ::elpptime_r(&rawTime, timeInfo); - return timeInfo; -#else -# if ELPP_COMPILER_MSVC - ELPP_UNUSED(currTime); - time_t t; -# if defined(_USE_32BIT_TIME_T) - _time32(&t); -# else - _time64(&t); -# endif - elpptime_s(timeInfo, &t); - return timeInfo; -# else - // For any other compilers that don't have CRT warnings issue e.g, MinGW or TDM GCC- we use different method - time_t rawTime = currTime->tv_sec; - struct tm* tmInf = elpptime(&rawTime); - *timeInfo = *tmInf; - return timeInfo; -# endif // ELPP_COMPILER_MSVC -#endif // ELPP_OS_UNIX -} - -char* DateTime::parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo, - std::size_t msec, const base::SubsecondPrecision* ssPrec) { - const char* bufLim = buf + bufSz; - for (; *format; ++format) { - if (*format == base::consts::kFormatSpecifierChar) { - switch (*++format) { - case base::consts::kFormatSpecifierChar: // Escape - break; - case '\0': // End - --format; - break; - case 'd': // Day - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mday, 2, buf, bufLim); - continue; - case 'a': // Day of week (short) - buf = base::utils::Str::addToBuff(base::consts::kDaysAbbrev[tInfo->tm_wday], buf, bufLim); - continue; - case 'A': // Day of week (long) - buf = base::utils::Str::addToBuff(base::consts::kDays[tInfo->tm_wday], buf, bufLim); - continue; - case 'M': // month - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mon + 1, 2, buf, bufLim); - continue; - case 'b': // month (short) - buf = base::utils::Str::addToBuff(base::consts::kMonthsAbbrev[tInfo->tm_mon], buf, bufLim); - continue; - case 'B': // month (long) - buf = base::utils::Str::addToBuff(base::consts::kMonths[tInfo->tm_mon], buf, bufLim); - continue; - case 'y': // year (two digits) - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 2, buf, bufLim); - continue; - case 'Y': // year (four digits) - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 4, buf, bufLim); - continue; - case 'h': // hour (12-hour) - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour % 12, 2, buf, bufLim); - continue; - case 'H': // hour (24-hour) - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour, 2, buf, bufLim); - continue; - case 'm': // minute - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_min, 2, buf, bufLim); - continue; - case 's': // second - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_sec, 2, buf, bufLim); - continue; - case 'z': // subsecond part - case 'g': - buf = base::utils::Str::convertAndAddToBuff(msec, ssPrec->m_width, buf, bufLim); - continue; - case 'F': // AM/PM - buf = base::utils::Str::addToBuff((tInfo->tm_hour >= 12) ? base::consts::kPm : base::consts::kAm, buf, bufLim); - continue; - default: - continue; - } - } - if (buf == bufLim) break; - *buf++ = *format; - } - return buf; -} - -// CommandLineArgs - -void CommandLineArgs::setArgs(int argc, char** argv) { - m_params.clear(); - m_paramsWithValue.clear(); - if (argc == 0 || argv == nullptr) { - return; - } - m_argc = argc; - m_argv = argv; - for (int i = 1; i < m_argc; ++i) { - const char* v = (strstr(m_argv[i], "=")); - if (v != nullptr && strlen(v) > 0) { - std::string key = std::string(m_argv[i]); - key = key.substr(0, key.find_first_of('=')); - if (hasParamWithValue(key.c_str())) { - ELPP_INTERNAL_INFO(1, "Skipping [" << key << "] arg since it already has value [" - << getParamValue(key.c_str()) << "]"); - } else { - m_paramsWithValue.insert(std::make_pair(key, std::string(v + 1))); - } - } - if (v == nullptr) { - if (hasParam(m_argv[i])) { - ELPP_INTERNAL_INFO(1, "Skipping [" << m_argv[i] << "] arg since it already exists"); - } else { - m_params.push_back(std::string(m_argv[i])); - } - } - } -} - -bool CommandLineArgs::hasParamWithValue(const char* paramKey) const { - return m_paramsWithValue.find(std::string(paramKey)) != m_paramsWithValue.end(); -} - -const char* CommandLineArgs::getParamValue(const char* paramKey) const { - std::unordered_map::const_iterator iter = m_paramsWithValue.find(std::string(paramKey)); - return iter != m_paramsWithValue.end() ? iter->second.c_str() : ""; -} - -bool CommandLineArgs::hasParam(const char* paramKey) const { - return std::find(m_params.begin(), m_params.end(), std::string(paramKey)) != m_params.end(); -} - -bool CommandLineArgs::empty(void) const { - return m_params.empty() && m_paramsWithValue.empty(); -} - -std::size_t CommandLineArgs::size(void) const { - return m_params.size() + m_paramsWithValue.size(); -} - -base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c) { - for (int i = 1; i < c.m_argc; ++i) { - os << ELPP_LITERAL("[") << c.m_argv[i] << ELPP_LITERAL("]"); - if (i < c.m_argc - 1) { - os << ELPP_LITERAL(" "); - } - } - return os; -} - -} // namespace utils - -// el::base::threading -namespace threading { - -#if ELPP_THREADING_ENABLED -# if ELPP_USE_STD_THREADING -# if ELPP_ASYNC_LOGGING -static void msleep(int ms) { - // Only when async logging enabled - this is because async is strict on compiler -# if defined(ELPP_NO_SLEEP_FOR) - usleep(ms * 1000); -# else - std::this_thread::sleep_for(std::chrono::milliseconds(ms)); -# endif // defined(ELPP_NO_SLEEP_FOR) -} -# endif // ELPP_ASYNC_LOGGING -# endif // !ELPP_USE_STD_THREADING -#endif // ELPP_THREADING_ENABLED - -} // namespace threading - -// el::base - -// SubsecondPrecision - -void SubsecondPrecision::init(int width) { - if (width < 1 || width > 6) { - width = base::consts::kDefaultSubsecondPrecision; - } - m_width = width; - switch (m_width) { - case 3: - m_offset = 1000; - break; - case 4: - m_offset = 100; - break; - case 5: - m_offset = 10; - break; - case 6: - m_offset = 1; - break; - default: - m_offset = 1000; - break; - } -} - -// LogFormat - -LogFormat::LogFormat(void) : - m_level(Level::Unknown), - m_userFormat(base::type::string_t()), - m_format(base::type::string_t()), - m_dateTimeFormat(std::string()), - m_flags(0x0), - m_currentUser(base::utils::OS::currentUser()), - m_currentHost(base::utils::OS::currentHost()) { -} - -LogFormat::LogFormat(Level level, const base::type::string_t& format) - : m_level(level), m_userFormat(format), m_currentUser(base::utils::OS::currentUser()), - m_currentHost(base::utils::OS::currentHost()) { - parseFromFormat(m_userFormat); -} - -LogFormat::LogFormat(const LogFormat& logFormat): - m_level(logFormat.m_level), - m_userFormat(logFormat.m_userFormat), - m_format(logFormat.m_format), - m_dateTimeFormat(logFormat.m_dateTimeFormat), - m_flags(logFormat.m_flags), - m_currentUser(logFormat.m_currentUser), - m_currentHost(logFormat.m_currentHost) { -} - -LogFormat::LogFormat(LogFormat&& logFormat) { - m_level = std::move(logFormat.m_level); - m_userFormat = std::move(logFormat.m_userFormat); - m_format = std::move(logFormat.m_format); - m_dateTimeFormat = std::move(logFormat.m_dateTimeFormat); - m_flags = std::move(logFormat.m_flags); - m_currentUser = std::move(logFormat.m_currentUser); - m_currentHost = std::move(logFormat.m_currentHost); -} - -LogFormat& LogFormat::operator=(const LogFormat& logFormat) { - if (&logFormat != this) { - m_level = logFormat.m_level; - m_userFormat = logFormat.m_userFormat; - m_dateTimeFormat = logFormat.m_dateTimeFormat; - m_flags = logFormat.m_flags; - m_currentUser = logFormat.m_currentUser; - m_currentHost = logFormat.m_currentHost; - } - return *this; -} - -bool LogFormat::operator==(const LogFormat& other) { - return m_level == other.m_level && m_userFormat == other.m_userFormat && m_format == other.m_format && - m_dateTimeFormat == other.m_dateTimeFormat && m_flags == other.m_flags; -} - -/// @brief Updates format to be used while logging. -/// @param userFormat User provided format -void LogFormat::parseFromFormat(const base::type::string_t& userFormat) { - // We make copy because we will be changing the format - // i.e, removing user provided date format from original format - // and then storing it. - base::type::string_t formatCopy = userFormat; - m_flags = 0x0; - auto conditionalAddFlag = [&](const base::type::char_t* specifier, base::FormatFlags flag) { - std::size_t foundAt = base::type::string_t::npos; - while ((foundAt = formatCopy.find(specifier, foundAt + 1)) != base::type::string_t::npos) { - if (foundAt > 0 && formatCopy[foundAt - 1] == base::consts::kFormatSpecifierChar) { - if (hasFlag(flag)) { - // If we already have flag we remove the escape chars so that '%%' is turned to '%' - // even after specifier resolution - this is because we only replaceFirst specifier - formatCopy.erase(foundAt - 1, 1); - ++foundAt; - } - } else { - if (!hasFlag(flag)) addFlag(flag); - } - } - }; - conditionalAddFlag(base::consts::kAppNameFormatSpecifier, base::FormatFlags::AppName); - conditionalAddFlag(base::consts::kSeverityLevelFormatSpecifier, base::FormatFlags::Level); - conditionalAddFlag(base::consts::kSeverityLevelShortFormatSpecifier, base::FormatFlags::LevelShort); - conditionalAddFlag(base::consts::kLoggerIdFormatSpecifier, base::FormatFlags::LoggerId); - conditionalAddFlag(base::consts::kThreadIdFormatSpecifier, base::FormatFlags::ThreadId); - conditionalAddFlag(base::consts::kLogFileFormatSpecifier, base::FormatFlags::File); - conditionalAddFlag(base::consts::kLogFileBaseFormatSpecifier, base::FormatFlags::FileBase); - conditionalAddFlag(base::consts::kLogLineFormatSpecifier, base::FormatFlags::Line); - conditionalAddFlag(base::consts::kLogLocationFormatSpecifier, base::FormatFlags::Location); - conditionalAddFlag(base::consts::kLogFunctionFormatSpecifier, base::FormatFlags::Function); - conditionalAddFlag(base::consts::kCurrentUserFormatSpecifier, base::FormatFlags::User); - conditionalAddFlag(base::consts::kCurrentHostFormatSpecifier, base::FormatFlags::Host); - conditionalAddFlag(base::consts::kMessageFormatSpecifier, base::FormatFlags::LogMessage); - conditionalAddFlag(base::consts::kVerboseLevelFormatSpecifier, base::FormatFlags::VerboseLevel); - // For date/time we need to extract user's date format first - std::size_t dateIndex = std::string::npos; - if ((dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier)) != std::string::npos) { - while (dateIndex != std::string::npos && dateIndex > 0 && formatCopy[dateIndex - 1] == base::consts::kFormatSpecifierChar) { - dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier, dateIndex + 1); - } - if (dateIndex != std::string::npos) { - addFlag(base::FormatFlags::DateTime); - updateDateFormat(dateIndex, formatCopy); - } - } - m_format = formatCopy; - updateFormatSpec(); -} - -void LogFormat::updateDateFormat(std::size_t index, base::type::string_t& currFormat) { - if (hasFlag(base::FormatFlags::DateTime)) { - index += ELPP_STRLEN(base::consts::kDateTimeFormatSpecifier); - } - const base::type::char_t* ptr = currFormat.c_str() + index; - if ((currFormat.size() > index) && (ptr[0] == '{')) { - // User has provided format for date/time - ++ptr; - int count = 1; // Start by 1 in order to remove starting brace - std::stringstream ss; - for (; *ptr; ++ptr, ++count) { - if (*ptr == '}') { - ++count; // In order to remove ending brace - break; - } - ss << static_cast(*ptr); - } - currFormat.erase(index, count); - m_dateTimeFormat = ss.str(); - } else { - // No format provided, use default - if (hasFlag(base::FormatFlags::DateTime)) { - m_dateTimeFormat = std::string(base::consts::kDefaultDateTimeFormat); - } - } -} - -void LogFormat::updateFormatSpec(void) { - // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. - if (m_level == Level::Debug) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kDebugLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kDebugLevelShortLogValue); - } else if (m_level == Level::Info) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kInfoLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kInfoLevelShortLogValue); - } else if (m_level == Level::Warning) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kWarningLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kWarningLevelShortLogValue); - } else if (m_level == Level::Error) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kErrorLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kErrorLevelShortLogValue); - } else if (m_level == Level::Fatal) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kFatalLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kFatalLevelShortLogValue); - } else if (m_level == Level::Verbose) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kVerboseLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kVerboseLevelShortLogValue); - } else if (m_level == Level::Trace) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kTraceLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kTraceLevelShortLogValue); - } - if (hasFlag(base::FormatFlags::User)) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentUserFormatSpecifier, - m_currentUser); - } - if (hasFlag(base::FormatFlags::Host)) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentHostFormatSpecifier, - m_currentHost); - } - // Ignore Level::Global and Level::Unknown -} - -// TypedConfigurations - -TypedConfigurations::TypedConfigurations(Configurations* configurations, - LogStreamsReferenceMapPtr logStreamsReference) { - m_configurations = configurations; - m_logStreamsReference = logStreamsReference; - build(m_configurations); -} - -TypedConfigurations::TypedConfigurations(const TypedConfigurations& other) { - this->m_configurations = other.m_configurations; - this->m_logStreamsReference = other.m_logStreamsReference; - build(m_configurations); -} - -bool TypedConfigurations::enabled(Level level) { - return getConfigByVal(level, &m_enabledMap, "enabled"); -} - -bool TypedConfigurations::toFile(Level level) { - return getConfigByVal(level, &m_toFileMap, "toFile"); -} - -const std::string& TypedConfigurations::filename(Level level) { - return getConfigByRef(level, &m_filenameMap, "filename"); -} - -bool TypedConfigurations::toStandardOutput(Level level) { - return getConfigByVal(level, &m_toStandardOutputMap, "toStandardOutput"); -} - -const base::LogFormat& TypedConfigurations::logFormat(Level level) { - return getConfigByRef(level, &m_logFormatMap, "logFormat"); -} - -const base::SubsecondPrecision& TypedConfigurations::subsecondPrecision(Level level) { - return getConfigByRef(level, &m_subsecondPrecisionMap, "subsecondPrecision"); -} - -const base::MillisecondsWidth& TypedConfigurations::millisecondsWidth(Level level) { - return getConfigByRef(level, &m_subsecondPrecisionMap, "millisecondsWidth"); -} - -bool TypedConfigurations::performanceTracking(Level level) { - return getConfigByVal(level, &m_performanceTrackingMap, "performanceTracking"); -} - -base::type::fstream_t* TypedConfigurations::fileStream(Level level) { - return getConfigByRef(level, &m_fileStreamMap, "fileStream").get(); -} - -std::size_t TypedConfigurations::maxLogFileSize(Level level) { - return getConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize"); -} - -std::size_t TypedConfigurations::logFlushThreshold(Level level) { - return getConfigByVal(level, &m_logFlushThresholdMap, "logFlushThreshold"); -} - -void TypedConfigurations::build(Configurations* configurations) { - base::threading::ScopedLock scopedLock(lock()); - auto getBool = [] (std::string boolStr) -> bool { // Pass by value for trimming - base::utils::Str::trim(boolStr); - return (boolStr == "TRUE" || boolStr == "true" || boolStr == "1"); - }; - std::vector withFileSizeLimit; - for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) { - Configuration* conf = *it; - // We cannot use switch on strong enums because Intel C++ dont support them yet - if (conf->configurationType() == ConfigurationType::Enabled) { - setValue(conf->level(), getBool(conf->value()), &m_enabledMap); - } else if (conf->configurationType() == ConfigurationType::ToFile) { - setValue(conf->level(), getBool(conf->value()), &m_toFileMap); - } else if (conf->configurationType() == ConfigurationType::ToStandardOutput) { - setValue(conf->level(), getBool(conf->value()), &m_toStandardOutputMap); - } else if (conf->configurationType() == ConfigurationType::Filename) { - // We do not yet configure filename but we will configure in another - // loop. This is because if file cannot be created, we will force ToFile - // to be false. Because configuring logger is not necessarily performance - // sensitive operation, we can live with another loop; (by the way this loop - // is not very heavy either) - } else if (conf->configurationType() == ConfigurationType::Format) { - setValue(conf->level(), base::LogFormat(conf->level(), - base::type::string_t(conf->value().begin(), conf->value().end())), &m_logFormatMap); - } else if (conf->configurationType() == ConfigurationType::SubsecondPrecision) { - setValue(Level::Global, - base::SubsecondPrecision(static_cast(getULong(conf->value()))), &m_subsecondPrecisionMap); - } else if (conf->configurationType() == ConfigurationType::PerformanceTracking) { - setValue(Level::Global, getBool(conf->value()), &m_performanceTrackingMap); - } else if (conf->configurationType() == ConfigurationType::MaxLogFileSize) { - auto v = getULong(conf->value()); - setValue(conf->level(), static_cast(v), &m_maxLogFileSizeMap); - if (v != 0) { - withFileSizeLimit.push_back(conf); - } - } else if (conf->configurationType() == ConfigurationType::LogFlushThreshold) { - setValue(conf->level(), static_cast(getULong(conf->value())), &m_logFlushThresholdMap); - } - } - // As mentioned earlier, we will now set filename configuration in separate loop to deal with non-existent files - for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) { - Configuration* conf = *it; - if (conf->configurationType() == ConfigurationType::Filename) { - insertFile(conf->level(), conf->value()); - } - } - for (std::vector::iterator conf = withFileSizeLimit.begin(); - conf != withFileSizeLimit.end(); ++conf) { - // This is not unsafe as mutex is locked in currect scope - unsafeValidateFileRolling((*conf)->level(), base::defaultPreRollOutCallback); - } -} - -unsigned long TypedConfigurations::getULong(std::string confVal) { - bool valid = true; - base::utils::Str::trim(confVal); - valid = !confVal.empty() && std::find_if(confVal.begin(), confVal.end(), - [](char c) { - return !base::utils::Str::isDigit(c); - }) == confVal.end(); - if (!valid) { - valid = false; - ELPP_ASSERT(valid, "Configuration value not a valid integer [" << confVal << "]"); - return 0; - } - return atol(confVal.c_str()); -} - -std::string TypedConfigurations::resolveFilename(const std::string& filename) { - std::string resultingFilename = filename; - std::size_t dateIndex = std::string::npos; - std::string dateTimeFormatSpecifierStr = std::string(base::consts::kDateTimeFormatSpecifierForFilename); - if ((dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str())) != std::string::npos) { - while (dateIndex > 0 && resultingFilename[dateIndex - 1] == base::consts::kFormatSpecifierChar) { - dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str(), dateIndex + 1); - } - if (dateIndex != std::string::npos) { - const char* ptr = resultingFilename.c_str() + dateIndex; - // Goto end of specifier - ptr += dateTimeFormatSpecifierStr.size(); - std::string fmt; - if ((resultingFilename.size() > dateIndex) && (ptr[0] == '{')) { - // User has provided format for date/time - ++ptr; - int count = 1; // Start by 1 in order to remove starting brace - std::stringstream ss; - for (; *ptr; ++ptr, ++count) { - if (*ptr == '}') { - ++count; // In order to remove ending brace - break; - } - ss << *ptr; - } - resultingFilename.erase(dateIndex + dateTimeFormatSpecifierStr.size(), count); - fmt = ss.str(); - } else { - fmt = std::string(base::consts::kDefaultDateTimeFormatInFilename); - } - base::SubsecondPrecision ssPrec(3); - std::string now = base::utils::DateTime::getDateTime(fmt.c_str(), &ssPrec); - base::utils::Str::replaceAll(now, '/', '-'); // Replace path element since we are dealing with filename - base::utils::Str::replaceAll(resultingFilename, dateTimeFormatSpecifierStr, now); - } - } - return resultingFilename; -} - -void TypedConfigurations::insertFile(Level level, const std::string& fullFilename) { - std::string resolvedFilename = resolveFilename(fullFilename); - if (resolvedFilename.empty()) { - std::cerr << "Could not load empty file for logging, please re-check your configurations for level [" - << LevelHelper::convertToString(level) << "]"; - } - std::string filePath = base::utils::File::extractPathFromFilename(resolvedFilename, base::consts::kFilePathSeparator); - if (filePath.size() < resolvedFilename.size()) { - base::utils::File::createPath(filePath); - } - auto create = [&](Level var_level) { - base::LogStreamsReferenceMap::iterator filestreamIter = m_logStreamsReference->find(resolvedFilename); - base::type::fstream_t* fs = nullptr; - if (filestreamIter == m_logStreamsReference->end()) { - // We need a completely new stream, nothing to share with - fs = base::utils::File::newFileStream(resolvedFilename); - m_filenameMap.insert(std::make_pair(var_level, resolvedFilename)); - m_fileStreamMap.insert(std::make_pair(var_level, base::FileStreamPtr(fs))); - m_logStreamsReference->insert(std::make_pair(resolvedFilename, base::FileStreamPtr(m_fileStreamMap.at(var_level)))); - } else { - // Woops! we have an existing one, share it! - m_filenameMap.insert(std::make_pair(var_level, filestreamIter->first)); - m_fileStreamMap.insert(std::make_pair(var_level, base::FileStreamPtr(filestreamIter->second))); - fs = filestreamIter->second.get(); - } - if (fs == nullptr) { - // We display bad file error from newFileStream() - ELPP_INTERNAL_ERROR("Setting [TO_FILE] of [" - << LevelHelper::convertToString(var_level) << "] to FALSE", false); - setValue(var_level, false, &m_toFileMap); - } - }; - // If we dont have file conf for any var_level, create it for Level::Global first - // otherwise create for specified var_level - create(m_filenameMap.empty() && m_fileStreamMap.empty() ? Level::Global : level); -} - -bool TypedConfigurations::unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) { - base::type::fstream_t* fs = unsafeGetConfigByRef(level, &m_fileStreamMap, "fileStream").get(); - if (fs == nullptr) { - return true; - } - std::size_t maxLogFileSize = unsafeGetConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize"); - std::size_t currFileSize = base::utils::File::getSizeOfFile(fs); - if (maxLogFileSize != 0 && currFileSize >= maxLogFileSize) { - std::string fname = unsafeGetConfigByRef(level, &m_filenameMap, "filename"); - ELPP_INTERNAL_INFO(1, "Truncating log file [" << fname << "] as a result of configurations for level [" - << LevelHelper::convertToString(level) << "]"); - fs->close(); - preRollOutCallback(fname.c_str(), currFileSize); - fs->open(fname, std::fstream::out | std::fstream::trunc); - return true; - } - return false; -} - -// RegisteredHitCounters - -bool RegisteredHitCounters::validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - base::threading::ScopedLock scopedLock(lock()); - base::HitCounter* counter = get(filename, lineNumber); - if (counter == nullptr) { - registerNew(counter = new base::HitCounter(filename, lineNumber)); - } - counter->validateHitCounts(n); - bool result = (n >= 1 && counter->hitCounts() != 0 && counter->hitCounts() % n == 0); - return result; -} - -/// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one -/// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned -bool RegisteredHitCounters::validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - base::threading::ScopedLock scopedLock(lock()); - base::HitCounter* counter = get(filename, lineNumber); - if (counter == nullptr) { - registerNew(counter = new base::HitCounter(filename, lineNumber)); - } - // Do not use validateHitCounts here since we do not want to reset counter here - // Note the >= instead of > because we are incrementing - // after this check - if (counter->hitCounts() >= n) - return true; - counter->increment(); - return false; -} - -/// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one -/// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned -bool RegisteredHitCounters::validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - base::threading::ScopedLock scopedLock(lock()); - base::HitCounter* counter = get(filename, lineNumber); - if (counter == nullptr) { - registerNew(counter = new base::HitCounter(filename, lineNumber)); - } - counter->increment(); - // Do not use validateHitCounts here since we do not want to reset counter here - if (counter->hitCounts() <= n) - return true; - return false; -} - -// RegisteredLoggers - -RegisteredLoggers::RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder) : - m_defaultLogBuilder(defaultLogBuilder) { - m_defaultConfigurations.setToDefault(); - m_logStreamsReference = std::make_shared(); -} - -Logger* RegisteredLoggers::get(const std::string& id, bool forceCreation) { - base::threading::ScopedLock scopedLock(lock()); - Logger* logger_ = base::utils::Registry::get(id); - if (logger_ == nullptr && forceCreation) { - bool validId = Logger::isValidId(id); - if (!validId) { - ELPP_ASSERT(validId, "Invalid logger ID [" << id << "]. Not registering this logger."); - return nullptr; - } - logger_ = new Logger(id, m_defaultConfigurations, m_logStreamsReference); - logger_->m_logBuilder = m_defaultLogBuilder; - registerNew(id, logger_); - LoggerRegistrationCallback* callback = nullptr; - for (const std::pair h - : m_loggerRegistrationCallbacks) { - callback = h.second.get(); - if (callback != nullptr && callback->enabled()) { - callback->handle(logger_); - } - } - } - return logger_; -} - -bool RegisteredLoggers::remove(const std::string& id) { - if (id == base::consts::kDefaultLoggerId) { - return false; - } - // get has internal lock - Logger* logger = base::utils::Registry::get(id); - if (logger != nullptr) { - // unregister has internal lock - unregister(logger); - } - return true; -} - -void RegisteredLoggers::unsafeFlushAll(void) { - ELPP_INTERNAL_INFO(1, "Flushing all log files"); - for (base::LogStreamsReferenceMap::iterator it = m_logStreamsReference->begin(); - it != m_logStreamsReference->end(); ++it) { - if (it->second.get() == nullptr) continue; - it->second->flush(); - } -} - -// VRegistry - -VRegistry::VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags) : m_level(level), m_pFlags(pFlags) { -} - -/// @brief Sets verbose level. Accepted range is 0-9 -void VRegistry::setLevel(base::type::VerboseLevel level) { - base::threading::ScopedLock scopedLock(lock()); - if (level > 9) - m_level = base::consts::kMaxVerboseLevel; - else - m_level = level; -} - -void VRegistry::setModules(const char* modules) { - base::threading::ScopedLock scopedLock(lock()); - auto addSuffix = [](std::stringstream& ss, const char* sfx, const char* prev) { - if (prev != nullptr && base::utils::Str::endsWith(ss.str(), std::string(prev))) { - std::string chr(ss.str().substr(0, ss.str().size() - strlen(prev))); - ss.str(std::string("")); - ss << chr; - } - if (base::utils::Str::endsWith(ss.str(), std::string(sfx))) { - std::string chr(ss.str().substr(0, ss.str().size() - strlen(sfx))); - ss.str(std::string("")); - ss << chr; - } - ss << sfx; - }; - auto insert = [&](std::stringstream& ss, base::type::VerboseLevel level) { - if (!base::utils::hasFlag(LoggingFlag::DisableVModulesExtensions, *m_pFlags)) { - addSuffix(ss, ".h", nullptr); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".c", ".h"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".cpp", ".c"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".cc", ".cpp"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".cxx", ".cc"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".-inl.h", ".cxx"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".hxx", ".-inl.h"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".hpp", ".hxx"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".hh", ".hpp"); - } - m_modules.insert(std::make_pair(ss.str(), level)); - }; - bool isMod = true; - bool isLevel = false; - std::stringstream ss; - int level = -1; - for (; *modules; ++modules) { - switch (*modules) { - case '=': - isLevel = true; - isMod = false; - break; - case ',': - isLevel = false; - isMod = true; - if (!ss.str().empty() && level != -1) { - insert(ss, static_cast(level)); - ss.str(std::string("")); - level = -1; - } - break; - default: - if (isMod) { - ss << *modules; - } else if (isLevel) { - if (isdigit(*modules)) { - level = static_cast(*modules) - 48; - } - } - break; - } - } - if (!ss.str().empty() && level != -1) { - insert(ss, static_cast(level)); - } -} - -bool VRegistry::allowed(base::type::VerboseLevel vlevel, const char* file) { - base::threading::ScopedLock scopedLock(lock()); - if (m_modules.empty() || file == nullptr) { - return vlevel <= m_level; - } else { - char baseFilename[base::consts::kSourceFilenameMaxLength] = ""; - base::utils::File::buildBaseFilename(file, baseFilename); - std::unordered_map::iterator it = m_modules.begin(); - for (; it != m_modules.end(); ++it) { - if (base::utils::Str::wildCardMatch(baseFilename, it->first.c_str())) { - return vlevel <= it->second; - } - } - if (base::utils::hasFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified, *m_pFlags)) { - return true; - } - return false; - } -} - -void VRegistry::setFromArgs(const base::utils::CommandLineArgs* commandLineArgs) { - if (commandLineArgs->hasParam("-v") || commandLineArgs->hasParam("--verbose") || - commandLineArgs->hasParam("-V") || commandLineArgs->hasParam("--VERBOSE")) { - setLevel(base::consts::kMaxVerboseLevel); - } else if (commandLineArgs->hasParamWithValue("--v")) { - setLevel(static_cast(atoi(commandLineArgs->getParamValue("--v")))); - } else if (commandLineArgs->hasParamWithValue("--V")) { - setLevel(static_cast(atoi(commandLineArgs->getParamValue("--V")))); - } else if ((commandLineArgs->hasParamWithValue("-vmodule")) && vModulesEnabled()) { - setModules(commandLineArgs->getParamValue("-vmodule")); - } else if (commandLineArgs->hasParamWithValue("-VMODULE") && vModulesEnabled()) { - setModules(commandLineArgs->getParamValue("-VMODULE")); - } -} - -#if !defined(ELPP_DEFAULT_LOGGING_FLAGS) -# define ELPP_DEFAULT_LOGGING_FLAGS 0x0 -#endif // !defined(ELPP_DEFAULT_LOGGING_FLAGS) -// Storage -#if ELPP_ASYNC_LOGGING -Storage::Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker) : -#else -Storage::Storage(const LogBuilderPtr& defaultLogBuilder) : -#endif // ELPP_ASYNC_LOGGING - m_registeredHitCounters(new base::RegisteredHitCounters()), - m_registeredLoggers(new base::RegisteredLoggers(defaultLogBuilder)), - m_flags(ELPP_DEFAULT_LOGGING_FLAGS), - m_vRegistry(new base::VRegistry(0, &m_flags)), - -#if ELPP_ASYNC_LOGGING - m_asyncLogQueue(new base::AsyncLogQueue()), - m_asyncDispatchWorker(asyncDispatchWorker), -#endif // ELPP_ASYNC_LOGGING - - m_preRollOutCallback(base::defaultPreRollOutCallback) { - // Register default logger - m_registeredLoggers->get(std::string(base::consts::kDefaultLoggerId)); - // We register default logger anyway (worse case it's not going to register) just in case - m_registeredLoggers->get("default"); - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - // Register performance logger and reconfigure format - Logger* performanceLogger = m_registeredLoggers->get(std::string(base::consts::kPerformanceLoggerId)); - m_registeredLoggers->get("performance"); - performanceLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%datetime %level %msg")); - performanceLogger->reconfigure(); -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - -#if defined(ELPP_SYSLOG) - // Register syslog logger and reconfigure format - Logger* sysLogLogger = m_registeredLoggers->get(std::string(base::consts::kSysLogLoggerId)); - sysLogLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%level: %msg")); - sysLogLogger->reconfigure(); -#endif // defined(ELPP_SYSLOG) - addFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified); -#if ELPP_ASYNC_LOGGING - installLogDispatchCallback(std::string("AsyncLogDispatchCallback")); -#else - installLogDispatchCallback(std::string("DefaultLogDispatchCallback")); -#endif // ELPP_ASYNC_LOGGING -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - installPerformanceTrackingCallback - (std::string("DefaultPerformanceTrackingCallback")); -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - ELPP_INTERNAL_INFO(1, "Easylogging++ has been initialized"); -#if ELPP_ASYNC_LOGGING - m_asyncDispatchWorker->start(); -#endif // ELPP_ASYNC_LOGGING -} - -Storage::~Storage(void) { - ELPP_INTERNAL_INFO(4, "Destroying storage"); -#if ELPP_ASYNC_LOGGING - ELPP_INTERNAL_INFO(5, "Replacing log dispatch callback to synchronous"); - uninstallLogDispatchCallback(std::string("AsyncLogDispatchCallback")); - installLogDispatchCallback(std::string("DefaultLogDispatchCallback")); - ELPP_INTERNAL_INFO(5, "Destroying asyncDispatchWorker"); - base::utils::safeDelete(m_asyncDispatchWorker); - ELPP_INTERNAL_INFO(5, "Destroying asyncLogQueue"); - base::utils::safeDelete(m_asyncLogQueue); -#endif // ELPP_ASYNC_LOGGING - ELPP_INTERNAL_INFO(5, "Destroying registeredHitCounters"); - base::utils::safeDelete(m_registeredHitCounters); - ELPP_INTERNAL_INFO(5, "Destroying registeredLoggers"); - base::utils::safeDelete(m_registeredLoggers); - ELPP_INTERNAL_INFO(5, "Destroying vRegistry"); - base::utils::safeDelete(m_vRegistry); -} - -bool Storage::hasCustomFormatSpecifier(const char* formatSpecifier) { - base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); - return std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(), - formatSpecifier) != m_customFormatSpecifiers.end(); -} - -void Storage::installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) { - if (hasCustomFormatSpecifier(customFormatSpecifier.formatSpecifier())) { - return; - } - base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); - m_customFormatSpecifiers.push_back(customFormatSpecifier); -} - -bool Storage::uninstallCustomFormatSpecifier(const char* formatSpecifier) { - base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); - std::vector::iterator it = std::find(m_customFormatSpecifiers.begin(), - m_customFormatSpecifiers.end(), formatSpecifier); - if (it != m_customFormatSpecifiers.end() && strcmp(formatSpecifier, it->formatSpecifier()) == 0) { - m_customFormatSpecifiers.erase(it); - return true; - } - return false; -} - -void Storage::setApplicationArguments(int argc, char** argv) { - m_commandLineArgs.setArgs(argc, argv); - m_vRegistry->setFromArgs(commandLineArgs()); - // default log file -#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) - if (m_commandLineArgs.hasParamWithValue(base::consts::kDefaultLogFileParam)) { - Configurations c; - c.setGlobally(ConfigurationType::Filename, - std::string(m_commandLineArgs.getParamValue(base::consts::kDefaultLogFileParam))); - registeredLoggers()->setDefaultConfigurations(c); - for (base::RegisteredLoggers::iterator it = registeredLoggers()->begin(); - it != registeredLoggers()->end(); ++it) { - it->second->configure(c); - } - } -#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) -#if defined(ELPP_LOGGING_FLAGS_FROM_ARG) - if (m_commandLineArgs.hasParamWithValue(base::consts::kLoggingFlagsParam)) { - int userInput = atoi(m_commandLineArgs.getParamValue(base::consts::kLoggingFlagsParam)); - if (ELPP_DEFAULT_LOGGING_FLAGS == 0x0) { - m_flags = userInput; - } else { - base::utils::addFlag(userInput, &m_flags); - } - } -#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG) -} - -} // namespace base - -// LogDispatchCallback -#if defined(ELPP_THREAD_SAFE) -void LogDispatchCallback::handle(const LogDispatchData* data) { - base::threading::ScopedLock scopedLock(m_fileLocksMapLock); - std::string filename = data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level()); - auto lock = m_fileLocks.find(filename); - if (lock == m_fileLocks.end()) { - m_fileLocks.emplace(std::make_pair(filename, std::unique_ptr(new base::threading::Mutex))); - } -} -#else -void LogDispatchCallback::handle(const LogDispatchData* /*data*/) {} -#endif - -base::threading::Mutex& LogDispatchCallback::fileHandle(const LogDispatchData* data) { - auto it = m_fileLocks.find(data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level())); - return *(it->second.get()); -} - -namespace base { -// DefaultLogDispatchCallback - -void DefaultLogDispatchCallback::handle(const LogDispatchData* data) { -#if defined(ELPP_THREAD_SAFE) - LogDispatchCallback::handle(data); - base::threading::ScopedLock scopedLock(fileHandle(data)); -#endif - m_data = data; - dispatch(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(), - m_data->dispatchAction() == base::DispatchAction::NormalLog)); -} - -void DefaultLogDispatchCallback::dispatch(base::type::string_t&& logLine) { - if (m_data->dispatchAction() == base::DispatchAction::NormalLog) { - if (m_data->logMessage()->logger()->m_typedConfigurations->toFile(m_data->logMessage()->level())) { - base::type::fstream_t* fs = m_data->logMessage()->logger()->m_typedConfigurations->fileStream( - m_data->logMessage()->level()); - if (fs != nullptr) { - fs->write(logLine.c_str(), logLine.size()); - if (fs->fail()) { - ELPP_INTERNAL_ERROR("Unable to write log to file [" - << m_data->logMessage()->logger()->m_typedConfigurations->filename(m_data->logMessage()->level()) << "].\n" - << "Few possible reasons (could be something else):\n" << " * Permission denied\n" - << " * Disk full\n" << " * Disk is not writable", true); - } else { - if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) - || (m_data->logMessage()->logger()->isFlushNeeded(m_data->logMessage()->level()))) { - m_data->logMessage()->logger()->flush(m_data->logMessage()->level(), fs); - } - } - } else { - ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(m_data->logMessage()->level()) << "] " - << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " - << m_data->logMessage()->logger()->id() << "]", false); - } - } - if (m_data->logMessage()->logger()->m_typedConfigurations->toStandardOutput(m_data->logMessage()->level())) { - if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput)) - m_data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, m_data->logMessage()->level()); - ELPP_COUT << ELPP_COUT_LINE(logLine); - } - } -#if defined(ELPP_SYSLOG) - else if (m_data->dispatchAction() == base::DispatchAction::SysLog) { - // Determine syslog priority - int sysLogPriority = 0; - if (m_data->logMessage()->level() == Level::Fatal) - sysLogPriority = LOG_EMERG; - else if (m_data->logMessage()->level() == Level::Error) - sysLogPriority = LOG_ERR; - else if (m_data->logMessage()->level() == Level::Warning) - sysLogPriority = LOG_WARNING; - else if (m_data->logMessage()->level() == Level::Info) - sysLogPriority = LOG_INFO; - else if (m_data->logMessage()->level() == Level::Debug) - sysLogPriority = LOG_DEBUG; - else - sysLogPriority = LOG_NOTICE; -# if defined(ELPP_UNICODE) - char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str()); - syslog(sysLogPriority, "%s", line); - free(line); -# else - syslog(sysLogPriority, "%s", logLine.c_str()); -# endif - } -#endif // defined(ELPP_SYSLOG) -} - -#if ELPP_ASYNC_LOGGING - -// AsyncLogDispatchCallback - -void AsyncLogDispatchCallback::handle(const LogDispatchData* data) { - base::type::string_t logLine = data->logMessage()->logger()->logBuilder()->build(data->logMessage(), - data->dispatchAction() == base::DispatchAction::NormalLog); - if (data->dispatchAction() == base::DispatchAction::NormalLog - && data->logMessage()->logger()->typedConfigurations()->toStandardOutput(data->logMessage()->level())) { - if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput)) - data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, data->logMessage()->level()); - ELPP_COUT << ELPP_COUT_LINE(logLine); - } - // Save resources and only queue if we want to write to file otherwise just ignore handler - if (data->logMessage()->logger()->typedConfigurations()->toFile(data->logMessage()->level())) { - ELPP->asyncLogQueue()->push(AsyncLogItem(*(data->logMessage()), *data, logLine)); - } -} - -// AsyncDispatchWorker -AsyncDispatchWorker::AsyncDispatchWorker() { - setContinueRunning(false); -} - -AsyncDispatchWorker::~AsyncDispatchWorker() { - setContinueRunning(false); - ELPP_INTERNAL_INFO(6, "Stopping dispatch worker - Cleaning log queue"); - clean(); - ELPP_INTERNAL_INFO(6, "Log queue cleaned"); -} - -bool AsyncDispatchWorker::clean(void) { - std::mutex m; - std::unique_lock lk(m); - cv.wait(lk, [] { return !ELPP->asyncLogQueue()->empty(); }); - emptyQueue(); - lk.unlock(); - cv.notify_one(); - return ELPP->asyncLogQueue()->empty(); -} - -void AsyncDispatchWorker::emptyQueue(void) { - while (!ELPP->asyncLogQueue()->empty()) { - AsyncLogItem data = ELPP->asyncLogQueue()->next(); - handle(&data); - base::threading::msleep(100); - } -} - -void AsyncDispatchWorker::start(void) { - base::threading::msleep(5000); // 5s (why?) - setContinueRunning(true); - std::thread t1(&AsyncDispatchWorker::run, this); - t1.join(); -} - -void AsyncDispatchWorker::handle(AsyncLogItem* logItem) { - LogDispatchData* data = logItem->data(); - LogMessage* logMessage = logItem->logMessage(); - Logger* logger = logMessage->logger(); - base::TypedConfigurations* conf = logger->typedConfigurations(); - base::type::string_t logLine = logItem->logLine(); - if (data->dispatchAction() == base::DispatchAction::NormalLog) { - if (conf->toFile(logMessage->level())) { - base::type::fstream_t* fs = conf->fileStream(logMessage->level()); - if (fs != nullptr) { - fs->write(logLine.c_str(), logLine.size()); - if (fs->fail()) { - ELPP_INTERNAL_ERROR("Unable to write log to file [" - << conf->filename(logMessage->level()) << "].\n" - << "Few possible reasons (could be something else):\n" << " * Permission denied\n" - << " * Disk full\n" << " * Disk is not writable", true); - } else { - if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (logger->isFlushNeeded(logMessage->level()))) { - logger->flush(logMessage->level(), fs); - } - } - } else { - ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(logMessage->level()) << "] " - << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " << logger->id() << "]", false); - } - } - } -# if defined(ELPP_SYSLOG) - else if (data->dispatchAction() == base::DispatchAction::SysLog) { - // Determine syslog priority - int sysLogPriority = 0; - if (logMessage->level() == Level::Fatal) - sysLogPriority = LOG_EMERG; - else if (logMessage->level() == Level::Error) - sysLogPriority = LOG_ERR; - else if (logMessage->level() == Level::Warning) - sysLogPriority = LOG_WARNING; - else if (logMessage->level() == Level::Info) - sysLogPriority = LOG_INFO; - else if (logMessage->level() == Level::Debug) - sysLogPriority = LOG_DEBUG; - else - sysLogPriority = LOG_NOTICE; -# if defined(ELPP_UNICODE) - char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str()); - syslog(sysLogPriority, "%s", line); - free(line); -# else - syslog(sysLogPriority, "%s", logLine.c_str()); -# endif - } -# endif // defined(ELPP_SYSLOG) -} - -void AsyncDispatchWorker::run(void) { - while (continueRunning()) { - emptyQueue(); - base::threading::msleep(10); // 10ms - } -} -#endif // ELPP_ASYNC_LOGGING - -// DefaultLogBuilder - -base::type::string_t DefaultLogBuilder::build(const LogMessage* logMessage, bool appendNewLine) const { - base::TypedConfigurations* tc = logMessage->logger()->typedConfigurations(); - const base::LogFormat* logFormat = &tc->logFormat(logMessage->level()); - base::type::string_t logLine = logFormat->format(); - char buff[base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength] = ""; - const char* bufLim = buff + sizeof(buff); - if (logFormat->hasFlag(base::FormatFlags::AppName)) { - // App name - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kAppNameFormatSpecifier, - logMessage->logger()->parentApplicationName()); - } - if (logFormat->hasFlag(base::FormatFlags::ThreadId)) { - // Thread ID - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kThreadIdFormatSpecifier, - ELPP->getThreadName(base::threading::getCurrentThreadId())); - } - if (logFormat->hasFlag(base::FormatFlags::DateTime)) { - // DateTime - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kDateTimeFormatSpecifier, - base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(), - &tc->subsecondPrecision(logMessage->level()))); - } - if (logFormat->hasFlag(base::FormatFlags::Function)) { - // Function - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFunctionFormatSpecifier, logMessage->func()); - } - if (logFormat->hasFlag(base::FormatFlags::File)) { - // File - base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength); - base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileFormatSpecifier, std::string(buff)); - } - if (logFormat->hasFlag(base::FormatFlags::FileBase)) { - // FileBase - base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength); - base::utils::File::buildBaseFilename(logMessage->file(), buff); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileBaseFormatSpecifier, std::string(buff)); - } - if (logFormat->hasFlag(base::FormatFlags::Line)) { - // Line - char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceLineMaxLength); - buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, false); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLineFormatSpecifier, std::string(buff)); - } - if (logFormat->hasFlag(base::FormatFlags::Location)) { - // Location - char* buf = base::utils::Str::clearBuff(buff, - base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength); - base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff); - buf = base::utils::Str::addToBuff(buff, buf, bufLim); - buf = base::utils::Str::addToBuff(":", buf, bufLim); - buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, - false); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLocationFormatSpecifier, std::string(buff)); - } - if (logMessage->level() == Level::Verbose && logFormat->hasFlag(base::FormatFlags::VerboseLevel)) { - // Verbose level - char* buf = base::utils::Str::clearBuff(buff, 1); - buf = base::utils::Str::convertAndAddToBuff(logMessage->verboseLevel(), 1, buf, bufLim, false); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kVerboseLevelFormatSpecifier, std::string(buff)); - } - if (logFormat->hasFlag(base::FormatFlags::LogMessage)) { - // Log message - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kMessageFormatSpecifier, logMessage->message()); - } -#if !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS) - el::base::threading::ScopedLock lock_(ELPP->customFormatSpecifiersLock()); - ELPP_UNUSED(lock_); - for (std::vector::const_iterator it = ELPP->customFormatSpecifiers()->begin(); - it != ELPP->customFormatSpecifiers()->end(); ++it) { - std::string fs(it->formatSpecifier()); - base::type::string_t wcsFormatSpecifier(fs.begin(), fs.end()); - base::utils::Str::replaceFirstWithEscape(logLine, wcsFormatSpecifier, it->resolver()(logMessage)); - } -#endif // !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS) - if (appendNewLine) logLine += ELPP_LITERAL("\n"); - return logLine; -} - -// LogDispatcher - -void LogDispatcher::dispatch(void) { - if (m_proceed && m_dispatchAction == base::DispatchAction::None) { - m_proceed = false; - } - if (!m_proceed) { - return; - } -#ifndef ELPP_NO_GLOBAL_LOCK - // see https://github.com/muflihun/easyloggingpp/issues/580 - // global lock is turned on by default unless - // ELPP_NO_GLOBAL_LOCK is defined - base::threading::ScopedLock scopedLock(ELPP->lock()); -#endif - base::TypedConfigurations* tc = m_logMessage->logger()->m_typedConfigurations; - if (ELPP->hasFlag(LoggingFlag::StrictLogFileSizeCheck)) { - tc->validateFileRolling(m_logMessage->level(), ELPP->preRollOutCallback()); - } - LogDispatchCallback* callback = nullptr; - LogDispatchData data; - for (const std::pair h - : ELPP->m_logDispatchCallbacks) { - callback = h.second.get(); - if (callback != nullptr && callback->enabled()) { - data.setLogMessage(m_logMessage); - data.setDispatchAction(m_dispatchAction); - callback->handle(&data); - } - } -} - -// MessageBuilder - -void MessageBuilder::initialize(Logger* logger) { - m_logger = logger; - m_containerLogSeparator = ELPP->hasFlag(LoggingFlag::NewLineForContainer) ? - ELPP_LITERAL("\n ") : ELPP_LITERAL(", "); -} - -MessageBuilder& MessageBuilder::operator<<(const wchar_t* msg) { - if (msg == nullptr) { - m_logger->stream() << base::consts::kNullPointer; - return *this; - } -# if defined(ELPP_UNICODE) - m_logger->stream() << msg; -# else - char* buff_ = base::utils::Str::wcharPtrToCharPtr(msg); - m_logger->stream() << buff_; - free(buff_); -# endif - if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) { - m_logger->stream() << " "; - } - return *this; -} - -// Writer - -Writer& Writer::construct(Logger* logger, bool needLock) { - m_logger = logger; - initializeLogger(logger->id(), false, needLock); - m_messageBuilder.initialize(m_logger); - return *this; -} - -Writer& Writer::construct(int count, const char* loggerIds, ...) { - if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) { - va_list loggersList; - va_start(loggersList, loggerIds); - const char* id = loggerIds; - m_loggerIds.reserve(count); - for (int i = 0; i < count; ++i) { - m_loggerIds.push_back(std::string(id)); - id = va_arg(loggersList, const char*); - } - va_end(loggersList); - initializeLogger(m_loggerIds.at(0)); - } else { - initializeLogger(std::string(loggerIds)); - } - m_messageBuilder.initialize(m_logger); - return *this; -} - -void Writer::initializeLogger(const std::string& loggerId, bool lookup, bool needLock) { - if (lookup) { - m_logger = ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically)); - } - if (m_logger == nullptr) { - { - if (!ELPP->registeredLoggers()->has(std::string(base::consts::kDefaultLoggerId))) { - // Somehow default logger has been unregistered. Not good! Register again - ELPP->registeredLoggers()->get(std::string(base::consts::kDefaultLoggerId)); - } - } - Writer(Level::Debug, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId) - << "Logger [" << loggerId << "] is not registered yet!"; - m_proceed = false; - } else { - if (needLock) { - m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because - // m_proceed can be changed by lines below - } - if (ELPP->hasFlag(LoggingFlag::HierarchicalLogging)) { - m_proceed = m_level == Level::Verbose ? m_logger->enabled(m_level) : - LevelHelper::castToInt(m_level) >= LevelHelper::castToInt(ELPP->m_loggingLevel); - } else { - m_proceed = m_logger->enabled(m_level); - } - } -} - -void Writer::processDispatch() { -#if ELPP_LOGGING_ENABLED - if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) { - bool firstDispatched = false; - base::type::string_t logMessage; - std::size_t i = 0; - do { - if (m_proceed) { - if (firstDispatched) { - m_logger->stream() << logMessage; - } else { - firstDispatched = true; - if (m_loggerIds.size() > 1) { - logMessage = m_logger->stream().str(); - } - } - triggerDispatch(); - } else if (m_logger != nullptr) { - m_logger->stream().str(ELPP_LITERAL("")); - m_logger->releaseLock(); - } - if (i + 1 < m_loggerIds.size()) { - initializeLogger(m_loggerIds.at(i + 1)); - } - } while (++i < m_loggerIds.size()); - } else { - if (m_proceed) { - triggerDispatch(); - } else if (m_logger != nullptr) { - m_logger->stream().str(ELPP_LITERAL("")); - m_logger->releaseLock(); - } - } -#else - if (m_logger != nullptr) { - m_logger->stream().str(ELPP_LITERAL("")); - m_logger->releaseLock(); - } -#endif // ELPP_LOGGING_ENABLED -} - -void Writer::triggerDispatch(void) { - try { - if (m_proceed) { - if (m_msg == nullptr) { - LogMessage msg(m_level, m_file, m_line, m_func, m_verboseLevel, - m_logger); - base::LogDispatcher(m_proceed, &msg, m_dispatchAction).dispatch(); - } else { - base::LogDispatcher(m_proceed, m_msg, m_dispatchAction).dispatch(); - } - } - if (m_logger != nullptr) { - m_logger->stream().str(ELPP_LITERAL("")); - m_logger->releaseLock(); - } - if (m_proceed && m_level == Level::Fatal - && !ELPP->hasFlag(LoggingFlag::DisableApplicationAbortOnFatalLog)) { - base::Writer(Level::Warning, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId) - << "Aborting application. Reason: Fatal log at [" << m_file << ":" << m_line << "]"; - std::stringstream reasonStream; - reasonStream << "Fatal log at [" << m_file << ":" << m_line << "]" - << " If you wish to disable 'abort on fatal log' please use " - << "el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog)"; - base::utils::abort(1, reasonStream.str()); - } - m_proceed = false; - } - catch(std::exception & ex){ - // Unused variable. Errors on MSVC. - (void)ex; - // Extremely low memory situation; don't let exception be unhandled. - } -} - -// PErrorWriter - -PErrorWriter::~PErrorWriter(void) { - if (m_proceed) { -#if ELPP_COMPILER_MSVC - char buff[256]; - strerror_s(buff, 256, errno); - m_logger->stream() << ": " << buff << " [" << errno << "]"; -#else - m_logger->stream() << ": " << strerror(errno) << " [" << errno << "]"; -#endif - } -} - -// PerformanceTracker - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - -PerformanceTracker::PerformanceTracker(const std::string& blockName, - base::TimestampUnit timestampUnit, - const std::string& loggerId, - bool scopedLog, Level level) : - m_blockName(blockName), m_timestampUnit(timestampUnit), m_loggerId(loggerId), m_scopedLog(scopedLog), - m_level(level), m_hasChecked(false), m_lastCheckpointId(std::string()), m_enabled(false) { -#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED - // We store it locally so that if user happen to change configuration by the end of scope - // or before calling checkpoint, we still depend on state of configuration at time of construction - el::Logger* loggerPtr = ELPP->registeredLoggers()->get(loggerId, false); - m_enabled = loggerPtr != nullptr && loggerPtr->m_typedConfigurations->performanceTracking(m_level); - if (m_enabled) { - base::utils::DateTime::gettimeofday(&m_startTime); - } -#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED -} - -PerformanceTracker::~PerformanceTracker(void) { -#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED - if (m_enabled) { - base::threading::ScopedLock scopedLock(lock()); - if (m_scopedLog) { - base::utils::DateTime::gettimeofday(&m_endTime); - base::type::string_t formattedTime = getFormattedTimeTaken(); - PerformanceTrackingData data(PerformanceTrackingData::DataType::Complete); - data.init(this); - data.m_formattedTimeTaken = formattedTime; - PerformanceTrackingCallback* callback = nullptr; - for (const std::pair& h - : ELPP->m_performanceTrackingCallbacks) { - callback = h.second.get(); - if (callback != nullptr && callback->enabled()) { - callback->handle(&data); - } - } - } - } -#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) -} - -void PerformanceTracker::checkpoint(const std::string& id, const char* file, base::type::LineNumber line, - const char* func) { -#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED - if (m_enabled) { - base::threading::ScopedLock scopedLock(lock()); - base::utils::DateTime::gettimeofday(&m_endTime); - base::type::string_t formattedTime = m_hasChecked ? getFormattedTimeTaken(m_lastCheckpointTime) : ELPP_LITERAL(""); - PerformanceTrackingData data(PerformanceTrackingData::DataType::Checkpoint); - data.init(this); - data.m_checkpointId = id; - data.m_file = file; - data.m_line = line; - data.m_func = func; - data.m_formattedTimeTaken = formattedTime; - PerformanceTrackingCallback* callback = nullptr; - for (const std::pair& h - : ELPP->m_performanceTrackingCallbacks) { - callback = h.second.get(); - if (callback != nullptr && callback->enabled()) { - callback->handle(&data); - } - } - base::utils::DateTime::gettimeofday(&m_lastCheckpointTime); - m_hasChecked = true; - m_lastCheckpointId = id; - } -#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED - ELPP_UNUSED(id); - ELPP_UNUSED(file); - ELPP_UNUSED(line); - ELPP_UNUSED(func); -} - -const base::type::string_t PerformanceTracker::getFormattedTimeTaken(struct timeval startTime) const { - if (ELPP->hasFlag(LoggingFlag::FixedTimeFormat)) { - base::type::stringstream_t ss; - ss << base::utils::DateTime::getTimeDifference(m_endTime, - startTime, m_timestampUnit) << " " << base::consts::kTimeFormats[static_cast - (m_timestampUnit)].unit; - return ss.str(); - } - return base::utils::DateTime::formatTime(base::utils::DateTime::getTimeDifference(m_endTime, - startTime, m_timestampUnit), m_timestampUnit); -} - -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - -namespace debug { -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - -// StackTrace - -StackTrace::StackTraceEntry::StackTraceEntry(std::size_t index, const std::string& loc, const std::string& demang, - const std::string& hex, - const std::string& addr) : - m_index(index), - m_location(loc), - m_demangled(demang), - m_hex(hex), - m_addr(addr) { -} - -std::ostream& operator<<(std::ostream& ss, const StackTrace::StackTraceEntry& si) { - ss << "[" << si.m_index << "] " << si.m_location << (si.m_hex.empty() ? "" : "+") << si.m_hex << " " << si.m_addr << - (si.m_demangled.empty() ? "" : ":") << si.m_demangled; - return ss; -} - -std::ostream& operator<<(std::ostream& os, const StackTrace& st) { - std::vector::const_iterator it = st.m_stack.begin(); - while (it != st.m_stack.end()) { - os << " " << *it++ << "\n"; - } - return os; -} - -void StackTrace::generateNew(void) { -#ifdef HAVE_EXECINFO - m_stack.clear(); - void* stack[kMaxStack]; - unsigned int size = backtrace(stack, kMaxStack); - char** strings = backtrace_symbols(stack, size); - if (size > kStackStart) { // Skip StackTrace c'tor and generateNew - for (std::size_t i = kStackStart; i < size; ++i) { - std::string mangName; - std::string location; - std::string hex; - std::string addr; - - // entry: 2 crash.cpp.bin 0x0000000101552be5 _ZN2el4base5debug10StackTraceC1Ev + 21 - const std::string line(strings[i]); - auto p = line.find("_"); - if (p != std::string::npos) { - mangName = line.substr(p); - mangName = mangName.substr(0, mangName.find(" +")); - } - p = line.find("0x"); - if (p != std::string::npos) { - addr = line.substr(p); - addr = addr.substr(0, addr.find("_")); - } - // Perform demangling if parsed properly - if (!mangName.empty()) { - int status = 0; - char* demangName = abi::__cxa_demangle(mangName.data(), 0, 0, &status); - // if demangling is successful, output the demangled function name - if (status == 0) { - // Success (see http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html) - StackTraceEntry entry(i - 1, location, demangName, hex, addr); - m_stack.push_back(entry); - } else { - // Not successful - we will use mangled name - StackTraceEntry entry(i - 1, location, mangName, hex, addr); - m_stack.push_back(entry); - } - free(demangName); - } else { - StackTraceEntry entry(i - 1, line); - m_stack.push_back(entry); - } - } - } - free(strings); -#else - ELPP_INTERNAL_INFO(1, "Stacktrace generation not supported for selected compiler"); -#endif // ELPP_STACKTRACE -} - -// Static helper functions - -static std::string crashReason(int sig) { - std::stringstream ss; - bool foundReason = false; - for (int i = 0; i < base::consts::kCrashSignalsCount; ++i) { - if (base::consts::kCrashSignals[i].numb == sig) { - ss << "Application has crashed due to [" << base::consts::kCrashSignals[i].name << "] signal"; - if (ELPP->hasFlag(el::LoggingFlag::LogDetailedCrashReason)) { - ss << std::endl << - " " << base::consts::kCrashSignals[i].brief << std::endl << - " " << base::consts::kCrashSignals[i].detail; - } - foundReason = true; - } - } - if (!foundReason) { - ss << "Application has crashed due to unknown signal [" << sig << "]"; - } - return ss.str(); -} -/// @brief Logs reason of crash from sig -static void logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) { - if (sig == SIGINT && ELPP->hasFlag(el::LoggingFlag::IgnoreSigInt)) { - return; - } - std::stringstream ss; - ss << "CRASH HANDLED; "; - ss << crashReason(sig); -#if ELPP_STACKTRACE - if (stackTraceIfAvailable) { - ss << std::endl << " ======= Backtrace: =========" << std::endl << base::debug::StackTrace(); - } -#else - ELPP_UNUSED(stackTraceIfAvailable); -#endif // ELPP_STACKTRACE - ELPP_WRITE_LOG(el::base::Writer, level, base::DispatchAction::NormalLog, logger) << ss.str(); -} - -static inline void crashAbort(int sig) { - base::utils::abort(sig, std::string()); -} - -/// @brief Default application crash handler -/// -/// @detail This function writes log using 'default' logger, prints stack trace for GCC based compilers and aborts program. -static inline void defaultCrashHandler(int sig) { - base::debug::logCrashReason(sig, true, Level::Fatal, base::consts::kDefaultLoggerId); - base::debug::crashAbort(sig); -} - -// CrashHandler - -CrashHandler::CrashHandler(bool useDefault) { - if (useDefault) { - setHandler(defaultCrashHandler); - } -} - -void CrashHandler::setHandler(const Handler& cHandler) { - m_handler = cHandler; -#if defined(ELPP_HANDLE_SIGABRT) - int i = 0; // SIGABRT is at base::consts::kCrashSignals[0] -#else - int i = 1; -#endif // defined(ELPP_HANDLE_SIGABRT) - for (; i < base::consts::kCrashSignalsCount; ++i) { - m_handler = signal(base::consts::kCrashSignals[i].numb, cHandler); - } -} - -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) -} // namespace debug -} // namespace base - -// el - -// Helpers - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - -void Helpers::crashAbort(int sig, const char* sourceFile, unsigned int long line) { - std::stringstream ss; - ss << base::debug::crashReason(sig).c_str(); - ss << " - [Called el::Helpers::crashAbort(" << sig << ")]"; - if (sourceFile != nullptr && strlen(sourceFile) > 0) { - ss << " - Source: " << sourceFile; - if (line > 0) - ss << ":" << line; - else - ss << " (line number not specified)"; - } - base::utils::abort(sig, ss.str()); -} - -void Helpers::logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) { - el::base::debug::logCrashReason(sig, stackTraceIfAvailable, level, logger); -} - -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - -// Loggers - -Logger* Loggers::getLogger(const std::string& identity, bool registerIfNotAvailable) { - return ELPP->registeredLoggers()->get(identity, registerIfNotAvailable); -} - -void Loggers::setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr) { - ELPP->registeredLoggers()->setDefaultLogBuilder(logBuilderPtr); -} - -bool Loggers::unregisterLogger(const std::string& identity) { - return ELPP->registeredLoggers()->remove(identity); -} - -bool Loggers::hasLogger(const std::string& identity) { - return ELPP->registeredLoggers()->has(identity); -} - -Logger* Loggers::reconfigureLogger(Logger* logger, const Configurations& configurations) { - if (!logger) return nullptr; - logger->configure(configurations); - return logger; -} - -Logger* Loggers::reconfigureLogger(const std::string& identity, const Configurations& configurations) { - return Loggers::reconfigureLogger(Loggers::getLogger(identity), configurations); -} - -Logger* Loggers::reconfigureLogger(const std::string& identity, ConfigurationType configurationType, - const std::string& value) { - Logger* logger = Loggers::getLogger(identity); - if (logger == nullptr) { - return nullptr; - } - logger->configurations()->set(Level::Global, configurationType, value); - logger->reconfigure(); - return logger; -} - -void Loggers::reconfigureAllLoggers(const Configurations& configurations) { - for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin(); - it != ELPP->registeredLoggers()->end(); ++it) { - Loggers::reconfigureLogger(it->second, configurations); - } -} - -void Loggers::reconfigureAllLoggers(Level level, ConfigurationType configurationType, - const std::string& value) { - for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin(); - it != ELPP->registeredLoggers()->end(); ++it) { - Logger* logger = it->second; - logger->configurations()->set(level, configurationType, value); - logger->reconfigure(); - } -} - -void Loggers::setDefaultConfigurations(const Configurations& configurations, bool reconfigureExistingLoggers) { - ELPP->registeredLoggers()->setDefaultConfigurations(configurations); - if (reconfigureExistingLoggers) { - Loggers::reconfigureAllLoggers(configurations); - } -} - -const Configurations* Loggers::defaultConfigurations(void) { - return ELPP->registeredLoggers()->defaultConfigurations(); -} - -const base::LogStreamsReferenceMapPtr Loggers::logStreamsReference(void) { - return ELPP->registeredLoggers()->logStreamsReference(); -} - -base::TypedConfigurations Loggers::defaultTypedConfigurations(void) { - return base::TypedConfigurations( - ELPP->registeredLoggers()->defaultConfigurations(), - ELPP->registeredLoggers()->logStreamsReference()); -} - -std::vector* Loggers::populateAllLoggerIds(std::vector* targetList) { - targetList->clear(); - for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->list().begin(); - it != ELPP->registeredLoggers()->list().end(); ++it) { - targetList->push_back(it->first); - } - return targetList; -} - -void Loggers::configureFromGlobal(const char* globalConfigurationFilePath) { - std::ifstream gcfStream(globalConfigurationFilePath, std::ifstream::in); - ELPP_ASSERT(gcfStream.is_open(), "Unable to open global configuration file [" << globalConfigurationFilePath - << "] for parsing."); - std::string line = std::string(); - std::stringstream ss; - Logger* logger = nullptr; - auto configure = [&](void) { - ELPP_INTERNAL_INFO(8, "Configuring logger: '" << logger->id() << "' with configurations \n" << ss.str() - << "\n--------------"); - Configurations c; - c.parseFromText(ss.str()); - logger->configure(c); - }; - while (gcfStream.good()) { - std::getline(gcfStream, line); - ELPP_INTERNAL_INFO(1, "Parsing line: " << line); - base::utils::Str::trim(line); - if (Configurations::Parser::isComment(line)) continue; - Configurations::Parser::ignoreComments(&line); - base::utils::Str::trim(line); - if (line.size() > 2 && base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLoggerId))) { - if (!ss.str().empty() && logger != nullptr) { - configure(); - } - ss.str(std::string("")); - line = line.substr(2); - base::utils::Str::trim(line); - if (line.size() > 1) { - ELPP_INTERNAL_INFO(1, "Getting logger: '" << line << "'"); - logger = getLogger(line); - } - } else { - ss << line << "\n"; - } - } - if (!ss.str().empty() && logger != nullptr) { - configure(); - } -} - -bool Loggers::configureFromArg(const char* argKey) { -#if defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS) - ELPP_UNUSED(argKey); -#else - if (!Helpers::commandLineArgs()->hasParamWithValue(argKey)) { - return false; - } - configureFromGlobal(Helpers::commandLineArgs()->getParamValue(argKey)); -#endif // defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS) - return true; -} - -void Loggers::flushAll(void) { - ELPP->registeredLoggers()->flushAll(); -} - -void Loggers::setVerboseLevel(base::type::VerboseLevel level) { - ELPP->vRegistry()->setLevel(level); -} - -base::type::VerboseLevel Loggers::verboseLevel(void) { - return ELPP->vRegistry()->level(); -} - -void Loggers::setVModules(const char* modules) { - if (ELPP->vRegistry()->vModulesEnabled()) { - ELPP->vRegistry()->setModules(modules); - } -} - -void Loggers::clearVModules(void) { - ELPP->vRegistry()->clearModules(); -} - -// VersionInfo - -const std::string VersionInfo::version(void) { - return std::string("9.96.7"); -} -/// @brief Release date of current version -const std::string VersionInfo::releaseDate(void) { - return std::string("24-11-2018 0728hrs"); -} - -} // namespace el diff --git a/third-party/easylogging++/easylogging++.h b/third-party/easylogging++/easylogging++.h deleted file mode 100644 index a5c9acf6..00000000 --- a/third-party/easylogging++/easylogging++.h +++ /dev/null @@ -1,4585 +0,0 @@ -// -// Bismillah ar-Rahmaan ar-Raheem -// -// Easylogging++ v9.96.7 -// Single-header only, cross-platform logging library for C++ applications -// -// Copyright (c) 2012-2018 Amrayn Web Services -// Copyright (c) 2012-2018 @abumusamq -// -// This library is released under the MIT Licence. -// https://github.com/amrayn/easyloggingpp/blob/master/LICENSE -// -// https://amrayn.com -// http://muflihun.com -// - -#ifndef EASYLOGGINGPP_H -#define EASYLOGGINGPP_H -// Compilers and C++0x/C++11 Evaluation -#if __cplusplus >= 201103L -# define ELPP_CXX11 1 -#endif // __cplusplus >= 201103L -#if (defined(__GNUC__)) -# define ELPP_COMPILER_GCC 1 -#else -# define ELPP_COMPILER_GCC 0 -#endif -#if ELPP_COMPILER_GCC -# define ELPP_GCC_VERSION (__GNUC__ * 10000 \ -+ __GNUC_MINOR__ * 100 \ -+ __GNUC_PATCHLEVEL__) -# if defined(__GXX_EXPERIMENTAL_CXX0X__) -# define ELPP_CXX0X 1 -# endif -#endif -// Visual C++ -#if defined(_MSC_VER) -# define ELPP_COMPILER_MSVC 1 -#else -# define ELPP_COMPILER_MSVC 0 -#endif -#define ELPP_CRT_DBG_WARNINGS ELPP_COMPILER_MSVC -#if ELPP_COMPILER_MSVC -# if (_MSC_VER == 1600) -# define ELPP_CXX0X 1 -# elif(_MSC_VER >= 1700) -# define ELPP_CXX11 1 -# endif -#endif -// Clang++ -#if (defined(__clang__) && (__clang__ == 1)) -# define ELPP_COMPILER_CLANG 1 -#else -# define ELPP_COMPILER_CLANG 0 -#endif -#if ELPP_COMPILER_CLANG -# if __has_include() -# include // Make __GLIBCXX__ defined when using libstdc++ -# if !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426 -# define ELPP_CLANG_SUPPORTS_THREAD -# endif // !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426 -# endif // __has_include() -#endif -#if (defined(__MINGW32__) || defined(__MINGW64__)) -# define ELPP_MINGW 1 -#else -# define ELPP_MINGW 0 -#endif -#if (defined(__CYGWIN__) && (__CYGWIN__ == 1)) -# define ELPP_CYGWIN 1 -#else -# define ELPP_CYGWIN 0 -#endif -#if (defined(__INTEL_COMPILER)) -# define ELPP_COMPILER_INTEL 1 -#else -# define ELPP_COMPILER_INTEL 0 -#endif -// Operating System Evaluation -// Windows -#if (defined(_WIN32) || defined(_WIN64)) -# define ELPP_OS_WINDOWS 1 -#else -# define ELPP_OS_WINDOWS 0 -#endif -// Linux -#if (defined(__linux) || defined(__linux__)) -# define ELPP_OS_LINUX 1 -#else -# define ELPP_OS_LINUX 0 -#endif -#if (defined(__APPLE__)) -# define ELPP_OS_MAC 1 -#else -# define ELPP_OS_MAC 0 -#endif -#if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) -# define ELPP_OS_FREEBSD 1 -#else -# define ELPP_OS_FREEBSD 0 -#endif -#if (defined(__sun)) -# define ELPP_OS_SOLARIS 1 -#else -# define ELPP_OS_SOLARIS 0 -#endif -#if (defined(_AIX)) -# define ELPP_OS_AIX 1 -#else -# define ELPP_OS_AIX 0 -#endif -#if (defined(__NetBSD__)) -# define ELPP_OS_NETBSD 1 -#else -# define ELPP_OS_NETBSD 0 -#endif -#if defined(__EMSCRIPTEN__) -# define ELPP_OS_EMSCRIPTEN 1 -#else -# define ELPP_OS_EMSCRIPTEN 0 -#endif -#if (defined(__QNX__) || defined(__QNXNTO__)) -# define ELPP_OS_QNX 1 -#else -# define ELPP_OS_QNX 0 -#endif -// Unix -#if ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_NETBSD || ELPP_OS_SOLARIS || ELPP_OS_AIX || ELPP_OS_EMSCRIPTEN || ELPP_OS_QNX) && (!ELPP_OS_WINDOWS)) -# define ELPP_OS_UNIX 1 -#else -# define ELPP_OS_UNIX 0 -#endif -#if (defined(__ANDROID__)) -# define ELPP_OS_ANDROID 1 -#else -# define ELPP_OS_ANDROID 0 -#endif -// Evaluating Cygwin as *nix OS -#if !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN -# undef ELPP_OS_UNIX -# undef ELPP_OS_LINUX -# define ELPP_OS_UNIX 1 -# define ELPP_OS_LINUX 1 -#endif // !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN -#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_INFO) -# define ELPP_INTERNAL_DEBUGGING_OUT_INFO std::cout -#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) -#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_ERROR) -# define ELPP_INTERNAL_DEBUGGING_OUT_ERROR std::cerr -#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) -#if !defined(ELPP_INTERNAL_DEBUGGING_ENDL) -# define ELPP_INTERNAL_DEBUGGING_ENDL std::endl -#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) -#if !defined(ELPP_INTERNAL_DEBUGGING_MSG) -# define ELPP_INTERNAL_DEBUGGING_MSG(msg) msg -#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) -// Internal Assertions and errors -#if !defined(ELPP_DISABLE_ASSERT) -# if (defined(ELPP_DEBUG_ASSERT_FAILURE)) -# define ELPP_ASSERT(expr, msg) if (!(expr)) { \ -std::stringstream internalInfoStream; internalInfoStream << msg; \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR \ -<< "EASYLOGGING++ ASSERTION FAILED (LINE: " << __LINE__ << ") [" #expr << "] WITH MESSAGE \"" \ -<< ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" << ELPP_INTERNAL_DEBUGGING_ENDL; base::utils::abort(1, \ -"ELPP Assertion failure, please define ELPP_DEBUG_ASSERT_FAILURE"); } -# else -# define ELPP_ASSERT(expr, msg) if (!(expr)) { \ -std::stringstream internalInfoStream; internalInfoStream << msg; \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR\ -<< "ASSERTION FAILURE FROM EASYLOGGING++ (LINE: " \ -<< __LINE__ << ") [" #expr << "] WITH MESSAGE \"" << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" \ -<< ELPP_INTERNAL_DEBUGGING_ENDL; } -# endif // (defined(ELPP_DEBUG_ASSERT_FAILURE)) -#else -# define ELPP_ASSERT(x, y) -#endif //(!defined(ELPP_DISABLE_ASSERT) -#if ELPP_COMPILER_MSVC -# define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \ -{ char buff[256]; strerror_s(buff, 256, errno); \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << buff << " [" << errno << "]";} (void)0 -#else -# define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << strerror(errno) << " [" << errno << "]"; (void)0 -#endif // ELPP_COMPILER_MSVC -#if defined(ELPP_DEBUG_ERRORS) -# if !defined(ELPP_INTERNAL_ERROR) -# define ELPP_INTERNAL_ERROR(msg, pe) { \ -std::stringstream internalInfoStream; internalInfoStream << " " << msg; \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR \ -<< "ERROR FROM EASYLOGGING++ (LINE: " << __LINE__ << ") " \ -<< ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << ELPP_INTERNAL_DEBUGGING_ENDL; \ -if (pe) { ELPP_INTERNAL_DEBUGGING_OUT_ERROR << " "; ELPP_INTERNAL_DEBUGGING_WRITE_PERROR; }} (void)0 -# endif -#else -# undef ELPP_INTERNAL_INFO -# define ELPP_INTERNAL_ERROR(msg, pe) -#endif // defined(ELPP_DEBUG_ERRORS) -#if (defined(ELPP_DEBUG_INFO)) -# if !(defined(ELPP_INTERNAL_INFO_LEVEL)) -# define ELPP_INTERNAL_INFO_LEVEL 9 -# endif // !(defined(ELPP_INTERNAL_INFO_LEVEL)) -# if !defined(ELPP_INTERNAL_INFO) -# define ELPP_INTERNAL_INFO(lvl, msg) { if (lvl <= ELPP_INTERNAL_INFO_LEVEL) { \ -std::stringstream internalInfoStream; internalInfoStream << " " << msg; \ -ELPP_INTERNAL_DEBUGGING_OUT_INFO << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) \ -<< ELPP_INTERNAL_DEBUGGING_ENDL; }} -# endif -#else -# undef ELPP_INTERNAL_INFO -# define ELPP_INTERNAL_INFO(lvl, msg) -#endif // (defined(ELPP_DEBUG_INFO)) -#if (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG)) -# if (ELPP_COMPILER_GCC && !ELPP_MINGW && !ELPP_CYGWIN && !ELPP_OS_ANDROID && !ELPP_OS_EMSCRIPTEN && !ELPP_OS_QNX) -# define ELPP_STACKTRACE 1 -# else -# if ELPP_COMPILER_MSVC -# pragma message("Stack trace not available for this compiler") -# else -# warning "Stack trace not available for this compiler"; -# endif // ELPP_COMPILER_MSVC -# define ELPP_STACKTRACE 0 -# endif // ELPP_COMPILER_GCC -#else -# define ELPP_STACKTRACE 0 -#endif // (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG)) -// Miscellaneous macros -#define ELPP_UNUSED(x) (void)x -#if ELPP_OS_UNIX -// Log file permissions for unix-based systems -# define ELPP_LOG_PERMS S_IRUSR | S_IWUSR | S_IXUSR | S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IXOTH -#endif // ELPP_OS_UNIX -#if defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC -# if defined(ELPP_EXPORT_SYMBOLS) -# define ELPP_EXPORT __declspec(dllexport) -# else -# define ELPP_EXPORT __declspec(dllimport) -# endif // defined(ELPP_EXPORT_SYMBOLS) -#else -# define ELPP_EXPORT -#endif // defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC -// Some special functions that are VC++ specific -#undef STRTOK -#undef STRERROR -#undef STRCAT -#undef STRCPY -#if ELPP_CRT_DBG_WARNINGS -# define STRTOK(a, b, c) strtok_s(a, b, c) -# define STRERROR(a, b, c) strerror_s(a, b, c) -# define STRCAT(a, b, len) strcat_s(a, len, b) -# define STRCPY(a, b, len) strcpy_s(a, len, b) -#else -# define STRTOK(a, b, c) strtok(a, b) -# define STRERROR(a, b, c) strerror(c) -# define STRCAT(a, b, len) strcat(a, b) -# define STRCPY(a, b, len) strcpy(a, b) -#endif -// Compiler specific support evaluations -#if (ELPP_MINGW && !defined(ELPP_FORCE_USE_STD_THREAD)) -# define ELPP_USE_STD_THREADING 0 -#else -# if ((ELPP_COMPILER_CLANG && defined(ELPP_CLANG_SUPPORTS_THREAD)) || \ - (!ELPP_COMPILER_CLANG && defined(ELPP_CXX11)) || \ - defined(ELPP_FORCE_USE_STD_THREAD)) -# define ELPP_USE_STD_THREADING 1 -# else -# define ELPP_USE_STD_THREADING 0 -# endif -#endif -#undef ELPP_FINAL -#if ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702) -# define ELPP_FINAL -#else -# define ELPP_FINAL final -#endif // ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702) -#if defined(ELPP_EXPERIMENTAL_ASYNC) -# define ELPP_ASYNC_LOGGING 1 -#else -# define ELPP_ASYNC_LOGGING 0 -#endif // defined(ELPP_EXPERIMENTAL_ASYNC) -#if defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING -# define ELPP_THREADING_ENABLED 1 -#else -# define ELPP_THREADING_ENABLED 0 -#endif // defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING -// Function macro ELPP_FUNC -#undef ELPP_FUNC -#if ELPP_COMPILER_MSVC // Visual C++ -# define ELPP_FUNC __FUNCSIG__ -#elif ELPP_COMPILER_GCC // GCC -# define ELPP_FUNC __PRETTY_FUNCTION__ -#elif ELPP_COMPILER_INTEL // Intel C++ -# define ELPP_FUNC __PRETTY_FUNCTION__ -#elif ELPP_COMPILER_CLANG // Clang++ -# define ELPP_FUNC __PRETTY_FUNCTION__ -#else -# if defined(__func__) -# define ELPP_FUNC __func__ -# else -# define ELPP_FUNC "" -# endif // defined(__func__) -#endif // defined(_MSC_VER) -#undef ELPP_VARIADIC_TEMPLATES_SUPPORTED -// Keep following line commented until features are fixed -#define ELPP_VARIADIC_TEMPLATES_SUPPORTED \ -(ELPP_COMPILER_GCC || ELPP_COMPILER_CLANG || ELPP_COMPILER_INTEL || (ELPP_COMPILER_MSVC && _MSC_VER >= 1800)) -// Logging Enable/Disable macros -#if defined(ELPP_DISABLE_LOGS) -#define ELPP_LOGGING_ENABLED 0 -#else -#define ELPP_LOGGING_ENABLED 1 -#endif -#if (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_DEBUG_LOG 1 -#else -# define ELPP_DEBUG_LOG 0 -#endif // (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_INFO_LOG 1 -#else -# define ELPP_INFO_LOG 0 -#endif // (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_WARNING_LOG 1 -#else -# define ELPP_WARNING_LOG 0 -#endif // (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_ERROR_LOG 1 -#else -# define ELPP_ERROR_LOG 0 -#endif // (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_FATAL_LOG 1 -#else -# define ELPP_FATAL_LOG 0 -#endif // (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_TRACE_LOG 1 -#else -# define ELPP_TRACE_LOG 0 -#endif // (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_VERBOSE_LOG 1 -#else -# define ELPP_VERBOSE_LOG 0 -#endif // (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!(ELPP_CXX0X || ELPP_CXX11)) -# error "C++0x (or higher) support not detected! (Is `-std=c++11' missing?)" -#endif // (!(ELPP_CXX0X || ELPP_CXX11)) -// Headers -#if defined(ELPP_SYSLOG) -# include -#endif // defined(ELPP_SYSLOG) -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(ELPP_UNICODE) -# include -# if ELPP_OS_WINDOWS -# include -# endif // ELPP_OS_WINDOWS -#endif // defined(ELPP_UNICODE) -#ifdef HAVE_EXECINFO -# include -# include -#endif // ENABLE_EXECINFO -#if ELPP_OS_ANDROID -# include -#endif // ELPP_OS_ANDROID -#if ELPP_OS_UNIX -# include -# include -#elif ELPP_OS_WINDOWS -# include -# include -# if defined(WIN32_LEAN_AND_MEAN) -# if defined(ELPP_WINSOCK2) -# include -# else -# include -# endif // defined(ELPP_WINSOCK2) -# endif // defined(WIN32_LEAN_AND_MEAN) -#endif // ELPP_OS_UNIX -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if ELPP_THREADING_ENABLED -# if ELPP_USE_STD_THREADING -# include -# include -# else -# if ELPP_OS_UNIX -# include -# endif // ELPP_OS_UNIX -# endif // ELPP_USE_STD_THREADING -#endif // ELPP_THREADING_ENABLED -#if ELPP_ASYNC_LOGGING -# if defined(ELPP_NO_SLEEP_FOR) -# include -# endif // defined(ELPP_NO_SLEEP_FOR) -# include -# include -# include -#endif // ELPP_ASYNC_LOGGING -#if defined(ELPP_STL_LOGGING) -// For logging STL based templates -# include -# include -# include -# include -# include -# include -# if defined(ELPP_LOG_STD_ARRAY) -# include -# endif // defined(ELPP_LOG_STD_ARRAY) -# if defined(ELPP_LOG_UNORDERED_SET) -# include -# endif // defined(ELPP_UNORDERED_SET) -#endif // defined(ELPP_STL_LOGGING) -#if defined(ELPP_QT_LOGGING) -// For logging Qt based classes & templates -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif // defined(ELPP_QT_LOGGING) -#if defined(ELPP_BOOST_LOGGING) -// For logging boost based classes & templates -# include -# include -# include -# include -# include -# include -# include -# include -#endif // defined(ELPP_BOOST_LOGGING) -#if defined(ELPP_WXWIDGETS_LOGGING) -// For logging wxWidgets based classes & templates -# include -#endif // defined(ELPP_WXWIDGETS_LOGGING) -#if defined(ELPP_UTC_DATETIME) -# define elpptime_r gmtime_r -# define elpptime_s gmtime_s -# define elpptime gmtime -#else -# define elpptime_r localtime_r -# define elpptime_s localtime_s -# define elpptime localtime -#endif // defined(ELPP_UTC_DATETIME) -// Forward declarations -namespace el { -class Logger; -class LogMessage; -class PerformanceTrackingData; -class Loggers; -class Helpers; -template class Callback; -class LogDispatchCallback; -class PerformanceTrackingCallback; -class LoggerRegistrationCallback; -class LogDispatchData; -namespace base { -class Storage; -class RegisteredLoggers; -class PerformanceTracker; -class MessageBuilder; -class Writer; -class PErrorWriter; -class LogDispatcher; -class DefaultLogBuilder; -class DefaultLogDispatchCallback; -#if ELPP_ASYNC_LOGGING -class AsyncLogDispatchCallback; -class AsyncDispatchWorker; -#endif // ELPP_ASYNC_LOGGING -class DefaultPerformanceTrackingCallback; -} // namespace base -} // namespace el -/// @brief Easylogging++ entry namespace -namespace el { -/// @brief Namespace containing base/internal functionality used by Easylogging++ -namespace base { -/// @brief Data types used by Easylogging++ -namespace type { -#undef ELPP_LITERAL -#undef ELPP_STRLEN -#undef ELPP_COUT -#if defined(ELPP_UNICODE) -# define ELPP_LITERAL(txt) L##txt -# define ELPP_STRLEN wcslen -# if defined ELPP_CUSTOM_COUT -# define ELPP_COUT ELPP_CUSTOM_COUT -# else -# define ELPP_COUT std::wcout -# endif // defined ELPP_CUSTOM_COUT -typedef wchar_t char_t; -typedef std::wstring string_t; -typedef std::wstringstream stringstream_t; -typedef std::wfstream fstream_t; -typedef std::wostream ostream_t; -#else -# define ELPP_LITERAL(txt) txt -# define ELPP_STRLEN strlen -# if defined ELPP_CUSTOM_COUT -# define ELPP_COUT ELPP_CUSTOM_COUT -# else -# define ELPP_COUT std::cout -# endif // defined ELPP_CUSTOM_COUT -typedef char char_t; -typedef std::string string_t; -typedef std::stringstream stringstream_t; -typedef std::fstream fstream_t; -typedef std::ostream ostream_t; -#endif // defined(ELPP_UNICODE) -#if defined(ELPP_CUSTOM_COUT_LINE) -# define ELPP_COUT_LINE(logLine) ELPP_CUSTOM_COUT_LINE(logLine) -#else -# define ELPP_COUT_LINE(logLine) logLine << std::flush -#endif // defined(ELPP_CUSTOM_COUT_LINE) -typedef unsigned int EnumType; -typedef unsigned short VerboseLevel; -typedef unsigned long int LineNumber; -typedef std::shared_ptr StoragePointer; -typedef std::shared_ptr LogDispatchCallbackPtr; -typedef std::shared_ptr PerformanceTrackingCallbackPtr; -typedef std::shared_ptr LoggerRegistrationCallbackPtr; -typedef std::unique_ptr PerformanceTrackerPtr; -} // namespace type -/// @brief Internal helper class that prevent copy constructor for class -/// -/// @detail When using this class simply inherit it privately -class NoCopy { - protected: - NoCopy(void) {} - private: - NoCopy(const NoCopy&); - NoCopy& operator=(const NoCopy&); -}; -/// @brief Internal helper class that makes all default constructors private. -/// -/// @detail This prevents initializing class making it static unless an explicit constructor is declared. -/// When using this class simply inherit it privately -class StaticClass { - private: - StaticClass(void); - StaticClass(const StaticClass&); - StaticClass& operator=(const StaticClass&); -}; -} // namespace base -/// @brief Represents enumeration for severity level used to determine level of logging -/// -/// @detail With Easylogging++, developers may disable or enable any level regardless of -/// what the severity is. Or they can choose to log using hierarchical logging flag -enum class Level : base::type::EnumType { - /// @brief Generic level that represents all the levels. Useful when setting global configuration for all levels - Global = 1, - /// @brief Information that can be useful to back-trace certain events - mostly useful than debug logs. - Trace = 2, - /// @brief Informational events most useful for developers to debug application - Debug = 4, - /// @brief Severe error information that will presumably abort application - Fatal = 8, - /// @brief Information representing errors in application but application will keep running - Error = 16, - /// @brief Useful when application has potentially harmful situations - Warning = 32, - /// @brief Information that can be highly useful and vary with verbose logging level. - Verbose = 64, - /// @brief Mainly useful to represent current progress of application - Info = 128, - /// @brief Represents unknown level - Unknown = 1010 -}; -} // namespace el -namespace std { -template<> struct hash { - public: - std::size_t operator()(const el::Level& l) const { - return hash {}(static_cast(l)); - } -}; -} -namespace el { -/// @brief Static class that contains helper functions for el::Level -class LevelHelper : base::StaticClass { - public: - /// @brief Represents minimum valid level. Useful when iterating through enum. - static const base::type::EnumType kMinValid = static_cast(Level::Trace); - /// @brief Represents maximum valid level. This is used internally and you should not need it. - static const base::type::EnumType kMaxValid = static_cast(Level::Info); - /// @brief Casts level to int, useful for iterating through enum. - static base::type::EnumType castToInt(Level level) { - return static_cast(level); - } - /// @brief Casts int(ushort) to level, useful for iterating through enum. - static Level castFromInt(base::type::EnumType l) { - return static_cast(l); - } - /// @brief Converts level to associated const char* - /// @return Upper case string based level. - static const char* convertToString(Level level); - /// @brief Converts from levelStr to Level - /// @param levelStr Upper case string based level. - /// Lower case is also valid but providing upper case is recommended. - static Level convertFromString(const char* levelStr); - /// @brief Applies specified function to each level starting from startIndex - /// @param startIndex initial value to start the iteration from. This is passed as pointer and - /// is left-shifted so this can be used inside function (fn) to represent current level. - /// @param fn function to apply with each level. This bool represent whether or not to stop iterating through levels. - static void forEachLevel(base::type::EnumType* startIndex, const std::function& fn); -}; -/// @brief Represents enumeration of ConfigurationType used to configure or access certain aspect -/// of logging -enum class ConfigurationType : base::type::EnumType { - /// @brief Determines whether or not corresponding level and logger of logging is enabled - /// You may disable all logs by using el::Level::Global - Enabled = 1, - /// @brief Whether or not to write corresponding log to log file - ToFile = 2, - /// @brief Whether or not to write corresponding level and logger log to standard output. - /// By standard output meaning termnal, command prompt etc - ToStandardOutput = 4, - /// @brief Determines format of logging corresponding level and logger. - Format = 8, - /// @brief Determines log file (full path) to write logs to for corresponding level and logger - Filename = 16, - /// @brief Specifies precision of the subsecond part. It should be within range (1-6). - SubsecondPrecision = 32, - /// @brief Alias of SubsecondPrecision (for backward compatibility) - MillisecondsWidth = SubsecondPrecision, - /// @brief Determines whether or not performance tracking is enabled. - /// - /// @detail This does not depend on logger or level. Performance tracking always uses 'performance' logger - PerformanceTracking = 64, - /// @brief Specifies log file max size. - /// - /// @detail If file size of corresponding log file (for corresponding level) is >= specified size, log file will - /// be truncated and re-initiated. - MaxLogFileSize = 128, - /// @brief Specifies number of log entries to hold until we flush pending log data - LogFlushThreshold = 256, - /// @brief Represents unknown configuration - Unknown = 1010 -}; -/// @brief Static class that contains helper functions for el::ConfigurationType -class ConfigurationTypeHelper : base::StaticClass { - public: - /// @brief Represents minimum valid configuration type. Useful when iterating through enum. - static const base::type::EnumType kMinValid = static_cast(ConfigurationType::Enabled); - /// @brief Represents maximum valid configuration type. This is used internally and you should not need it. - static const base::type::EnumType kMaxValid = static_cast(ConfigurationType::MaxLogFileSize); - /// @brief Casts configuration type to int, useful for iterating through enum. - static base::type::EnumType castToInt(ConfigurationType configurationType) { - return static_cast(configurationType); - } - /// @brief Casts int(ushort) to configuration type, useful for iterating through enum. - static ConfigurationType castFromInt(base::type::EnumType c) { - return static_cast(c); - } - /// @brief Converts configuration type to associated const char* - /// @returns Upper case string based configuration type. - static const char* convertToString(ConfigurationType configurationType); - /// @brief Converts from configStr to ConfigurationType - /// @param configStr Upper case string based configuration type. - /// Lower case is also valid but providing upper case is recommended. - static ConfigurationType convertFromString(const char* configStr); - /// @brief Applies specified function to each configuration type starting from startIndex - /// @param startIndex initial value to start the iteration from. This is passed by pointer and is left-shifted - /// so this can be used inside function (fn) to represent current configuration type. - /// @param fn function to apply with each configuration type. - /// This bool represent whether or not to stop iterating through configurations. - static inline void forEachConfigType(base::type::EnumType* startIndex, const std::function& fn); -}; -/// @brief Flags used while writing logs. This flags are set by user -enum class LoggingFlag : base::type::EnumType { - /// @brief Makes sure we have new line for each container log entry - NewLineForContainer = 1, - /// @brief Makes sure if -vmodule is used and does not specifies a module, then verbose - /// logging is allowed via that module. - AllowVerboseIfModuleNotSpecified = 2, - /// @brief When handling crashes by default, detailed crash reason will be logged as well - LogDetailedCrashReason = 4, - /// @brief Allows to disable application abortion when logged using FATAL level - DisableApplicationAbortOnFatalLog = 8, - /// @brief Flushes log with every log-entry (performance sensitive) - Disabled by default - ImmediateFlush = 16, - /// @brief Enables strict file rolling - StrictLogFileSizeCheck = 32, - /// @brief Make terminal output colorful for supported terminals - ColoredTerminalOutput = 64, - /// @brief Supports use of multiple logging in same macro, e.g, CLOG(INFO, "default", "network") - MultiLoggerSupport = 128, - /// @brief Disables comparing performance tracker's checkpoints - DisablePerformanceTrackingCheckpointComparison = 256, - /// @brief Disable VModules - DisableVModules = 512, - /// @brief Disable VModules extensions - DisableVModulesExtensions = 1024, - /// @brief Enables hierarchical logging - HierarchicalLogging = 2048, - /// @brief Creates logger automatically when not available - CreateLoggerAutomatically = 4096, - /// @brief Adds spaces b/w logs that separated by left-shift operator - AutoSpacing = 8192, - /// @brief Preserves time format and does not convert it to sec, hour etc (performance tracking only) - FixedTimeFormat = 16384, - // @brief Ignore SIGINT or crash - IgnoreSigInt = 32768, -}; -namespace base { -/// @brief Namespace containing constants used internally. -namespace consts { -static const char kFormatSpecifierCharValue = 'v'; -static const char kFormatSpecifierChar = '%'; -static const unsigned int kMaxLogPerCounter = 100000; -static const unsigned int kMaxLogPerContainer = 100; -static const unsigned int kDefaultSubsecondPrecision = 3; - -#ifdef ELPP_DEFAULT_LOGGER -static const char* kDefaultLoggerId = ELPP_DEFAULT_LOGGER; -#else -static const char* kDefaultLoggerId = "default"; -#endif - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) -#ifdef ELPP_DEFAULT_PERFORMANCE_LOGGER -static const char* kPerformanceLoggerId = ELPP_DEFAULT_PERFORMANCE_LOGGER; -#else -static const char* kPerformanceLoggerId = "performance"; -#endif // ELPP_DEFAULT_PERFORMANCE_LOGGER -#endif - -#if defined(ELPP_SYSLOG) -static const char* kSysLogLoggerId = "syslog"; -#endif // defined(ELPP_SYSLOG) - -#if ELPP_OS_WINDOWS -static const char* kFilePathSeparator = "\\"; -#else -static const char* kFilePathSeparator = "/"; -#endif // ELPP_OS_WINDOWS - -static const std::size_t kSourceFilenameMaxLength = 100; -static const std::size_t kSourceLineMaxLength = 10; -static const Level kPerformanceTrackerDefaultLevel = Level::Info; -const struct { - double value; - const base::type::char_t* unit; -} kTimeFormats[] = { - { 1000.0, ELPP_LITERAL("us") }, - { 1000.0, ELPP_LITERAL("ms") }, - { 60.0, ELPP_LITERAL("seconds") }, - { 60.0, ELPP_LITERAL("minutes") }, - { 24.0, ELPP_LITERAL("hours") }, - { 7.0, ELPP_LITERAL("days") } -}; -static const int kTimeFormatsCount = sizeof(kTimeFormats) / sizeof(kTimeFormats[0]); -const struct { - int numb; - const char* name; - const char* brief; - const char* detail; -} kCrashSignals[] = { - // NOTE: Do not re-order, if you do please check CrashHandler(bool) constructor and CrashHandler::setHandler(..) - { - SIGABRT, "SIGABRT", "Abnormal termination", - "Program was abnormally terminated." - }, - { - SIGFPE, "SIGFPE", "Erroneous arithmetic operation", - "Arithmetic operation issue such as division by zero or operation resulting in overflow." - }, - { - SIGILL, "SIGILL", "Illegal instruction", - "Generally due to a corruption in the code or to an attempt to execute data." - }, - { - SIGSEGV, "SIGSEGV", "Invalid access to memory", - "Program is trying to read an invalid (unallocated, deleted or corrupted) or inaccessible memory." - }, - { - SIGINT, "SIGINT", "Interactive attention signal", - "Interruption generated (generally) by user or operating system." - }, -}; -static const int kCrashSignalsCount = sizeof(kCrashSignals) / sizeof(kCrashSignals[0]); -} // namespace consts -} // namespace base -typedef std::function PreRollOutCallback; -namespace base { -static inline void defaultPreRollOutCallback(const char*, std::size_t) {} -/// @brief Enum to represent timestamp unit -enum class TimestampUnit : base::type::EnumType { - Microsecond = 0, Millisecond = 1, Second = 2, Minute = 3, Hour = 4, Day = 5 -}; -/// @brief Format flags used to determine specifiers that are active for performance improvements. -enum class FormatFlags : base::type::EnumType { - DateTime = 1 << 1, - LoggerId = 1 << 2, - File = 1 << 3, - Line = 1 << 4, - Location = 1 << 5, - Function = 1 << 6, - User = 1 << 7, - Host = 1 << 8, - LogMessage = 1 << 9, - VerboseLevel = 1 << 10, - AppName = 1 << 11, - ThreadId = 1 << 12, - Level = 1 << 13, - FileBase = 1 << 14, - LevelShort = 1 << 15 -}; -/// @brief A subsecond precision class containing actual width and offset of the subsecond part -class SubsecondPrecision { - public: - SubsecondPrecision(void) { - init(base::consts::kDefaultSubsecondPrecision); - } - explicit SubsecondPrecision(int width) { - init(width); - } - bool operator==(const SubsecondPrecision& ssPrec) { - return m_width == ssPrec.m_width && m_offset == ssPrec.m_offset; - } - int m_width; - unsigned int m_offset; - private: - void init(int width); -}; -/// @brief Type alias of SubsecondPrecision -typedef SubsecondPrecision MillisecondsWidth; -/// @brief Namespace containing utility functions/static classes used internally -namespace utils { -/// @brief Deletes memory safely and points to null -template -static -typename std::enable_if::value, void>::type -safeDelete(T*& pointer) { - if (pointer == nullptr) - return; - delete pointer; - pointer = nullptr; -} -/// @brief Bitwise operations for C++11 strong enum class. This casts e into Flag_T and returns value after bitwise operation -/// Use these function as
flag = bitwise::Or(MyEnum::val1, flag);
-namespace bitwise { -template -static inline base::type::EnumType And(Enum e, base::type::EnumType flag) { - return static_cast(flag) & static_cast(e); -} -template -static inline base::type::EnumType Not(Enum e, base::type::EnumType flag) { - return static_cast(flag) & ~(static_cast(e)); -} -template -static inline base::type::EnumType Or(Enum e, base::type::EnumType flag) { - return static_cast(flag) | static_cast(e); -} -} // namespace bitwise -template -static inline void addFlag(Enum e, base::type::EnumType* flag) { - *flag = base::utils::bitwise::Or(e, *flag); -} -template -static inline void removeFlag(Enum e, base::type::EnumType* flag) { - *flag = base::utils::bitwise::Not(e, *flag); -} -template -static inline bool hasFlag(Enum e, base::type::EnumType flag) { - return base::utils::bitwise::And(e, flag) > 0x0; -} -} // namespace utils -namespace threading { -#if ELPP_THREADING_ENABLED -# if !ELPP_USE_STD_THREADING -namespace internal { -/// @brief A mutex wrapper for compiler that dont yet support std::recursive_mutex -class Mutex : base::NoCopy { - public: - Mutex(void) { -# if ELPP_OS_UNIX - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&m_underlyingMutex, &attr); - pthread_mutexattr_destroy(&attr); -# elif ELPP_OS_WINDOWS - InitializeCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - virtual ~Mutex(void) { -# if ELPP_OS_UNIX - pthread_mutex_destroy(&m_underlyingMutex); -# elif ELPP_OS_WINDOWS - DeleteCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - inline void lock(void) { -# if ELPP_OS_UNIX - pthread_mutex_lock(&m_underlyingMutex); -# elif ELPP_OS_WINDOWS - EnterCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - inline bool try_lock(void) { -# if ELPP_OS_UNIX - return (pthread_mutex_trylock(&m_underlyingMutex) == 0); -# elif ELPP_OS_WINDOWS - return TryEnterCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - inline void unlock(void) { -# if ELPP_OS_UNIX - pthread_mutex_unlock(&m_underlyingMutex); -# elif ELPP_OS_WINDOWS - LeaveCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - private: -# if ELPP_OS_UNIX - pthread_mutex_t m_underlyingMutex; -# elif ELPP_OS_WINDOWS - CRITICAL_SECTION m_underlyingMutex; -# endif // ELPP_OS_UNIX -}; -/// @brief Scoped lock for compiler that dont yet support std::lock_guard -template -class ScopedLock : base::NoCopy { - public: - explicit ScopedLock(M& mutex) { - m_mutex = &mutex; - m_mutex->lock(); - } - - virtual ~ScopedLock(void) { - m_mutex->unlock(); - } - private: - M* m_mutex; - ScopedLock(void); -}; -} // namespace internal -typedef base::threading::internal::Mutex Mutex; -typedef base::threading::internal::ScopedLock ScopedLock; -# else -typedef std::recursive_mutex Mutex; -typedef std::lock_guard ScopedLock; -# endif // !ELPP_USE_STD_THREADING -#else -namespace internal { -/// @brief Mutex wrapper used when multi-threading is disabled. -class NoMutex : base::NoCopy { - public: - NoMutex(void) {} - inline void lock(void) {} - inline bool try_lock(void) { - return true; - } - inline void unlock(void) {} -}; -/// @brief Lock guard wrapper used when multi-threading is disabled. -template -class NoScopedLock : base::NoCopy { - public: - explicit NoScopedLock(Mutex&) { - } - virtual ~NoScopedLock(void) { - } - private: - NoScopedLock(void); -}; -} // namespace internal -typedef base::threading::internal::NoMutex Mutex; -typedef base::threading::internal::NoScopedLock ScopedLock; -#endif // ELPP_THREADING_ENABLED -/// @brief Base of thread safe class, this class is inheritable-only -class ThreadSafe { - public: - virtual inline void acquireLock(void) ELPP_FINAL { m_mutex.lock(); } - virtual inline void releaseLock(void) ELPP_FINAL { m_mutex.unlock(); } - virtual inline base::threading::Mutex& lock(void) ELPP_FINAL { return m_mutex; } - protected: - ThreadSafe(void) {} - virtual ~ThreadSafe(void) {} - private: - base::threading::Mutex m_mutex; -}; - -#if ELPP_THREADING_ENABLED -# if !ELPP_USE_STD_THREADING -/// @brief Gets ID of currently running threading in windows systems. On unix, nothing is returned. -static std::string getCurrentThreadId(void) { - std::stringstream ss; -# if (ELPP_OS_WINDOWS) - ss << GetCurrentThreadId(); -# endif // (ELPP_OS_WINDOWS) - return ss.str(); -} -# else -/// @brief Gets ID of currently running threading using std::this_thread::get_id() -static std::string getCurrentThreadId(void) { - std::stringstream ss; - ss << std::this_thread::get_id(); - return ss.str(); -} -# endif // !ELPP_USE_STD_THREADING -#else -static inline std::string getCurrentThreadId(void) { - return std::string(); -} -#endif // ELPP_THREADING_ENABLED -} // namespace threading -namespace utils { -class File : base::StaticClass { - public: - /// @brief Creates new out file stream for specified filename. - /// @return Pointer to newly created fstream or nullptr - static base::type::fstream_t* newFileStream(const std::string& filename); - - /// @brief Gets size of file provided in stream - static std::size_t getSizeOfFile(base::type::fstream_t* fs); - - /// @brief Determines whether or not provided path exist in current file system - static bool pathExists(const char* path, bool considerFile = false); - - /// @brief Creates specified path on file system - /// @param path Path to create. - static bool createPath(const std::string& path); - /// @brief Extracts path of filename with leading slash - static std::string extractPathFromFilename(const std::string& fullPath, - const char* separator = base::consts::kFilePathSeparator); - /// @brief builds stripped filename and puts it in buff - static void buildStrippedFilename(const char* filename, char buff[], - std::size_t limit = base::consts::kSourceFilenameMaxLength); - /// @brief builds base filename and puts it in buff - static void buildBaseFilename(const std::string& fullPath, char buff[], - std::size_t limit = base::consts::kSourceFilenameMaxLength, - const char* separator = base::consts::kFilePathSeparator); -}; -/// @brief String utilities helper class used internally. You should not use it. -class Str : base::StaticClass { - public: - /// @brief Checks if character is digit. Dont use libc implementation of it to prevent locale issues. - static inline bool isDigit(char c) { - return c >= '0' && c <= '9'; - } - - /// @brief Matches wildcards, '*' and '?' only supported. - static bool wildCardMatch(const char* str, const char* pattern); - - static std::string& ltrim(std::string& str); - static std::string& rtrim(std::string& str); - static std::string& trim(std::string& str); - - /// @brief Determines whether or not str starts with specified string - /// @param str String to check - /// @param start String to check against - /// @return Returns true if starts with specified string, false otherwise - static bool startsWith(const std::string& str, const std::string& start); - - /// @brief Determines whether or not str ends with specified string - /// @param str String to check - /// @param end String to check against - /// @return Returns true if ends with specified string, false otherwise - static bool endsWith(const std::string& str, const std::string& end); - - /// @brief Replaces all instances of replaceWhat with 'replaceWith'. Original variable is changed for performance. - /// @param [in,out] str String to replace from - /// @param replaceWhat Character to replace - /// @param replaceWith Character to replace with - /// @return Modified version of str - static std::string& replaceAll(std::string& str, char replaceWhat, char replaceWith); - - /// @brief Replaces all instances of 'replaceWhat' with 'replaceWith'. (String version) Replaces in place - /// @param str String to replace from - /// @param replaceWhat Character to replace - /// @param replaceWith Character to replace with - /// @return Modified (original) str - static std::string& replaceAll(std::string& str, const std::string& replaceWhat, - const std::string& replaceWith); - - static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, - const base::type::string_t& replaceWith); -#if defined(ELPP_UNICODE) - static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, - const std::string& replaceWith); -#endif // defined(ELPP_UNICODE) - /// @brief Converts string to uppercase - /// @param str String to convert - /// @return Uppercase string - static std::string& toUpper(std::string& str); - - /// @brief Compares cstring equality - uses strcmp - static bool cStringEq(const char* s1, const char* s2); - - /// @brief Compares cstring equality (case-insensitive) - uses toupper(char) - /// Dont use strcasecmp because of CRT (VC++) - static bool cStringCaseEq(const char* s1, const char* s2); - - /// @brief Returns true if c exist in str - static bool contains(const char* str, char c); - - static char* convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded = true); - static char* addToBuff(const char* str, char* buf, const char* bufLim); - static char* clearBuff(char buff[], std::size_t lim); - - /// @brief Converts wchar* to char* - /// NOTE: Need to free return value after use! - static char* wcharPtrToCharPtr(const wchar_t* line); -}; -/// @brief Operating System helper static class used internally. You should not use it. -class OS : base::StaticClass { - public: -#if ELPP_OS_WINDOWS - /// @brief Gets environment variables for Windows based OS. - /// We are not using getenv(const char*) because of CRT deprecation - /// @param varname Variable name to get environment variable value for - /// @return If variable exist the value of it otherwise nullptr - static const char* getWindowsEnvironmentVariable(const char* varname); -#endif // ELPP_OS_WINDOWS -#if ELPP_OS_ANDROID - /// @brief Reads android property value - static std::string getProperty(const char* prop); - - /// @brief Reads android device name - static std::string getDeviceName(void); -#endif // ELPP_OS_ANDROID - - /// @brief Runs command on terminal and returns the output. - /// - /// @detail This is applicable only on unix based systems, for all other OS, an empty string is returned. - /// @param command Bash command - /// @return Result of bash output or empty string if no result found. - static const std::string getBashOutput(const char* command); - - /// @brief Gets environment variable. This is cross-platform and CRT safe (for VC++) - /// @param variableName Environment variable name - /// @param defaultVal If no environment variable or value found the value to return by default - /// @param alternativeBashCommand If environment variable not found what would be alternative bash command - /// in order to look for value user is looking for. E.g, for 'user' alternative command will 'whoami' - static std::string getEnvironmentVariable(const char* variableName, const char* defaultVal, - const char* alternativeBashCommand = nullptr); - /// @brief Gets current username. - static std::string currentUser(void); - - /// @brief Gets current host name or computer name. - /// - /// @detail For android systems this is device name with its manufacturer and model separated by hyphen - static std::string currentHost(void); - /// @brief Whether or not terminal supports colors - static bool termSupportsColor(void); -}; -/// @brief Contains utilities for cross-platform date/time. This class make use of el::base::utils::Str -class DateTime : base::StaticClass { - public: - /// @brief Cross platform gettimeofday for Windows and unix platform. This can be used to determine current microsecond. - /// - /// @detail For unix system it uses gettimeofday(timeval*, timezone*) and for Windows, a separate implementation is provided - /// @param [in,out] tv Pointer that gets updated - static void gettimeofday(struct timeval* tv); - - /// @brief Gets current date and time with a subsecond part. - /// @param format User provided date/time format - /// @param ssPrec A pointer to base::SubsecondPrecision from configuration (non-null) - /// @returns string based date time in specified format. - static std::string getDateTime(const char* format, const base::SubsecondPrecision* ssPrec); - - /// @brief Converts timeval (struct from ctime) to string using specified format and subsecond precision - static std::string timevalToString(struct timeval tval, const char* format, - const el::base::SubsecondPrecision* ssPrec); - - /// @brief Formats time to get unit accordingly, units like second if > 1000 or minutes if > 60000 etc - static base::type::string_t formatTime(unsigned long long time, base::TimestampUnit timestampUnit); - - /// @brief Gets time difference in milli/micro second depending on timestampUnit - static unsigned long long getTimeDifference(const struct timeval& endTime, const struct timeval& startTime, - base::TimestampUnit timestampUnit); - - - static struct ::tm* buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo); - private: - static char* parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo, - std::size_t msec, const base::SubsecondPrecision* ssPrec); -}; -/// @brief Command line arguments for application if specified using el::Helpers::setArgs(..) or START_EASYLOGGINGPP(..) -class CommandLineArgs { - public: - CommandLineArgs(void) { - setArgs(0, static_cast(nullptr)); - } - CommandLineArgs(int argc, const char** argv) { - setArgs(argc, argv); - } - CommandLineArgs(int argc, char** argv) { - setArgs(argc, argv); - } - virtual ~CommandLineArgs(void) {} - /// @brief Sets arguments and parses them - inline void setArgs(int argc, const char** argv) { - setArgs(argc, const_cast(argv)); - } - /// @brief Sets arguments and parses them - void setArgs(int argc, char** argv); - /// @brief Returns true if arguments contain paramKey with a value (separated by '=') - bool hasParamWithValue(const char* paramKey) const; - /// @brief Returns value of arguments - /// @see hasParamWithValue(const char*) - const char* getParamValue(const char* paramKey) const; - /// @brief Return true if arguments has a param (not having a value) i,e without '=' - bool hasParam(const char* paramKey) const; - /// @brief Returns true if no params available. This exclude argv[0] - bool empty(void) const; - /// @brief Returns total number of arguments. This exclude argv[0] - std::size_t size(void) const; - friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c); - - private: - int m_argc; - char** m_argv; - std::unordered_map m_paramsWithValue; - std::vector m_params; -}; -/// @brief Abstract registry (aka repository) that provides basic interface for pointer repository specified by T_Ptr type. -/// -/// @detail Most of the functions are virtual final methods but anything implementing this abstract class should implement -/// unregisterAll() and deepCopy(const AbstractRegistry&) and write registerNew() method according to container -/// and few more methods; get() to find element, unregister() to unregister single entry. -/// Please note that this is thread-unsafe and should also implement thread-safety mechanisms in implementation. -template -class AbstractRegistry : public base::threading::ThreadSafe { - public: - typedef typename Container::iterator iterator; - typedef typename Container::const_iterator const_iterator; - - /// @brief Default constructor - AbstractRegistry(void) {} - - /// @brief Move constructor that is useful for base classes - AbstractRegistry(AbstractRegistry&& sr) { - if (this == &sr) { - return; - } - unregisterAll(); - m_list = std::move(sr.m_list); - } - - bool operator==(const AbstractRegistry& other) { - if (size() != other.size()) { - return false; - } - for (std::size_t i = 0; i < m_list.size(); ++i) { - if (m_list.at(i) != other.m_list.at(i)) { - return false; - } - } - return true; - } - - bool operator!=(const AbstractRegistry& other) { - if (size() != other.size()) { - return true; - } - for (std::size_t i = 0; i < m_list.size(); ++i) { - if (m_list.at(i) != other.m_list.at(i)) { - return true; - } - } - return false; - } - - /// @brief Assignment move operator - AbstractRegistry& operator=(AbstractRegistry&& sr) { - if (this == &sr) { - return *this; - } - unregisterAll(); - m_list = std::move(sr.m_list); - return *this; - } - - virtual ~AbstractRegistry(void) { - } - - /// @return Iterator pointer from start of repository - virtual inline iterator begin(void) ELPP_FINAL { - return m_list.begin(); - } - - /// @return Iterator pointer from end of repository - virtual inline iterator end(void) ELPP_FINAL { - return m_list.end(); - } - - - /// @return Constant iterator pointer from start of repository - virtual inline const_iterator cbegin(void) const ELPP_FINAL { - return m_list.cbegin(); - } - - /// @return End of repository - virtual inline const_iterator cend(void) const ELPP_FINAL { - return m_list.cend(); - } - - /// @return Whether or not repository is empty - virtual inline bool empty(void) const ELPP_FINAL { - return m_list.empty(); - } - - /// @return Size of repository - virtual inline std::size_t size(void) const ELPP_FINAL { - return m_list.size(); - } - - /// @brief Returns underlying container by reference - virtual inline Container& list(void) ELPP_FINAL { - return m_list; - } - - /// @brief Returns underlying container by constant reference. - virtual inline const Container& list(void) const ELPP_FINAL { - return m_list; - } - - /// @brief Unregisters all the pointers from current repository. - virtual void unregisterAll(void) = 0; - - protected: - virtual void deepCopy(const AbstractRegistry&) = 0; - void reinitDeepCopy(const AbstractRegistry& sr) { - unregisterAll(); - deepCopy(sr); - } - - private: - Container m_list; -}; - -/// @brief A pointer registry mechanism to manage memory and provide search functionalities. (non-predicate version) -/// -/// @detail NOTE: This is thread-unsafe implementation (although it contains lock function, it does not use these functions) -/// of AbstractRegistry. Any implementation of this class should be -/// explicitly (by using lock functions) -template -class Registry : public AbstractRegistry> { - public: - typedef typename Registry::iterator iterator; - typedef typename Registry::const_iterator const_iterator; - - Registry(void) {} - - /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor. - Registry(const Registry& sr) : AbstractRegistry>() { - if (this == &sr) { - return; - } - this->reinitDeepCopy(sr); - } - - /// @brief Assignment operator that unregisters all the existing registries and deeply copies each of repo element - /// @see unregisterAll() - /// @see deepCopy(const AbstractRegistry&) - Registry& operator=(const Registry& sr) { - if (this == &sr) { - return *this; - } - this->reinitDeepCopy(sr); - return *this; - } - - virtual ~Registry(void) { - unregisterAll(); - } - - protected: - virtual void unregisterAll(void) ELPP_FINAL { - if (!this->empty()) { - for (auto&& curr : this->list()) { - base::utils::safeDelete(curr.second); - } - this->list().clear(); - } - } - -/// @brief Registers new registry to repository. - virtual void registerNew(const T_Key& uniqKey, T_Ptr* ptr) ELPP_FINAL { - unregister(uniqKey); - this->list().insert(std::make_pair(uniqKey, ptr)); - } - -/// @brief Unregisters single entry mapped to specified unique key - void unregister(const T_Key& uniqKey) { - T_Ptr* existing = get(uniqKey); - if (existing != nullptr) { - this->list().erase(uniqKey); - base::utils::safeDelete(existing); - } - } - -/// @brief Gets pointer from repository. If none found, nullptr is returned. - T_Ptr* get(const T_Key& uniqKey) { - iterator it = this->list().find(uniqKey); - return it == this->list().end() - ? nullptr - : it->second; - } - - private: - virtual void deepCopy(const AbstractRegistry>& sr) ELPP_FINAL { - for (const_iterator it = sr.cbegin(); it != sr.cend(); ++it) { - registerNew(it->first, new T_Ptr(*it->second)); - } - } -}; - -/// @brief A pointer registry mechanism to manage memory and provide search functionalities. (predicate version) -/// -/// @detail NOTE: This is thread-unsafe implementation of AbstractRegistry. Any implementation of this class -/// should be made thread-safe explicitly -template -class RegistryWithPred : public AbstractRegistry> { - public: - typedef typename RegistryWithPred::iterator iterator; - typedef typename RegistryWithPred::const_iterator const_iterator; - - RegistryWithPred(void) { - } - - virtual ~RegistryWithPred(void) { - unregisterAll(); - } - - /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor. - RegistryWithPred(const RegistryWithPred& sr) : AbstractRegistry>() { - if (this == &sr) { - return; - } - this->reinitDeepCopy(sr); - } - - /// @brief Assignment operator that unregisters all the existing registries and deeply copies each of repo element - /// @see unregisterAll() - /// @see deepCopy(const AbstractRegistry&) - RegistryWithPred& operator=(const RegistryWithPred& sr) { - if (this == &sr) { - return *this; - } - this->reinitDeepCopy(sr); - return *this; - } - - friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const RegistryWithPred& sr) { - for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) { - os << ELPP_LITERAL(" ") << **it << ELPP_LITERAL("\n"); - } - return os; - } - - protected: - virtual void unregisterAll(void) ELPP_FINAL { - if (!this->empty()) { - for (auto&& curr : this->list()) { - base::utils::safeDelete(curr); - } - this->list().clear(); - } - } - - virtual void unregister(T_Ptr*& ptr) ELPP_FINAL { - if (ptr) { - iterator iter = this->begin(); - for (; iter != this->end(); ++iter) { - if (ptr == *iter) { - break; - } - } - if (iter != this->end() && *iter != nullptr) { - this->list().erase(iter); - base::utils::safeDelete(*iter); - } - } - } - - virtual inline void registerNew(T_Ptr* ptr) ELPP_FINAL { - this->list().push_back(ptr); - } - -/// @brief Gets pointer from repository with specified arguments. Arguments are passed to predicate -/// in order to validate pointer. - template - T_Ptr* get(const T& arg1, const T2 arg2) { - iterator iter = std::find_if(this->list().begin(), this->list().end(), Pred(arg1, arg2)); - if (iter != this->list().end() && *iter != nullptr) { - return *iter; - } - return nullptr; - } - - private: - virtual void deepCopy(const AbstractRegistry>& sr) { - for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) { - registerNew(new T_Ptr(**it)); - } - } -}; -class Utils { - public: - template - static bool installCallback(const std::string& id, std::unordered_map* mapT) { - if (mapT->find(id) == mapT->end()) { - mapT->insert(std::make_pair(id, TPtr(new T()))); - return true; - } - return false; - } - - template - static void uninstallCallback(const std::string& id, std::unordered_map* mapT) { - if (mapT->find(id) != mapT->end()) { - mapT->erase(id); - } - } - - template - static T* callback(const std::string& id, std::unordered_map* mapT) { - typename std::unordered_map::iterator iter = mapT->find(id); - if (iter != mapT->end()) { - return static_cast(iter->second.get()); - } - return nullptr; - } -}; -} // namespace utils -} // namespace base -/// @brief Base of Easylogging++ friendly class -/// -/// @detail After inheriting this class publicly, implement pure-virtual function `void log(std::ostream&) const` -class Loggable { - public: - virtual ~Loggable(void) {} - virtual void log(el::base::type::ostream_t&) const = 0; - private: - friend inline el::base::type::ostream_t& operator<<(el::base::type::ostream_t& os, const Loggable& loggable) { - loggable.log(os); - return os; - } -}; -namespace base { -/// @brief Represents log format containing flags and date format. This is used internally to start initial log -class LogFormat : public Loggable { - public: - LogFormat(void); - LogFormat(Level level, const base::type::string_t& format); - LogFormat(const LogFormat& logFormat); - LogFormat(LogFormat&& logFormat); - LogFormat& operator=(const LogFormat& logFormat); - virtual ~LogFormat(void) {} - bool operator==(const LogFormat& other); - - /// @brief Updates format to be used while logging. - /// @param userFormat User provided format - void parseFromFormat(const base::type::string_t& userFormat); - - inline Level level(void) const { - return m_level; - } - - inline const base::type::string_t& userFormat(void) const { - return m_userFormat; - } - - inline const base::type::string_t& format(void) const { - return m_format; - } - - inline const std::string& dateTimeFormat(void) const { - return m_dateTimeFormat; - } - - inline base::type::EnumType flags(void) const { - return m_flags; - } - - inline bool hasFlag(base::FormatFlags flag) const { - return base::utils::hasFlag(flag, m_flags); - } - - virtual void log(el::base::type::ostream_t& os) const { - os << m_format; - } - - protected: - /// @brief Updates date time format if available in currFormat. - /// @param index Index where %datetime, %date or %time was found - /// @param [in,out] currFormat current format that is being used to format - virtual void updateDateFormat(std::size_t index, base::type::string_t& currFormat) ELPP_FINAL; - - /// @brief Updates %level from format. This is so that we dont have to do it at log-writing-time. It uses m_format and m_level - virtual void updateFormatSpec(void) ELPP_FINAL; - - inline void addFlag(base::FormatFlags flag) { - base::utils::addFlag(flag, &m_flags); - } - - private: - Level m_level; - base::type::string_t m_userFormat; - base::type::string_t m_format; - std::string m_dateTimeFormat; - base::type::EnumType m_flags; - std::string m_currentUser; - std::string m_currentHost; - friend class el::Logger; // To resolve loggerId format specifier easily -}; -} // namespace base -/// @brief Resolving function for format specifier -typedef std::function FormatSpecifierValueResolver; -/// @brief User-provided custom format specifier -/// @see el::Helpers::installCustomFormatSpecifier -/// @see FormatSpecifierValueResolver -class CustomFormatSpecifier { - public: - CustomFormatSpecifier(const char* formatSpecifier, const FormatSpecifierValueResolver& resolver) : - m_formatSpecifier(formatSpecifier), m_resolver(resolver) {} - inline const char* formatSpecifier(void) const { - return m_formatSpecifier; - } - inline const FormatSpecifierValueResolver& resolver(void) const { - return m_resolver; - } - inline bool operator==(const char* formatSpecifier) { - return strcmp(m_formatSpecifier, formatSpecifier) == 0; - } - - private: - const char* m_formatSpecifier; - FormatSpecifierValueResolver m_resolver; -}; -/// @brief Represents single configuration that has representing level, configuration type and a string based value. -/// -/// @detail String based value means any value either its boolean, integer or string itself, it will be embedded inside quotes -/// and will be parsed later. -/// -/// Consider some examples below: -/// * el::Configuration confEnabledInfo(el::Level::Info, el::ConfigurationType::Enabled, "true"); -/// * el::Configuration confMaxLogFileSizeInfo(el::Level::Info, el::ConfigurationType::MaxLogFileSize, "2048"); -/// * el::Configuration confFilenameInfo(el::Level::Info, el::ConfigurationType::Filename, "/var/log/my.log"); -class Configuration : public Loggable { - public: - Configuration(const Configuration& c); - Configuration& operator=(const Configuration& c); - - virtual ~Configuration(void) { - } - - /// @brief Full constructor used to sets value of configuration - Configuration(Level level, ConfigurationType configurationType, const std::string& value); - - /// @brief Gets level of current configuration - inline Level level(void) const { - return m_level; - } - - /// @brief Gets configuration type of current configuration - inline ConfigurationType configurationType(void) const { - return m_configurationType; - } - - /// @brief Gets string based configuration value - inline const std::string& value(void) const { - return m_value; - } - - /// @brief Set string based configuration value - /// @param value Value to set. Values have to be std::string; For boolean values use "true", "false", for any integral values - /// use them in quotes. They will be parsed when configuring - inline void setValue(const std::string& value) { - m_value = value; - } - - virtual void log(el::base::type::ostream_t& os) const; - - /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it. - class Predicate { - public: - Predicate(Level level, ConfigurationType configurationType); - - bool operator()(const Configuration* conf) const; - - private: - Level m_level; - ConfigurationType m_configurationType; - }; - - private: - Level m_level; - ConfigurationType m_configurationType; - std::string m_value; -}; - -/// @brief Thread-safe Configuration repository -/// -/// @detail This repository represents configurations for all the levels and configuration type mapped to a value. -class Configurations : public base::utils::RegistryWithPred { - public: - /// @brief Default constructor with empty repository - Configurations(void); - - /// @brief Constructor used to set configurations using configuration file. - /// @param configurationFile Full path to configuration file - /// @param useDefaultsForRemaining Lets you set the remaining configurations to default. - /// @param base If provided, this configuration will be based off existing repository that this argument is pointing to. - /// @see parseFromFile(const std::string&, Configurations* base) - /// @see setRemainingToDefault() - Configurations(const std::string& configurationFile, bool useDefaultsForRemaining = true, - Configurations* base = nullptr); - - virtual ~Configurations(void) { - } - - /// @brief Parses configuration from file. - /// @param configurationFile Full path to configuration file - /// @param base Configurations to base new configuration repository off. This value is used when you want to use - /// existing Configurations to base all the values and then set rest of configuration via configuration file. - /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you - /// do not proceed without successful parse. - bool parseFromFile(const std::string& configurationFile, Configurations* base = nullptr); - - /// @brief Parse configurations from configuration string. - /// - /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary - /// new line characters are provided. - /// @param base Configurations to base new configuration repository off. This value is used when you want to use - /// existing Configurations to base all the values and then set rest of configuration via configuration text. - /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you - /// do not proceed without successful parse. - bool parseFromText(const std::string& configurationsString, Configurations* base = nullptr); - - /// @brief Sets configuration based-off an existing configurations. - /// @param base Pointer to existing configurations. - void setFromBase(Configurations* base); - - /// @brief Determines whether or not specified configuration type exists in the repository. - /// - /// @detail Returns as soon as first level is found. - /// @param configurationType Type of configuration to check existence for. - bool hasConfiguration(ConfigurationType configurationType); - - /// @brief Determines whether or not specified configuration type exists for specified level - /// @param level Level to check - /// @param configurationType Type of configuration to check existence for. - bool hasConfiguration(Level level, ConfigurationType configurationType); - - /// @brief Sets value of configuration for specified level. - /// - /// @detail Any existing configuration for specified level will be replaced. Also note that configuration types - /// ConfigurationType::SubsecondPrecision and ConfigurationType::PerformanceTracking will be ignored if not set for - /// Level::Global because these configurations are not dependant on level. - /// @param level Level to set configuration for (el::Level). - /// @param configurationType Type of configuration (el::ConfigurationType) - /// @param value A string based value. Regardless of what the data type of configuration is, it will always be string - /// from users' point of view. This is then parsed later to be used internally. - /// @see Configuration::setValue(const std::string& value) - /// @see el::Level - /// @see el::ConfigurationType - void set(Level level, ConfigurationType configurationType, const std::string& value); - - /// @brief Sets single configuration based on other single configuration. - /// @see set(Level level, ConfigurationType configurationType, const std::string& value) - void set(Configuration* conf); - - inline Configuration* get(Level level, ConfigurationType configurationType) { - base::threading::ScopedLock scopedLock(lock()); - return RegistryWithPred::get(level, configurationType); - } - - /// @brief Sets configuration for all levels. - /// @param configurationType Type of configuration - /// @param value String based value - /// @see Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) - inline void setGlobally(ConfigurationType configurationType, const std::string& value) { - setGlobally(configurationType, value, false); - } - - /// @brief Clears repository so that all the configurations are unset - inline void clear(void) { - base::threading::ScopedLock scopedLock(lock()); - unregisterAll(); - } - - /// @brief Gets configuration file used in parsing this configurations. - /// - /// @detail If this repository was set manually or by text this returns empty string. - inline const std::string& configurationFile(void) const { - return m_configurationFile; - } - - /// @brief Sets configurations to "factory based" configurations. - void setToDefault(void); - - /// @brief Lets you set the remaining configurations to default. - /// - /// @detail By remaining, it means that the level/type a configuration does not exist for. - /// This function is useful when you want to minimize chances of failures, e.g, if you have a configuration file that sets - /// configuration for all the configurations except for Enabled or not, we use this so that ENABLED is set to default i.e, - /// true. If you dont do this explicitly (either by calling this function or by using second param in Constructor - /// and try to access a value, an error is thrown - void setRemainingToDefault(void); - - /// @brief Parser used internally to parse configurations from file or text. - /// - /// @detail This class makes use of base::utils::Str. - /// You should not need this unless you are working on some tool for Easylogging++ - class Parser : base::StaticClass { - public: - /// @brief Parses configuration from file. - /// @param configurationFile Full path to configuration file - /// @param sender Sender configurations pointer. Usually 'this' is used from calling class - /// @param base Configurations to base new configuration repository off. This value is used when you want to use - /// existing Configurations to base all the values and then set rest of configuration via configuration file. - /// @return True if successfully parsed, false otherwise. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you - /// do not proceed without successful parse. - static bool parseFromFile(const std::string& configurationFile, Configurations* sender, - Configurations* base = nullptr); - - /// @brief Parse configurations from configuration string. - /// - /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary - /// new line characters are provided. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you - /// do not proceed without successful parse (This is recommended) - /// @param configurationsString the configuration in plain text format - /// @param sender Sender configurations pointer. Usually 'this' is used from calling class - /// @param base Configurations to base new configuration repository off. This value is used when you want to use - /// existing Configurations to base all the values and then set rest of configuration via configuration text. - /// @return True if successfully parsed, false otherwise. - static bool parseFromText(const std::string& configurationsString, Configurations* sender, - Configurations* base = nullptr); - - private: - friend class el::Loggers; - static void ignoreComments(std::string* line); - static bool isLevel(const std::string& line); - static bool isComment(const std::string& line); - static inline bool isConfig(const std::string& line); - static bool parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, Level* currLevel, - Configurations* conf); - }; - - private: - std::string m_configurationFile; - bool m_isFromFile; - friend class el::Loggers; - - /// @brief Unsafely sets configuration if does not already exist - void unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value); - - /// @brief Thread unsafe set - void unsafeSet(Level level, ConfigurationType configurationType, const std::string& value); - - /// @brief Sets configurations for all levels including Level::Global if includeGlobalLevel is true - /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value) - void setGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel); - - /// @brief Sets configurations (Unsafely) for all levels including Level::Global if includeGlobalLevel is true - /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value) - void unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel); -}; - -namespace base { -typedef std::shared_ptr FileStreamPtr; -typedef std::unordered_map LogStreamsReferenceMap; -typedef std::shared_ptr LogStreamsReferenceMapPtr; -/// @brief Configurations with data types. -/// -/// @detail el::Configurations have string based values. This is whats used internally in order to read correct configurations. -/// This is to perform faster while writing logs using correct configurations. -/// -/// This is thread safe and final class containing non-virtual destructor (means nothing should inherit this class) -class TypedConfigurations : public base::threading::ThreadSafe { - public: - /// @brief Constructor to initialize (construct) the object off el::Configurations - /// @param configurations Configurations pointer/reference to base this typed configurations off. - /// @param logStreamsReference Use ELPP->registeredLoggers()->logStreamsReference() - TypedConfigurations(Configurations* configurations, LogStreamsReferenceMapPtr logStreamsReference); - - TypedConfigurations(const TypedConfigurations& other); - - virtual ~TypedConfigurations(void) { - } - - const Configurations* configurations(void) const { - return m_configurations; - } - - bool enabled(Level level); - bool toFile(Level level); - const std::string& filename(Level level); - bool toStandardOutput(Level level); - const base::LogFormat& logFormat(Level level); - const base::SubsecondPrecision& subsecondPrecision(Level level = Level::Global); - const base::MillisecondsWidth& millisecondsWidth(Level level = Level::Global); - bool performanceTracking(Level level = Level::Global); - base::type::fstream_t* fileStream(Level level); - std::size_t maxLogFileSize(Level level); - std::size_t logFlushThreshold(Level level); - - private: - Configurations* m_configurations; - std::unordered_map m_enabledMap; - std::unordered_map m_toFileMap; - std::unordered_map m_filenameMap; - std::unordered_map m_toStandardOutputMap; - std::unordered_map m_logFormatMap; - std::unordered_map m_subsecondPrecisionMap; - std::unordered_map m_performanceTrackingMap; - std::unordered_map m_fileStreamMap; - std::unordered_map m_maxLogFileSizeMap; - std::unordered_map m_logFlushThresholdMap; - LogStreamsReferenceMapPtr m_logStreamsReference = nullptr; - - friend class el::Helpers; - friend class el::base::MessageBuilder; - friend class el::base::Writer; - friend class el::base::DefaultLogDispatchCallback; - friend class el::base::LogDispatcher; - - template - inline Conf_T getConfigByVal(Level level, const std::unordered_map* confMap, const char* confName) { - base::threading::ScopedLock scopedLock(lock()); - return unsafeGetConfigByVal(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope - } - - template - inline Conf_T& getConfigByRef(Level level, std::unordered_map* confMap, const char* confName) { - base::threading::ScopedLock scopedLock(lock()); - return unsafeGetConfigByRef(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope - } - - template - Conf_T unsafeGetConfigByVal(Level level, const std::unordered_map* confMap, const char* confName) { - ELPP_UNUSED(confName); - typename std::unordered_map::const_iterator it = confMap->find(level); - if (it == confMap->end()) { - try { - return confMap->at(Level::Global); - } catch (...) { - ELPP_INTERNAL_ERROR("Unable to get configuration [" << confName << "] for level [" - << LevelHelper::convertToString(level) << "]" - << std::endl << "Please ensure you have properly configured logger.", false); - return Conf_T(); - } - } - return it->second; - } - - template - Conf_T& unsafeGetConfigByRef(Level level, std::unordered_map* confMap, const char* confName) { - ELPP_UNUSED(confName); - typename std::unordered_map::iterator it = confMap->find(level); - if (it == confMap->end()) { - try { - return confMap->at(Level::Global); - } catch (...) { - ELPP_INTERNAL_ERROR("Unable to get configuration [" << confName << "] for level [" - << LevelHelper::convertToString(level) << "]" - << std::endl << "Please ensure you have properly configured logger.", false); - } - } - return it->second; - } - - template - void setValue(Level level, const Conf_T& value, std::unordered_map* confMap, - bool includeGlobalLevel = true) { - // If map is empty and we are allowed to add into generic level (Level::Global), do it! - if (confMap->empty() && includeGlobalLevel) { - confMap->insert(std::make_pair(Level::Global, value)); - return; - } - // If same value exist in generic level already, dont add it to explicit level - typename std::unordered_map::iterator it = confMap->find(Level::Global); - if (it != confMap->end() && it->second == value) { - return; - } - // Now make sure we dont double up values if we really need to add it to explicit level - it = confMap->find(level); - if (it == confMap->end()) { - // Value not found for level, add new - confMap->insert(std::make_pair(level, value)); - } else { - // Value found, just update value - confMap->at(level) = value; - } - } - - void build(Configurations* configurations); - unsigned long getULong(std::string confVal); - std::string resolveFilename(const std::string& filename); - void insertFile(Level level, const std::string& fullFilename); - bool unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback); - - inline bool validateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) { - base::threading::ScopedLock scopedLock(lock()); - return unsafeValidateFileRolling(level, preRollOutCallback); - } -}; -/// @brief Class that keeps record of current line hit for occasional logging -class HitCounter { - public: - HitCounter(void) : - m_filename(""), - m_lineNumber(0), - m_hitCounts(0) { - } - - HitCounter(const char* filename, base::type::LineNumber lineNumber) : - m_filename(filename), - m_lineNumber(lineNumber), - m_hitCounts(0) { - } - - HitCounter(const HitCounter& hitCounter) : - m_filename(hitCounter.m_filename), - m_lineNumber(hitCounter.m_lineNumber), - m_hitCounts(hitCounter.m_hitCounts) { - } - - HitCounter& operator=(const HitCounter& hitCounter) { - if (&hitCounter != this) { - m_filename = hitCounter.m_filename; - m_lineNumber = hitCounter.m_lineNumber; - m_hitCounts = hitCounter.m_hitCounts; - } - return *this; - } - - virtual ~HitCounter(void) { - } - - /// @brief Resets location of current hit counter - inline void resetLocation(const char* filename, base::type::LineNumber lineNumber) { - m_filename = filename; - m_lineNumber = lineNumber; - } - - /// @brief Validates hit counts and resets it if necessary - inline void validateHitCounts(std::size_t n) { - if (m_hitCounts >= base::consts::kMaxLogPerCounter) { - m_hitCounts = (n >= 1 ? base::consts::kMaxLogPerCounter % n : 0); - } - ++m_hitCounts; - } - - inline const char* filename(void) const { - return m_filename; - } - - inline base::type::LineNumber lineNumber(void) const { - return m_lineNumber; - } - - inline std::size_t hitCounts(void) const { - return m_hitCounts; - } - - inline void increment(void) { - ++m_hitCounts; - } - - class Predicate { - public: - Predicate(const char* filename, base::type::LineNumber lineNumber) - : m_filename(filename), - m_lineNumber(lineNumber) { - } - inline bool operator()(const HitCounter* counter) { - return ((counter != nullptr) && - (strcmp(counter->m_filename, m_filename) == 0) && - (counter->m_lineNumber == m_lineNumber)); - } - - private: - const char* m_filename; - base::type::LineNumber m_lineNumber; - }; - - private: - const char* m_filename; - base::type::LineNumber m_lineNumber; - std::size_t m_hitCounts; -}; -/// @brief Repository for hit counters used across the application -class RegisteredHitCounters : public base::utils::RegistryWithPred { - public: - /// @brief Validates counter for every N, i.e, registers new if does not exist otherwise updates original one - /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned - bool validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n); - - /// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one - /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned - bool validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n); - - /// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one - /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned - bool validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n); - - /// @brief Gets hit counter registered at specified position - inline const base::HitCounter* getCounter(const char* filename, base::type::LineNumber lineNumber) { - base::threading::ScopedLock scopedLock(lock()); - return get(filename, lineNumber); - } -}; -/// @brief Action to be taken for dispatching -enum class DispatchAction : base::type::EnumType { - None = 1, NormalLog = 2, SysLog = 4 -}; -} // namespace base -template -class Callback : protected base::threading::ThreadSafe { - public: - Callback(void) : m_enabled(true) {} - inline bool enabled(void) const { - return m_enabled; - } - inline void setEnabled(bool enabled) { - base::threading::ScopedLock scopedLock(lock()); - m_enabled = enabled; - } - protected: - virtual void handle(const T* handlePtr) = 0; - private: - bool m_enabled; -}; -class LogDispatchData { - public: - LogDispatchData() : m_logMessage(nullptr), m_dispatchAction(base::DispatchAction::None) {} - inline const LogMessage* logMessage(void) const { - return m_logMessage; - } - inline base::DispatchAction dispatchAction(void) const { - return m_dispatchAction; - } - inline void setLogMessage(LogMessage* logMessage) { - m_logMessage = logMessage; - } - inline void setDispatchAction(base::DispatchAction dispatchAction) { - m_dispatchAction = dispatchAction; - } - private: - LogMessage* m_logMessage; - base::DispatchAction m_dispatchAction; - friend class base::LogDispatcher; - -}; -class LogDispatchCallback : public Callback { - protected: - virtual void handle(const LogDispatchData* data); - base::threading::Mutex& fileHandle(const LogDispatchData* data); - private: - friend class base::LogDispatcher; - std::unordered_map> m_fileLocks; - base::threading::Mutex m_fileLocksMapLock; -}; -class PerformanceTrackingCallback : public Callback { - private: - friend class base::PerformanceTracker; -}; -class LoggerRegistrationCallback : public Callback { - private: - friend class base::RegisteredLoggers; -}; -class LogBuilder : base::NoCopy { - public: - LogBuilder() : m_termSupportsColor(base::utils::OS::termSupportsColor()) {} - virtual ~LogBuilder(void) { - ELPP_INTERNAL_INFO(3, "Destroying log builder...") - } - virtual base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const = 0; - void convertToColoredOutput(base::type::string_t* logLine, Level level); - private: - bool m_termSupportsColor; - friend class el::base::DefaultLogDispatchCallback; -}; -typedef std::shared_ptr LogBuilderPtr; -/// @brief Represents a logger holding ID and configurations we need to write logs -/// -/// @detail This class does not write logs itself instead its used by writer to read configurations from. -class Logger : public base::threading::ThreadSafe, public Loggable { - public: - Logger(const std::string& id, base::LogStreamsReferenceMapPtr logStreamsReference); - Logger(const std::string& id, const Configurations& configurations, base::LogStreamsReferenceMapPtr logStreamsReference); - Logger(const Logger& logger); - Logger& operator=(const Logger& logger); - - virtual ~Logger(void) { - base::utils::safeDelete(m_typedConfigurations); - } - - virtual inline void log(el::base::type::ostream_t& os) const { - os << m_id.c_str(); - } - - /// @brief Configures the logger using specified configurations. - void configure(const Configurations& configurations); - - /// @brief Reconfigures logger using existing configurations - void reconfigure(void); - - inline const std::string& id(void) const { - return m_id; - } - - inline const std::string& parentApplicationName(void) const { - return m_parentApplicationName; - } - - inline void setParentApplicationName(const std::string& parentApplicationName) { - m_parentApplicationName = parentApplicationName; - } - - inline Configurations* configurations(void) { - return &m_configurations; - } - - inline base::TypedConfigurations* typedConfigurations(void) { - return m_typedConfigurations; - } - - static bool isValidId(const std::string& id); - - /// @brief Flushes logger to sync all log files for all levels - void flush(void); - - void flush(Level level, base::type::fstream_t* fs); - - inline bool isFlushNeeded(Level level) { -//If GCC, errors on MSVC. -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wnull-dereference" -#endif - // Causes an error on GCC. - return ++m_unflushedCount.find(level)->second >= m_typedConfigurations->logFlushThreshold(level); -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - } - - inline LogBuilder* logBuilder(void) const { - return m_logBuilder.get(); - } - - inline void setLogBuilder(const LogBuilderPtr& logBuilder) { - m_logBuilder = logBuilder; - } - - inline bool enabled(Level level) const { - return m_typedConfigurations->enabled(level); - } - -#if ELPP_VARIADIC_TEMPLATES_SUPPORTED -# define LOGGER_LEVEL_WRITERS_SIGNATURES(FUNCTION_NAME)\ -template \ -inline void FUNCTION_NAME(const char*, const T&, const Args&...);\ -template \ -inline void FUNCTION_NAME(const T&); - - template - inline void verbose(int, const char*, const T&, const Args&...); - - template - inline void verbose(int, const T&); - - LOGGER_LEVEL_WRITERS_SIGNATURES(info) - LOGGER_LEVEL_WRITERS_SIGNATURES(debug) - LOGGER_LEVEL_WRITERS_SIGNATURES(warn) - LOGGER_LEVEL_WRITERS_SIGNATURES(error) - LOGGER_LEVEL_WRITERS_SIGNATURES(fatal) - LOGGER_LEVEL_WRITERS_SIGNATURES(trace) -# undef LOGGER_LEVEL_WRITERS_SIGNATURES -#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED - private: - std::string m_id; - base::TypedConfigurations* m_typedConfigurations; - base::type::stringstream_t m_stream; - std::string m_parentApplicationName; - bool m_isConfigured; - Configurations m_configurations; - std::unordered_map m_unflushedCount; - base::LogStreamsReferenceMapPtr m_logStreamsReference = nullptr; - LogBuilderPtr m_logBuilder; - - friend class el::LogMessage; - friend class el::Loggers; - friend class el::Helpers; - friend class el::base::RegisteredLoggers; - friend class el::base::DefaultLogDispatchCallback; - friend class el::base::MessageBuilder; - friend class el::base::Writer; - friend class el::base::PErrorWriter; - friend class el::base::Storage; - friend class el::base::PerformanceTracker; - friend class el::base::LogDispatcher; - - Logger(void); - -#if ELPP_VARIADIC_TEMPLATES_SUPPORTED - template - void log_(Level, int, const char*, const T&, const Args&...); - - template - inline void log_(Level, int, const T&); - - template - void log(Level, const char*, const T&, const Args&...); - - template - inline void log(Level, const T&); -#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED - - void initUnflushedCount(void); - - inline base::type::stringstream_t& stream(void) { - return m_stream; - } - - void resolveLoggerFormatSpec(void) const; -}; -namespace base { -/// @brief Loggers repository -class RegisteredLoggers : public base::utils::Registry { - public: - explicit RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder); - - virtual ~RegisteredLoggers(void) { - unsafeFlushAll(); - } - - inline void setDefaultConfigurations(const Configurations& configurations) { - base::threading::ScopedLock scopedLock(lock()); - m_defaultConfigurations.setFromBase(const_cast(&configurations)); - } - - inline Configurations* defaultConfigurations(void) { - return &m_defaultConfigurations; - } - - Logger* get(const std::string& id, bool forceCreation = true); - - template - inline bool installLoggerRegistrationCallback(const std::string& id) { - return base::utils::Utils::installCallback(id, - &m_loggerRegistrationCallbacks); - } - - template - inline void uninstallLoggerRegistrationCallback(const std::string& id) { - base::utils::Utils::uninstallCallback(id, &m_loggerRegistrationCallbacks); - } - - template - inline T* loggerRegistrationCallback(const std::string& id) { - return base::utils::Utils::callback(id, &m_loggerRegistrationCallbacks); - } - - bool remove(const std::string& id); - - inline bool has(const std::string& id) { - return get(id, false) != nullptr; - } - - inline void unregister(Logger*& logger) { - base::threading::ScopedLock scopedLock(lock()); - base::utils::Registry::unregister(logger->id()); - } - - inline LogStreamsReferenceMapPtr logStreamsReference(void) { - return m_logStreamsReference; - } - - inline void flushAll(void) { - base::threading::ScopedLock scopedLock(lock()); - unsafeFlushAll(); - } - - inline void setDefaultLogBuilder(LogBuilderPtr& logBuilderPtr) { - base::threading::ScopedLock scopedLock(lock()); - m_defaultLogBuilder = logBuilderPtr; - } - - private: - LogBuilderPtr m_defaultLogBuilder; - Configurations m_defaultConfigurations; - base::LogStreamsReferenceMapPtr m_logStreamsReference = nullptr; - std::unordered_map m_loggerRegistrationCallbacks; - friend class el::base::Storage; - - void unsafeFlushAll(void); -}; -/// @brief Represents registries for verbose logging -class VRegistry : base::NoCopy, public base::threading::ThreadSafe { - public: - explicit VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags); - - /// @brief Sets verbose level. Accepted range is 0-9 - void setLevel(base::type::VerboseLevel level); - - inline base::type::VerboseLevel level(void) const { - return m_level; - } - - inline void clearModules(void) { - base::threading::ScopedLock scopedLock(lock()); - m_modules.clear(); - } - - void setModules(const char* modules); - - bool allowed(base::type::VerboseLevel vlevel, const char* file); - - inline const std::unordered_map& modules(void) const { - return m_modules; - } - - void setFromArgs(const base::utils::CommandLineArgs* commandLineArgs); - - /// @brief Whether or not vModules enabled - inline bool vModulesEnabled(void) { - return !base::utils::hasFlag(LoggingFlag::DisableVModules, *m_pFlags); - } - - private: - base::type::VerboseLevel m_level; - base::type::EnumType* m_pFlags; - std::unordered_map m_modules; -}; -} // namespace base -class LogMessage { - public: - LogMessage(Level level, const std::string& file, base::type::LineNumber line, const std::string& func, - base::type::VerboseLevel verboseLevel, Logger* logger) : - m_level(level), m_file(file), m_line(line), m_func(func), - m_verboseLevel(verboseLevel), m_logger(logger), m_message(logger->stream().str()) { - } - inline Level level(void) const { - return m_level; - } - inline const std::string& file(void) const { - return m_file; - } - inline base::type::LineNumber line(void) const { - return m_line; - } - inline const std::string& func(void) const { - return m_func; - } - inline base::type::VerboseLevel verboseLevel(void) const { - return m_verboseLevel; - } - inline Logger* logger(void) const { - return m_logger; - } - inline const base::type::string_t& message(void) const { - return m_message; - } - private: - Level m_level; - std::string m_file; - base::type::LineNumber m_line; - std::string m_func; - base::type::VerboseLevel m_verboseLevel; - Logger* m_logger; - base::type::string_t m_message; -}; -namespace base { -#if ELPP_ASYNC_LOGGING -class AsyncLogItem { - public: - explicit AsyncLogItem(const LogMessage& logMessage, const LogDispatchData& data, const base::type::string_t& logLine) - : m_logMessage(logMessage), m_dispatchData(data), m_logLine(logLine) {} - virtual ~AsyncLogItem() {} - inline LogMessage* logMessage(void) { - return &m_logMessage; - } - inline LogDispatchData* data(void) { - return &m_dispatchData; - } - inline base::type::string_t logLine(void) { - return m_logLine; - } - private: - LogMessage m_logMessage; - LogDispatchData m_dispatchData; - base::type::string_t m_logLine; -}; -class AsyncLogQueue : public base::threading::ThreadSafe { - public: - virtual ~AsyncLogQueue() { - ELPP_INTERNAL_INFO(6, "~AsyncLogQueue"); - } - - inline AsyncLogItem next(void) { - base::threading::ScopedLock scopedLock(lock()); - AsyncLogItem result = m_queue.front(); - m_queue.pop(); - return result; - } - - inline void push(const AsyncLogItem& item) { - base::threading::ScopedLock scopedLock(lock()); - m_queue.push(item); - } - inline void pop(void) { - base::threading::ScopedLock scopedLock(lock()); - m_queue.pop(); - } - inline AsyncLogItem front(void) { - base::threading::ScopedLock scopedLock(lock()); - return m_queue.front(); - } - inline bool empty(void) { - base::threading::ScopedLock scopedLock(lock()); - return m_queue.empty(); - } - private: - std::queue m_queue; -}; -class IWorker { - public: - virtual ~IWorker() {} - virtual void start() = 0; -}; -#endif // ELPP_ASYNC_LOGGING -/// @brief Easylogging++ management storage -class Storage : base::NoCopy, public base::threading::ThreadSafe { - public: -#if ELPP_ASYNC_LOGGING - Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker); -#else - explicit Storage(const LogBuilderPtr& defaultLogBuilder); -#endif // ELPP_ASYNC_LOGGING - - virtual ~Storage(void); - - inline bool validateEveryNCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t occasion) { - return hitCounters()->validateEveryN(filename, lineNumber, occasion); - } - - inline bool validateAfterNCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - return hitCounters()->validateAfterN(filename, lineNumber, n); - } - - inline bool validateNTimesCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - return hitCounters()->validateNTimes(filename, lineNumber, n); - } - - inline base::RegisteredHitCounters* hitCounters(void) const { - return m_registeredHitCounters; - } - - inline base::RegisteredLoggers* registeredLoggers(void) const { - return m_registeredLoggers; - } - - inline base::VRegistry* vRegistry(void) const { - return m_vRegistry; - } - -#if ELPP_ASYNC_LOGGING - inline base::AsyncLogQueue* asyncLogQueue(void) const { - return m_asyncLogQueue; - } -#endif // ELPP_ASYNC_LOGGING - - inline const base::utils::CommandLineArgs* commandLineArgs(void) const { - return &m_commandLineArgs; - } - - inline void addFlag(LoggingFlag flag) { - base::utils::addFlag(flag, &m_flags); - } - - inline void removeFlag(LoggingFlag flag) { - base::utils::removeFlag(flag, &m_flags); - } - - inline bool hasFlag(LoggingFlag flag) const { - return base::utils::hasFlag(flag, m_flags); - } - - inline base::type::EnumType flags(void) const { - return m_flags; - } - - inline void setFlags(base::type::EnumType flags) { - m_flags = flags; - } - - inline void setPreRollOutCallback(const PreRollOutCallback& callback) { - m_preRollOutCallback = callback; - } - - inline void unsetPreRollOutCallback(void) { - m_preRollOutCallback = base::defaultPreRollOutCallback; - } - - inline PreRollOutCallback& preRollOutCallback(void) { - return m_preRollOutCallback; - } - - bool hasCustomFormatSpecifier(const char* formatSpecifier); - void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier); - bool uninstallCustomFormatSpecifier(const char* formatSpecifier); - - const std::vector* customFormatSpecifiers(void) const { - return &m_customFormatSpecifiers; - } - - base::threading::Mutex& customFormatSpecifiersLock() { - return m_customFormatSpecifiersLock; - } - - inline void setLoggingLevel(Level level) { - m_loggingLevel = level; - } - - template - inline bool installLogDispatchCallback(const std::string& id) { - return base::utils::Utils::installCallback(id, &m_logDispatchCallbacks); - } - - template - inline void uninstallLogDispatchCallback(const std::string& id) { - base::utils::Utils::uninstallCallback(id, &m_logDispatchCallbacks); - } - template - inline T* logDispatchCallback(const std::string& id) { - return base::utils::Utils::callback(id, &m_logDispatchCallbacks); - } - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - template - inline bool installPerformanceTrackingCallback(const std::string& id) { - return base::utils::Utils::installCallback(id, - &m_performanceTrackingCallbacks); - } - - template - inline void uninstallPerformanceTrackingCallback(const std::string& id) { - base::utils::Utils::uninstallCallback(id, - &m_performanceTrackingCallbacks); - } - - template - inline T* performanceTrackingCallback(const std::string& id) { - return base::utils::Utils::callback(id, &m_performanceTrackingCallbacks); - } -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - - /// @brief Sets thread name for current thread. Requires std::thread - inline void setThreadName(const std::string& name) { - if (name.empty()) return; - base::threading::ScopedLock scopedLock(m_threadNamesLock); - m_threadNames[base::threading::getCurrentThreadId()] = name; - } - - inline std::string getThreadName(const std::string& threadId) { - base::threading::ScopedLock scopedLock(m_threadNamesLock); - std::unordered_map::const_iterator it = m_threadNames.find(threadId); - if (it == m_threadNames.end()) { - return threadId; - } - return it->second; - } - private: - base::RegisteredHitCounters* m_registeredHitCounters; - base::RegisteredLoggers* m_registeredLoggers; - base::type::EnumType m_flags; - base::VRegistry* m_vRegistry; -#if ELPP_ASYNC_LOGGING - base::AsyncLogQueue* m_asyncLogQueue; - base::IWorker* m_asyncDispatchWorker; -#endif // ELPP_ASYNC_LOGGING - base::utils::CommandLineArgs m_commandLineArgs; - PreRollOutCallback m_preRollOutCallback; - std::unordered_map m_logDispatchCallbacks; - std::unordered_map m_performanceTrackingCallbacks; - std::unordered_map m_threadNames; - std::vector m_customFormatSpecifiers; - base::threading::Mutex m_customFormatSpecifiersLock; - base::threading::Mutex m_threadNamesLock; - Level m_loggingLevel; - - friend class el::Helpers; - friend class el::base::DefaultLogDispatchCallback; - friend class el::LogBuilder; - friend class el::base::MessageBuilder; - friend class el::base::Writer; - friend class el::base::PerformanceTracker; - friend class el::base::LogDispatcher; - - void setApplicationArguments(int argc, char** argv); - - inline void setApplicationArguments(int argc, const char** argv) { - setApplicationArguments(argc, const_cast(argv)); - } -}; -extern ELPP_EXPORT base::type::StoragePointer elStorage; -#define ELPP el::base::elStorage -class DefaultLogDispatchCallback : public LogDispatchCallback { - protected: - void handle(const LogDispatchData* data); - private: - const LogDispatchData* m_data; - void dispatch(base::type::string_t&& logLine); -}; -#if ELPP_ASYNC_LOGGING -class AsyncLogDispatchCallback : public LogDispatchCallback { - protected: - void handle(const LogDispatchData* data); -}; -class AsyncDispatchWorker : public base::IWorker, public base::threading::ThreadSafe { - public: - AsyncDispatchWorker(); - virtual ~AsyncDispatchWorker(); - - bool clean(void); - void emptyQueue(void); - virtual void start(void); - void handle(AsyncLogItem* logItem); - void run(void); - - void setContinueRunning(bool value) { - base::threading::ScopedLock scopedLock(m_continueRunningLock); - m_continueRunning = value; - } - - bool continueRunning(void) const { - return m_continueRunning; - } - private: - std::condition_variable cv; - bool m_continueRunning; - base::threading::Mutex m_continueRunningLock; -}; -#endif // ELPP_ASYNC_LOGGING -} // namespace base -namespace base { -class DefaultLogBuilder : public LogBuilder { - public: - base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const; -}; -/// @brief Dispatches log messages -class LogDispatcher : base::NoCopy { - public: - LogDispatcher(bool proceed, LogMessage* logMessage, base::DispatchAction dispatchAction) : - m_proceed(proceed), - m_logMessage(logMessage), - m_dispatchAction(std::move(dispatchAction)) { - } - - void dispatch(void); - - private: - bool m_proceed; - LogMessage* m_logMessage; - base::DispatchAction m_dispatchAction; -}; -#if defined(ELPP_STL_LOGGING) -/// @brief Workarounds to write some STL logs -/// -/// @detail There is workaround needed to loop through some stl containers. In order to do that, we need iterable containers -/// of same type and provide iterator interface and pass it on to writeIterator(). -/// Remember, this is passed by value in constructor so that we dont change original containers. -/// This operation is as expensive as Big-O(std::min(class_.size(), base::consts::kMaxLogPerContainer)) -namespace workarounds { -/// @brief Abstract IterableContainer template that provides interface for iterable classes of type T -template -class IterableContainer { - public: - typedef typename Container::iterator iterator; - typedef typename Container::const_iterator const_iterator; - IterableContainer(void) {} - virtual ~IterableContainer(void) {} - iterator begin(void) { - return getContainer().begin(); - } - iterator end(void) { - return getContainer().end(); - } - private: - virtual Container& getContainer(void) = 0; -}; -/// @brief Implements IterableContainer and provides iterable std::priority_queue class -template, typename Comparator = std::less> -class IterablePriorityQueue : public IterableContainer, - public std::priority_queue { - public: - IterablePriorityQueue(std::priority_queue queue_) { - std::size_t count_ = 0; - while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) { - this->push(queue_.top()); - queue_.pop(); - } - } - private: - inline Container& getContainer(void) { - return this->c; - } -}; -/// @brief Implements IterableContainer and provides iterable std::queue class -template> -class IterableQueue : public IterableContainer, public std::queue { - public: - IterableQueue(std::queue queue_) { - std::size_t count_ = 0; - while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) { - this->push(queue_.front()); - queue_.pop(); - } - } - private: - inline Container& getContainer(void) { - return this->c; - } -}; -/// @brief Implements IterableContainer and provides iterable std::stack class -template> -class IterableStack : public IterableContainer, public std::stack { - public: - IterableStack(std::stack stack_) { - std::size_t count_ = 0; - while (++count_ < base::consts::kMaxLogPerContainer && !stack_.empty()) { - this->push(stack_.top()); - stack_.pop(); - } - } - private: - inline Container& getContainer(void) { - return this->c; - } -}; -} // namespace workarounds -#endif // defined(ELPP_STL_LOGGING) -// Log message builder -class MessageBuilder { - public: - MessageBuilder(void) : m_logger(nullptr), m_containerLogSeparator(ELPP_LITERAL("")) {} - void initialize(Logger* logger); - -# define ELPP_SIMPLE_LOG(LOG_TYPE)\ -MessageBuilder& operator<<(LOG_TYPE msg) {\ -m_logger->stream() << msg;\ -if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {\ -m_logger->stream() << " ";\ -}\ -return *this;\ -} - - inline MessageBuilder& operator<<(const std::string& msg) { - return operator<<(msg.c_str()); - } - ELPP_SIMPLE_LOG(char) - ELPP_SIMPLE_LOG(bool) - ELPP_SIMPLE_LOG(signed short) - ELPP_SIMPLE_LOG(unsigned short) - ELPP_SIMPLE_LOG(signed int) - ELPP_SIMPLE_LOG(unsigned int) - ELPP_SIMPLE_LOG(signed long) - ELPP_SIMPLE_LOG(unsigned long) - ELPP_SIMPLE_LOG(float) - ELPP_SIMPLE_LOG(double) - ELPP_SIMPLE_LOG(char*) - ELPP_SIMPLE_LOG(const char*) - ELPP_SIMPLE_LOG(const void*) - ELPP_SIMPLE_LOG(long double) - inline MessageBuilder& operator<<(const std::wstring& msg) { - return operator<<(msg.c_str()); - } - MessageBuilder& operator<<(const wchar_t* msg); - // ostream manipulators - inline MessageBuilder& operator<<(std::ostream& (*OStreamMani)(std::ostream&)) { - m_logger->stream() << OStreamMani; - return *this; - } -#define ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} -#define ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} -#define ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} -#define ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} -#define ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} - -#if defined(ELPP_STL_LOGGING) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::vector) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::list) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::deque) - ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::set) - ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::multiset) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::map) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::multimap) - template - inline MessageBuilder& operator<<(const std::queue& queue_) { - base::workarounds::IterableQueue iterableQueue_ = - static_cast >(queue_); - return writeIterator(iterableQueue_.begin(), iterableQueue_.end(), iterableQueue_.size()); - } - template - inline MessageBuilder& operator<<(const std::stack& stack_) { - base::workarounds::IterableStack iterableStack_ = - static_cast >(stack_); - return writeIterator(iterableStack_.begin(), iterableStack_.end(), iterableStack_.size()); - } - template - inline MessageBuilder& operator<<(const std::priority_queue& priorityQueue_) { - base::workarounds::IterablePriorityQueue iterablePriorityQueue_ = - static_cast >(priorityQueue_); - return writeIterator(iterablePriorityQueue_.begin(), iterablePriorityQueue_.end(), iterablePriorityQueue_.size()); - } - template - MessageBuilder& operator<<(const std::pair& pair_) { - m_logger->stream() << ELPP_LITERAL("("); - operator << (static_cast(pair_.first)); - m_logger->stream() << ELPP_LITERAL(", "); - operator << (static_cast(pair_.second)); - m_logger->stream() << ELPP_LITERAL(")"); - return *this; - } - template - MessageBuilder& operator<<(const std::bitset& bitset_) { - m_logger->stream() << ELPP_LITERAL("["); - operator << (bitset_.to_string()); - m_logger->stream() << ELPP_LITERAL("]"); - return *this; - } -# if defined(ELPP_LOG_STD_ARRAY) - template - inline MessageBuilder& operator<<(const std::array& array) { - return writeIterator(array.begin(), array.end(), array.size()); - } -# endif // defined(ELPP_LOG_STD_ARRAY) -# if defined(ELPP_LOG_UNORDERED_MAP) - ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_map) - ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_multimap) -# endif // defined(ELPP_LOG_UNORDERED_MAP) -# if defined(ELPP_LOG_UNORDERED_SET) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_set) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_multiset) -# endif // defined(ELPP_LOG_UNORDERED_SET) -#endif // defined(ELPP_STL_LOGGING) -#if defined(ELPP_QT_LOGGING) - inline MessageBuilder& operator<<(const QString& msg) { -# if defined(ELPP_UNICODE) - m_logger->stream() << msg.toStdWString(); -# else - m_logger->stream() << msg.toStdString(); -# endif // defined(ELPP_UNICODE) - return *this; - } - inline MessageBuilder& operator<<(const QByteArray& msg) { - return operator << (QString(msg)); - } - inline MessageBuilder& operator<<(const QStringRef& msg) { - return operator<<(msg.toString()); - } - inline MessageBuilder& operator<<(qint64 msg) { -# if defined(ELPP_UNICODE) - m_logger->stream() << QString::number(msg).toStdWString(); -# else - m_logger->stream() << QString::number(msg).toStdString(); -# endif // defined(ELPP_UNICODE) - return *this; - } - inline MessageBuilder& operator<<(quint64 msg) { -# if defined(ELPP_UNICODE) - m_logger->stream() << QString::number(msg).toStdWString(); -# else - m_logger->stream() << QString::number(msg).toStdString(); -# endif // defined(ELPP_UNICODE) - return *this; - } - inline MessageBuilder& operator<<(QChar msg) { - m_logger->stream() << msg.toLatin1(); - return *this; - } - inline MessageBuilder& operator<<(const QLatin1String& msg) { - m_logger->stream() << msg.latin1(); - return *this; - } - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QList) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QVector) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QQueue) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QSet) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QLinkedList) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QStack) - template - MessageBuilder& operator<<(const QPair& pair_) { - m_logger->stream() << ELPP_LITERAL("("); - operator << (static_cast(pair_.first)); - m_logger->stream() << ELPP_LITERAL(", "); - operator << (static_cast(pair_.second)); - m_logger->stream() << ELPP_LITERAL(")"); - return *this; - } - template - MessageBuilder& operator<<(const QMap& map_) { - m_logger->stream() << ELPP_LITERAL("["); - QList keys = map_.keys(); - typename QList::const_iterator begin = keys.begin(); - typename QList::const_iterator end = keys.end(); - int max_ = static_cast(base::consts::kMaxLogPerContainer); // to prevent warning - for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) { - m_logger->stream() << ELPP_LITERAL("("); - operator << (static_cast(*begin)); - m_logger->stream() << ELPP_LITERAL(", "); - operator << (static_cast(map_.value(*begin))); - m_logger->stream() << ELPP_LITERAL(")"); - m_logger->stream() << ((index_ < keys.size() -1) ? m_containerLogSeparator : ELPP_LITERAL("")); - } - if (begin != end) { - m_logger->stream() << ELPP_LITERAL("..."); - } - m_logger->stream() << ELPP_LITERAL("]"); - return *this; - } - template - inline MessageBuilder& operator<<(const QMultiMap& map_) { - operator << (static_cast>(map_)); - return *this; - } - template - MessageBuilder& operator<<(const QHash& hash_) { - m_logger->stream() << ELPP_LITERAL("["); - QList keys = hash_.keys(); - typename QList::const_iterator begin = keys.begin(); - typename QList::const_iterator end = keys.end(); - int max_ = static_cast(base::consts::kMaxLogPerContainer); // prevent type warning - for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) { - m_logger->stream() << ELPP_LITERAL("("); - operator << (static_cast(*begin)); - m_logger->stream() << ELPP_LITERAL(", "); - operator << (static_cast(hash_.value(*begin))); - m_logger->stream() << ELPP_LITERAL(")"); - m_logger->stream() << ((index_ < keys.size() -1) ? m_containerLogSeparator : ELPP_LITERAL("")); - } - if (begin != end) { - m_logger->stream() << ELPP_LITERAL("..."); - } - m_logger->stream() << ELPP_LITERAL("]"); - return *this; - } - template - inline MessageBuilder& operator<<(const QMultiHash& multiHash_) { - operator << (static_cast>(multiHash_)); - return *this; - } -#endif // defined(ELPP_QT_LOGGING) -#if defined(ELPP_BOOST_LOGGING) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::vector) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::stable_vector) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::list) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::deque) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::map) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::flat_map) - ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::set) - ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::flat_set) -#endif // defined(ELPP_BOOST_LOGGING) - - /// @brief Macro used internally that can be used externally to make containers easylogging++ friendly - /// - /// @detail This macro expands to write an ostream& operator<< for container. This container is expected to - /// have begin() and end() methods that return respective iterators - /// @param ContainerType Type of container e.g, MyList from WX_DECLARE_LIST(int, MyList); in wxwidgets - /// @param SizeMethod Method used to get size of container. - /// @param ElementInstance Instance of element to be fed out. Instance name is "elem". See WXELPP_ENABLED macro - /// for an example usage -#define MAKE_CONTAINERELPP_FRIENDLY(ContainerType, SizeMethod, ElementInstance) \ -el::base::type::ostream_t& operator<<(el::base::type::ostream_t& ss, const ContainerType& container) {\ -const el::base::type::char_t* sep = ELPP->hasFlag(el::LoggingFlag::NewLineForContainer) ? \ -ELPP_LITERAL("\n ") : ELPP_LITERAL(", ");\ -ContainerType::const_iterator elem = container.begin();\ -ContainerType::const_iterator endElem = container.end();\ -std::size_t size_ = container.SizeMethod; \ -ss << ELPP_LITERAL("[");\ -for (std::size_t i = 0; elem != endElem && i < el::base::consts::kMaxLogPerContainer; ++i, ++elem) { \ -ss << ElementInstance;\ -ss << ((i < size_ - 1) ? sep : ELPP_LITERAL(""));\ -}\ -if (elem != endElem) {\ -ss << ELPP_LITERAL("...");\ -}\ -ss << ELPP_LITERAL("]");\ -return ss;\ -} -#if defined(ELPP_WXWIDGETS_LOGGING) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(wxVector) -# define ELPP_WX_PTR_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), *(*elem)) -# define ELPP_WX_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), (*elem)) -# define ELPP_WX_HASH_MAP_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), \ -ELPP_LITERAL("(") << elem->first << ELPP_LITERAL(", ") << elem->second << ELPP_LITERAL(")") -#else -# define ELPP_WX_PTR_ENABLED(ContainerType) -# define ELPP_WX_ENABLED(ContainerType) -# define ELPP_WX_HASH_MAP_ENABLED(ContainerType) -#endif // defined(ELPP_WXWIDGETS_LOGGING) - // Other classes - template - ELPP_SIMPLE_LOG(const Class&) -#undef ELPP_SIMPLE_LOG -#undef ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG -#undef ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG -#undef ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG -#undef ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG -#undef ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG - private: - Logger* m_logger; - const base::type::char_t* m_containerLogSeparator; - - template - MessageBuilder& writeIterator(Iterator begin_, Iterator end_, std::size_t size_) { - m_logger->stream() << ELPP_LITERAL("["); - for (std::size_t i = 0; begin_ != end_ && i < base::consts::kMaxLogPerContainer; ++i, ++begin_) { - operator << (*begin_); - m_logger->stream() << ((i < size_ - 1) ? m_containerLogSeparator : ELPP_LITERAL("")); - } - if (begin_ != end_) { - m_logger->stream() << ELPP_LITERAL("..."); - } - m_logger->stream() << ELPP_LITERAL("]"); - if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) { - m_logger->stream() << " "; - } - return *this; - } -}; -/// @brief Writes nothing - Used when certain log is disabled -class NullWriter : base::NoCopy { - public: - NullWriter(void) {} - - // Null manipulator - inline NullWriter& operator<<(std::ostream& (*)(std::ostream&)) { - return *this; - } - - template - inline NullWriter& operator<<(const T&) { - return *this; - } - - inline operator bool() { - return true; - } -}; -/// @brief Main entry point of each logging -class Writer : base::NoCopy { - public: - Writer(Level level, const char* file, base::type::LineNumber line, - const char* func, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog, - base::type::VerboseLevel verboseLevel = 0) : - m_msg(nullptr), m_level(level), m_file(file), m_line(line), m_func(func), m_verboseLevel(verboseLevel), - m_logger(nullptr), m_proceed(false), m_dispatchAction(dispatchAction) { - } - - Writer(LogMessage* msg, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog) : - m_msg(msg), m_level(msg != nullptr ? msg->level() : Level::Unknown), - m_line(0), m_logger(nullptr), m_proceed(false), m_dispatchAction(dispatchAction) { - } - - virtual ~Writer(void) { - processDispatch(); - } - - template - inline Writer& operator<<(const T& log) { -#if ELPP_LOGGING_ENABLED - if (m_proceed) { - m_messageBuilder << log; - } -#endif // ELPP_LOGGING_ENABLED - return *this; - } - - inline Writer& operator<<(std::ostream& (*log)(std::ostream&)) { -#if ELPP_LOGGING_ENABLED - if (m_proceed) { - m_messageBuilder << log; - } -#endif // ELPP_LOGGING_ENABLED - return *this; - } - - inline operator bool() { - return true; - } - - Writer& construct(Logger* logger, bool needLock = true); - Writer& construct(int count, const char* loggerIds, ...); - protected: - LogMessage* m_msg; - Level m_level; - const char* m_file; - const base::type::LineNumber m_line; - const char* m_func; - base::type::VerboseLevel m_verboseLevel; - Logger* m_logger; - bool m_proceed; - base::MessageBuilder m_messageBuilder; - base::DispatchAction m_dispatchAction; - std::vector m_loggerIds; - friend class el::Helpers; - - void initializeLogger(const std::string& loggerId, bool lookup = true, bool needLock = true); - void processDispatch(); - void triggerDispatch(void); -}; -class PErrorWriter : public base::Writer { - public: - PErrorWriter(Level level, const char* file, base::type::LineNumber line, - const char* func, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog, - base::type::VerboseLevel verboseLevel = 0) : - base::Writer(level, file, line, func, dispatchAction, verboseLevel) { - } - - virtual ~PErrorWriter(void); -}; -} // namespace base -// Logging from Logger class. Why this is here? Because we have Storage and Writer class available -#if ELPP_VARIADIC_TEMPLATES_SUPPORTED -template -void Logger::log_(Level varlevel, int vlevel, const char* s, const T& value, const Args&... args) { - base::MessageBuilder b; - b.initialize(this); - while (*s) { - if (*s == base::consts::kFormatSpecifierChar) { - if (*(s + 1) == base::consts::kFormatSpecifierChar) { - ++s; - } else { - if (*(s + 1) == base::consts::kFormatSpecifierCharValue) { - ++s; - b << value; - log_(varlevel, vlevel, ++s, args...); - return; - } - } - } - b << *s++; - } - ELPP_INTERNAL_ERROR("Too many arguments provided. Unable to handle. Please provide more format specifiers", false); -} -template -void Logger::log_(Level varlevel, int vlevel, const T& vlog) { - if (varlevel == Level::Verbose) { - if (ELPP->vRegistry()->allowed(static_cast(vlevel), __FILE__)) { - base::Writer(Level::Verbose, "FILE", 0, "FUNCTION", - base::DispatchAction::NormalLog, vlevel).construct(this, false) << vlog; - } else { - stream().str(ELPP_LITERAL("")); - releaseLock(); - } - } else { - base::Writer(varlevel, "FILE", 0, "FUNCTION").construct(this, false) << vlog; - } -} -template -inline void Logger::log(Level varlevel, const char* s, const T& value, const Args&... args) { - acquireLock(); // released in Writer! - log_(varlevel, 0, s, value, args...); -} -template -inline void Logger::log(Level varlevel, const T& vlog) { - acquireLock(); // released in Writer! - log_(varlevel, 0, vlog); -} -# if ELPP_VERBOSE_LOG -template -inline void Logger::verbose(int vlevel, const char* s, const T& value, const Args&... args) { - acquireLock(); // released in Writer! - log_(el::Level::Verbose, vlevel, s, value, args...); -} -template -inline void Logger::verbose(int vlevel, const T& vlog) { - acquireLock(); // released in Writer! - log_(el::Level::Verbose, vlevel, vlog); -} -# else -template -inline void Logger::verbose(int, const char*, const T&, const Args&...) { - return; -} -template -inline void Logger::verbose(int, const T&) { - return; -} -# endif // ELPP_VERBOSE_LOG -# define LOGGER_LEVEL_WRITERS(FUNCTION_NAME, LOG_LEVEL)\ -template \ -inline void Logger::FUNCTION_NAME(const char* s, const T& value, const Args&... args) {\ -log(LOG_LEVEL, s, value, args...);\ -}\ -template \ -inline void Logger::FUNCTION_NAME(const T& value) {\ -log(LOG_LEVEL, value);\ -} -# define LOGGER_LEVEL_WRITERS_DISABLED(FUNCTION_NAME, LOG_LEVEL)\ -template \ -inline void Logger::FUNCTION_NAME(const char*, const T&, const Args&...) {\ -return;\ -}\ -template \ -inline void Logger::FUNCTION_NAME(const T&) {\ -return;\ -} - -# if ELPP_INFO_LOG -LOGGER_LEVEL_WRITERS(info, Level::Info) -# else -LOGGER_LEVEL_WRITERS_DISABLED(info, Level::Info) -# endif // ELPP_INFO_LOG -# if ELPP_DEBUG_LOG -LOGGER_LEVEL_WRITERS(debug, Level::Debug) -# else -LOGGER_LEVEL_WRITERS_DISABLED(debug, Level::Debug) -# endif // ELPP_DEBUG_LOG -# if ELPP_WARNING_LOG -LOGGER_LEVEL_WRITERS(warn, Level::Warning) -# else -LOGGER_LEVEL_WRITERS_DISABLED(warn, Level::Warning) -# endif // ELPP_WARNING_LOG -# if ELPP_ERROR_LOG -LOGGER_LEVEL_WRITERS(error, Level::Error) -# else -LOGGER_LEVEL_WRITERS_DISABLED(error, Level::Error) -# endif // ELPP_ERROR_LOG -# if ELPP_FATAL_LOG -LOGGER_LEVEL_WRITERS(fatal, Level::Fatal) -# else -LOGGER_LEVEL_WRITERS_DISABLED(fatal, Level::Fatal) -# endif // ELPP_FATAL_LOG -# if ELPP_TRACE_LOG -LOGGER_LEVEL_WRITERS(trace, Level::Trace) -# else -LOGGER_LEVEL_WRITERS_DISABLED(trace, Level::Trace) -# endif // ELPP_TRACE_LOG -# undef LOGGER_LEVEL_WRITERS -# undef LOGGER_LEVEL_WRITERS_DISABLED -#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED -#if ELPP_COMPILER_MSVC -# define ELPP_VARIADIC_FUNC_MSVC(variadicFunction, variadicArgs) variadicFunction variadicArgs -# define ELPP_VARIADIC_FUNC_MSVC_RUN(variadicFunction, ...) ELPP_VARIADIC_FUNC_MSVC(variadicFunction, (__VA_ARGS__)) -# define el_getVALength(...) ELPP_VARIADIC_FUNC_MSVC_RUN(el_resolveVALength, 0, ## __VA_ARGS__,\ -10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) -#else -# if ELPP_COMPILER_CLANG -# define el_getVALength(...) el_resolveVALength(0, __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) -# else -# define el_getVALength(...) el_resolveVALength(0, ## __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) -# endif // ELPP_COMPILER_CLANG -#endif // ELPP_COMPILER_MSVC -#define el_resolveVALength(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N -#define ELPP_WRITE_LOG(writer, level, dispatchAction, ...) \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#define ELPP_WRITE_LOG_IF(writer, condition, level, dispatchAction, ...) if (condition) \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#define ELPP_WRITE_LOG_EVERY_N(writer, occasion, level, dispatchAction, ...) \ -ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion) && \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#define ELPP_WRITE_LOG_AFTER_N(writer, n, level, dispatchAction, ...) \ -ELPP->validateAfterNCounter(__FILE__, __LINE__, n) && \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#define ELPP_WRITE_LOG_N_TIMES(writer, n, level, dispatchAction, ...) \ -ELPP->validateNTimesCounter(__FILE__, __LINE__, n) && \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) -class PerformanceTrackingData { - public: - enum class DataType : base::type::EnumType { - Checkpoint = 1, Complete = 2 - }; - // Do not use constructor, will run into multiple definition error, use init(PerformanceTracker*) - explicit PerformanceTrackingData(DataType dataType) : m_performanceTracker(nullptr), - m_dataType(dataType), m_firstCheckpoint(false), m_file(""), m_line(0), m_func("") {} - inline const std::string* blockName(void) const; - inline const struct timeval* startTime(void) const; - inline const struct timeval* endTime(void) const; - inline const struct timeval* lastCheckpointTime(void) const; - inline const base::PerformanceTracker* performanceTracker(void) const { - return m_performanceTracker; - } - inline PerformanceTrackingData::DataType dataType(void) const { - return m_dataType; - } - inline bool firstCheckpoint(void) const { - return m_firstCheckpoint; - } - inline std::string checkpointId(void) const { - return m_checkpointId; - } - inline const char* file(void) const { - return m_file; - } - inline base::type::LineNumber line(void) const { - return m_line; - } - inline const char* func(void) const { - return m_func; - } - inline const base::type::string_t* formattedTimeTaken() const { - return &m_formattedTimeTaken; - } - inline const std::string& loggerId(void) const; - private: - base::PerformanceTracker* m_performanceTracker; - base::type::string_t m_formattedTimeTaken; - PerformanceTrackingData::DataType m_dataType; - bool m_firstCheckpoint; - std::string m_checkpointId; - const char* m_file; - base::type::LineNumber m_line; - const char* m_func; - inline void init(base::PerformanceTracker* performanceTracker, bool firstCheckpoint = false) { - m_performanceTracker = performanceTracker; - m_firstCheckpoint = firstCheckpoint; - } - - friend class el::base::PerformanceTracker; -}; -namespace base { -/// @brief Represents performanceTracker block of code that conditionally adds performance status to log -/// either when goes outside the scope of when checkpoint() is called -class PerformanceTracker : public base::threading::ThreadSafe, public Loggable { - public: - PerformanceTracker(const std::string& blockName, - base::TimestampUnit timestampUnit = base::TimestampUnit::Millisecond, - const std::string& loggerId = std::string(el::base::consts::kPerformanceLoggerId), - bool scopedLog = true, Level level = base::consts::kPerformanceTrackerDefaultLevel); - /// @brief Copy constructor - PerformanceTracker(const PerformanceTracker& t) : - m_blockName(t.m_blockName), m_timestampUnit(t.m_timestampUnit), m_loggerId(t.m_loggerId), m_scopedLog(t.m_scopedLog), - m_level(t.m_level), m_hasChecked(t.m_hasChecked), m_lastCheckpointId(t.m_lastCheckpointId), m_enabled(t.m_enabled), - m_startTime(t.m_startTime), m_endTime(t.m_endTime), m_lastCheckpointTime(t.m_lastCheckpointTime) { - } - virtual ~PerformanceTracker(void); - /// @brief A checkpoint for current performanceTracker block. - void checkpoint(const std::string& id = std::string(), const char* file = __FILE__, - base::type::LineNumber line = __LINE__, - const char* func = ""); - inline Level level(void) const { - return m_level; - } - private: - std::string m_blockName; - base::TimestampUnit m_timestampUnit; - std::string m_loggerId; - bool m_scopedLog; - Level m_level; - bool m_hasChecked; - std::string m_lastCheckpointId; - bool m_enabled; - struct timeval m_startTime, m_endTime, m_lastCheckpointTime; - - PerformanceTracker(void); - - friend class el::PerformanceTrackingData; - friend class base::DefaultPerformanceTrackingCallback; - - const inline base::type::string_t getFormattedTimeTaken() const { - return getFormattedTimeTaken(m_startTime); - } - - const base::type::string_t getFormattedTimeTaken(struct timeval startTime) const; - - virtual inline void log(el::base::type::ostream_t& os) const { - os << getFormattedTimeTaken(); - } -}; -class DefaultPerformanceTrackingCallback : public PerformanceTrackingCallback { - protected: - void handle(const PerformanceTrackingData* data) { - m_data = data; - base::type::stringstream_t ss; - if (m_data->dataType() == PerformanceTrackingData::DataType::Complete) { - ss << ELPP_LITERAL("Executed [") << m_data->blockName()->c_str() << ELPP_LITERAL("] in [") << - *m_data->formattedTimeTaken() << ELPP_LITERAL("]"); - } else { - ss << ELPP_LITERAL("Performance checkpoint"); - if (!m_data->checkpointId().empty()) { - ss << ELPP_LITERAL(" [") << m_data->checkpointId().c_str() << ELPP_LITERAL("]"); - } - ss << ELPP_LITERAL(" for block [") << m_data->blockName()->c_str() << ELPP_LITERAL("] : [") << - *m_data->performanceTracker(); - if (!ELPP->hasFlag(LoggingFlag::DisablePerformanceTrackingCheckpointComparison) - && m_data->performanceTracker()->m_hasChecked) { - ss << ELPP_LITERAL(" ([") << *m_data->formattedTimeTaken() << ELPP_LITERAL("] from "); - if (m_data->performanceTracker()->m_lastCheckpointId.empty()) { - ss << ELPP_LITERAL("last checkpoint"); - } else { - ss << ELPP_LITERAL("checkpoint '") << m_data->performanceTracker()->m_lastCheckpointId.c_str() << ELPP_LITERAL("'"); - } - ss << ELPP_LITERAL(")]"); - } else { - ss << ELPP_LITERAL("]"); - } - } - el::base::Writer(m_data->performanceTracker()->level(), m_data->file(), m_data->line(), m_data->func()).construct(1, - m_data->loggerId().c_str()) << ss.str(); - } - private: - const PerformanceTrackingData* m_data; -}; -} // namespace base -inline const std::string* PerformanceTrackingData::blockName() const { - return const_cast(&m_performanceTracker->m_blockName); -} -inline const struct timeval* PerformanceTrackingData::startTime() const { - return const_cast(&m_performanceTracker->m_startTime); -} -inline const struct timeval* PerformanceTrackingData::endTime() const { - return const_cast(&m_performanceTracker->m_endTime); -} -inline const struct timeval* PerformanceTrackingData::lastCheckpointTime() const { - return const_cast(&m_performanceTracker->m_lastCheckpointTime); -} -inline const std::string& PerformanceTrackingData::loggerId(void) const { - return m_performanceTracker->m_loggerId; -} -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) -namespace base { -/// @brief Contains some internal debugging tools like crash handler and stack tracer -namespace debug { -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) -class StackTrace : base::NoCopy { - public: - static const unsigned int kMaxStack = 64; - static const unsigned int kStackStart = 2; // We want to skip c'tor and StackTrace::generateNew() - class StackTraceEntry { - public: - StackTraceEntry(std::size_t index, const std::string& loc, const std::string& demang, const std::string& hex, - const std::string& addr); - StackTraceEntry(std::size_t index, const std::string& loc) : - m_index(index), - m_location(loc) { - } - std::size_t m_index; - std::string m_location; - std::string m_demangled; - std::string m_hex; - std::string m_addr; - friend std::ostream& operator<<(std::ostream& ss, const StackTraceEntry& si); - - private: - StackTraceEntry(void); - }; - - StackTrace(void) { - generateNew(); - } - - virtual ~StackTrace(void) { - } - - inline std::vector& getLatestStack(void) { - return m_stack; - } - - friend std::ostream& operator<<(std::ostream& os, const StackTrace& st); - - private: - std::vector m_stack; - - void generateNew(void); -}; -/// @brief Handles unexpected crashes -class CrashHandler : base::NoCopy { - public: - typedef void (*Handler)(int); - - explicit CrashHandler(bool useDefault); - explicit CrashHandler(const Handler& cHandler) { - setHandler(cHandler); - } - void setHandler(const Handler& cHandler); - - private: - Handler m_handler; -}; -#else -class CrashHandler { - public: - explicit CrashHandler(bool) {} -}; -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) -} // namespace debug -} // namespace base -extern base::debug::CrashHandler elCrashHandler; -#define MAKE_LOGGABLE(ClassType, ClassInstance, OutputStreamInstance) \ -el::base::type::ostream_t& operator<<(el::base::type::ostream_t& OutputStreamInstance, const ClassType& ClassInstance) -/// @brief Initializes syslog with process ID, options and facility. calls closelog() on d'tor -class SysLogInitializer { - public: - SysLogInitializer(const char* processIdent, int options = 0, int facility = 0) { -#if defined(ELPP_SYSLOG) - (void)base::consts::kSysLogLoggerId; - openlog(processIdent, options, facility); -#else - ELPP_UNUSED(processIdent); - ELPP_UNUSED(options); - ELPP_UNUSED(facility); -#endif // defined(ELPP_SYSLOG) - } - virtual ~SysLogInitializer(void) { -#if defined(ELPP_SYSLOG) - closelog(); -#endif // defined(ELPP_SYSLOG) - } -}; -#define ELPP_INITIALIZE_SYSLOG(id, opt, fac) el::SysLogInitializer elSyslogInit(id, opt, fac) -/// @brief Static helpers for developers -class Helpers : base::StaticClass { - public: - /// @brief Shares logging repository (base::Storage) - static inline void setStorage(base::type::StoragePointer storage) { - ELPP = storage; - } - /// @return Main storage repository - static inline base::type::StoragePointer storage() { - return ELPP; - } - /// @brief Sets application arguments and figures out whats active for logging and whats not. - static inline void setArgs(int argc, char** argv) { - ELPP->setApplicationArguments(argc, argv); - } - /// @copydoc setArgs(int argc, char** argv) - static inline void setArgs(int argc, const char** argv) { - ELPP->setApplicationArguments(argc, const_cast(argv)); - } - /// @brief Sets thread name for current thread. Requires std::thread - static inline void setThreadName(const std::string& name) { - ELPP->setThreadName(name); - } - static inline std::string getThreadName() { - return ELPP->getThreadName(base::threading::getCurrentThreadId()); - } -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - /// @brief Overrides default crash handler and installs custom handler. - /// @param crashHandler A functor with no return type that takes single int argument. - /// Handler is a typedef with specification: void (*Handler)(int) - static inline void setCrashHandler(const el::base::debug::CrashHandler::Handler& crashHandler) { - el::elCrashHandler.setHandler(crashHandler); - } - /// @brief Abort due to crash with signal in parameter - /// @param sig Crash signal - static void crashAbort(int sig, const char* sourceFile = "", unsigned int long line = 0); - /// @brief Logs reason of crash as per sig - /// @param sig Crash signal - /// @param stackTraceIfAvailable Includes stack trace if available - /// @param level Logging level - /// @param logger Logger to use for logging - static void logCrashReason(int sig, bool stackTraceIfAvailable = false, - Level level = Level::Fatal, const char* logger = base::consts::kDefaultLoggerId); -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - /// @brief Installs pre rollout callback, this callback is triggered when log file is about to be rolled out - /// (can be useful for backing up) - static inline void installPreRollOutCallback(const PreRollOutCallback& callback) { - ELPP->setPreRollOutCallback(callback); - } - /// @brief Uninstalls pre rollout callback - static inline void uninstallPreRollOutCallback(void) { - ELPP->unsetPreRollOutCallback(); - } - /// @brief Installs post log dispatch callback, this callback is triggered when log is dispatched - template - static inline bool installLogDispatchCallback(const std::string& id) { - return ELPP->installLogDispatchCallback(id); - } - /// @brief Uninstalls log dispatch callback - template - static inline void uninstallLogDispatchCallback(const std::string& id) { - ELPP->uninstallLogDispatchCallback(id); - } - template - static inline T* logDispatchCallback(const std::string& id) { - return ELPP->logDispatchCallback(id); - } -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - /// @brief Installs post performance tracking callback, this callback is triggered when performance tracking is finished - template - static inline bool installPerformanceTrackingCallback(const std::string& id) { - return ELPP->installPerformanceTrackingCallback(id); - } - /// @brief Uninstalls post performance tracking handler - template - static inline void uninstallPerformanceTrackingCallback(const std::string& id) { - ELPP->uninstallPerformanceTrackingCallback(id); - } - template - static inline T* performanceTrackingCallback(const std::string& id) { - return ELPP->performanceTrackingCallback(id); - } -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - /// @brief Converts template to std::string - useful for loggable classes to log containers within log(std::ostream&) const - template - static std::string convertTemplateToStdString(const T& templ) { - el::Logger* logger = - ELPP->registeredLoggers()->get(el::base::consts::kDefaultLoggerId); - if (logger == nullptr) { - return std::string(); - } - base::MessageBuilder b; - b.initialize(logger); - logger->acquireLock(); - b << templ; -#if defined(ELPP_UNICODE) - std::string s = std::string(logger->stream().str().begin(), logger->stream().str().end()); -#else - std::string s = logger->stream().str(); -#endif // defined(ELPP_UNICODE) - logger->stream().str(ELPP_LITERAL("")); - logger->releaseLock(); - return s; - } - /// @brief Returns command line arguments (pointer) provided to easylogging++ - static inline const el::base::utils::CommandLineArgs* commandLineArgs(void) { - return ELPP->commandLineArgs(); - } - /// @brief Reserve space for custom format specifiers for performance - /// @see std::vector::reserve - static inline void reserveCustomFormatSpecifiers(std::size_t size) { - ELPP->m_customFormatSpecifiers.reserve(size); - } - /// @brief Installs user defined format specifier and handler - static inline void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) { - ELPP->installCustomFormatSpecifier(customFormatSpecifier); - } - /// @brief Uninstalls user defined format specifier and handler - static inline bool uninstallCustomFormatSpecifier(const char* formatSpecifier) { - return ELPP->uninstallCustomFormatSpecifier(formatSpecifier); - } - /// @brief Returns true if custom format specifier is installed - static inline bool hasCustomFormatSpecifier(const char* formatSpecifier) { - return ELPP->hasCustomFormatSpecifier(formatSpecifier); - } - static inline void validateFileRolling(Logger* logger, Level level) { - if (ELPP == nullptr || logger == nullptr) return; - logger->m_typedConfigurations->validateFileRolling(level, ELPP->preRollOutCallback()); - } -}; -/// @brief Static helpers to deal with loggers and their configurations -class Loggers : base::StaticClass { - public: - /// @brief Gets existing or registers new logger - static Logger* getLogger(const std::string& identity, bool registerIfNotAvailable = true); - /// @brief Changes default log builder for future loggers - static void setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr); - /// @brief Installs logger registration callback, this callback is triggered when new logger is registered - template - static inline bool installLoggerRegistrationCallback(const std::string& id) { - return ELPP->registeredLoggers()->installLoggerRegistrationCallback(id); - } - /// @brief Uninstalls log dispatch callback - template - static inline void uninstallLoggerRegistrationCallback(const std::string& id) { - ELPP->registeredLoggers()->uninstallLoggerRegistrationCallback(id); - } - template - static inline T* loggerRegistrationCallback(const std::string& id) { - return ELPP->registeredLoggers()->loggerRegistrationCallback(id); - } - /// @brief Unregisters logger - use it only when you know what you are doing, you may unregister - /// loggers initialized / used by third-party libs. - static bool unregisterLogger(const std::string& identity); - /// @brief Whether or not logger with id is registered - static bool hasLogger(const std::string& identity); - /// @brief Reconfigures specified logger with new configurations - static Logger* reconfigureLogger(Logger* logger, const Configurations& configurations); - /// @brief Reconfigures logger with new configurations after looking it up using identity - static Logger* reconfigureLogger(const std::string& identity, const Configurations& configurations); - /// @brief Reconfigures logger's single configuration - static Logger* reconfigureLogger(const std::string& identity, ConfigurationType configurationType, - const std::string& value); - /// @brief Reconfigures all the existing loggers with new configurations - static void reconfigureAllLoggers(const Configurations& configurations); - /// @brief Reconfigures single configuration for all the loggers - static inline void reconfigureAllLoggers(ConfigurationType configurationType, const std::string& value) { - reconfigureAllLoggers(Level::Global, configurationType, value); - } - /// @brief Reconfigures single configuration for all the loggers for specified level - static void reconfigureAllLoggers(Level level, ConfigurationType configurationType, - const std::string& value); - /// @brief Sets default configurations. This configuration is used for future (and conditionally for existing) loggers - static void setDefaultConfigurations(const Configurations& configurations, - bool reconfigureExistingLoggers = false); - /// @brief Returns current default - static const Configurations* defaultConfigurations(void); - /// @brief Returns log stream reference pointer if needed by user - static const base::LogStreamsReferenceMapPtr logStreamsReference(void); - /// @brief Default typed configuration based on existing defaultConf - static base::TypedConfigurations defaultTypedConfigurations(void); - /// @brief Populates all logger IDs in current repository. - /// @param [out] targetList List of fill up. - static std::vector* populateAllLoggerIds(std::vector* targetList); - /// @brief Sets configurations from global configuration file. - static void configureFromGlobal(const char* globalConfigurationFilePath); - /// @brief Configures loggers using command line arg. Ensure you have already set command line args, - /// @return False if invalid argument or argument with no value provided, true if attempted to configure logger. - /// If true is returned that does not mean it has been configured successfully, it only means that it - /// has attempted to configure logger using configuration file provided in argument - static bool configureFromArg(const char* argKey); - /// @brief Flushes all loggers for all levels - Be careful if you dont know how many loggers are registered - static void flushAll(void); - /// @brief Adds logging flag used internally. - static inline void addFlag(LoggingFlag flag) { - ELPP->addFlag(flag); - } - /// @brief Removes logging flag used internally. - static inline void removeFlag(LoggingFlag flag) { - ELPP->removeFlag(flag); - } - /// @brief Determines whether or not certain flag is active - static inline bool hasFlag(LoggingFlag flag) { - return ELPP->hasFlag(flag); - } - /// @brief Adds flag and removes it when scope goes out - class ScopedAddFlag { - public: - ScopedAddFlag(LoggingFlag flag) : m_flag(flag) { - Loggers::addFlag(m_flag); - } - ~ScopedAddFlag(void) { - Loggers::removeFlag(m_flag); - } - private: - LoggingFlag m_flag; - }; - /// @brief Removes flag and add it when scope goes out - class ScopedRemoveFlag { - public: - ScopedRemoveFlag(LoggingFlag flag) : m_flag(flag) { - Loggers::removeFlag(m_flag); - } - ~ScopedRemoveFlag(void) { - Loggers::addFlag(m_flag); - } - private: - LoggingFlag m_flag; - }; - /// @brief Sets hierarchy for logging. Needs to enable logging flag (HierarchicalLogging) - static void setLoggingLevel(Level level) { - ELPP->setLoggingLevel(level); - } - /// @brief Sets verbose level on the fly - static void setVerboseLevel(base::type::VerboseLevel level); - /// @brief Gets current verbose level - static base::type::VerboseLevel verboseLevel(void); - /// @brief Sets vmodules as specified (on the fly) - static void setVModules(const char* modules); - /// @brief Clears vmodules - static void clearVModules(void); -}; -class VersionInfo : base::StaticClass { - public: - /// @brief Current version number - static const std::string version(void); - - /// @brief Release date of current version - static const std::string releaseDate(void); -}; -} // namespace el -#undef VLOG_IS_ON -/// @brief Determines whether verbose logging is on for specified level current file. -#define VLOG_IS_ON(verboseLevel) (ELPP->vRegistry()->allowed(verboseLevel, __FILE__)) -#undef TIMED_BLOCK -#undef TIMED_SCOPE -#undef TIMED_SCOPE_IF -#undef TIMED_FUNC -#undef TIMED_FUNC_IF -#undef ELPP_MIN_UNIT -#if defined(ELPP_PERFORMANCE_MICROSECONDS) -# define ELPP_MIN_UNIT el::base::TimestampUnit::Microsecond -#else -# define ELPP_MIN_UNIT el::base::TimestampUnit::Millisecond -#endif // (defined(ELPP_PERFORMANCE_MICROSECONDS)) -/// @brief Performance tracked scope. Performance gets written when goes out of scope using -/// 'performance' logger. -/// -/// @detail Please note in order to check the performance at a certain time you can use obj->checkpoint(); -/// @see el::base::PerformanceTracker -/// @see el::base::PerformanceTracker::checkpoint -// Note: Do not surround this definition with null macro because of obj instance -#define TIMED_SCOPE_IF(obj, blockname, condition) el::base::type::PerformanceTrackerPtr obj( condition ? \ - new el::base::PerformanceTracker(blockname, ELPP_MIN_UNIT) : nullptr ) -#define TIMED_SCOPE(obj, blockname) TIMED_SCOPE_IF(obj, blockname, true) -#define TIMED_BLOCK(obj, blockName) for (struct { int i; el::base::type::PerformanceTrackerPtr timer; } obj = { 0, \ - el::base::type::PerformanceTrackerPtr(new el::base::PerformanceTracker(blockName, ELPP_MIN_UNIT)) }; obj.i < 1; ++obj.i) -/// @brief Performance tracked function. Performance gets written when goes out of scope using -/// 'performance' logger. -/// -/// @detail Please note in order to check the performance at a certain time you can use obj->checkpoint(); -/// @see el::base::PerformanceTracker -/// @see el::base::PerformanceTracker::checkpoint -#define TIMED_FUNC_IF(obj,condition) TIMED_SCOPE_IF(obj, ELPP_FUNC, condition) -#define TIMED_FUNC(obj) TIMED_SCOPE(obj, ELPP_FUNC) -#undef PERFORMANCE_CHECKPOINT -#undef PERFORMANCE_CHECKPOINT_WITH_ID -#define PERFORMANCE_CHECKPOINT(obj) obj->checkpoint(std::string(), __FILE__, __LINE__, ELPP_FUNC) -#define PERFORMANCE_CHECKPOINT_WITH_ID(obj, id) obj->checkpoint(id, __FILE__, __LINE__, ELPP_FUNC) -#undef ELPP_COUNTER -#undef ELPP_COUNTER_POS -/// @brief Gets hit counter for file/line -#define ELPP_COUNTER (ELPP->hitCounters()->getCounter(__FILE__, __LINE__)) -/// @brief Gets hit counter position for file/line, -1 if not registered yet -#define ELPP_COUNTER_POS (ELPP_COUNTER == nullptr ? -1 : ELPP_COUNTER->hitCounts()) -// Undef levels to support LOG(LEVEL) -#undef INFO -#undef WARNING -#undef DEBUG -#undef ERROR -#undef FATAL -#undef TRACE -#undef VERBOSE -// Undef existing -#undef CINFO -#undef CWARNING -#undef CDEBUG -#undef CFATAL -#undef CERROR -#undef CTRACE -#undef CVERBOSE -#undef CINFO_IF -#undef CWARNING_IF -#undef CDEBUG_IF -#undef CERROR_IF -#undef CFATAL_IF -#undef CTRACE_IF -#undef CVERBOSE_IF -#undef CINFO_EVERY_N -#undef CWARNING_EVERY_N -#undef CDEBUG_EVERY_N -#undef CERROR_EVERY_N -#undef CFATAL_EVERY_N -#undef CTRACE_EVERY_N -#undef CVERBOSE_EVERY_N -#undef CINFO_AFTER_N -#undef CWARNING_AFTER_N -#undef CDEBUG_AFTER_N -#undef CERROR_AFTER_N -#undef CFATAL_AFTER_N -#undef CTRACE_AFTER_N -#undef CVERBOSE_AFTER_N -#undef CINFO_N_TIMES -#undef CWARNING_N_TIMES -#undef CDEBUG_N_TIMES -#undef CERROR_N_TIMES -#undef CFATAL_N_TIMES -#undef CTRACE_N_TIMES -#undef CVERBOSE_N_TIMES -// Normal logs -#if ELPP_INFO_LOG -# define CINFO(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE(writer, vlevel, dispatchAction, ...) if (VLOG_IS_ON(vlevel)) writer(\ -el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#else -# define CVERBOSE(writer, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// Conditional logs -#if ELPP_INFO_LOG -# define CINFO_IF(writer, condition_, dispatchAction, ...) \ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) if (VLOG_IS_ON(vlevel) && (condition_)) writer( \ -el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#else -# define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// Occasional logs -#if ELPP_INFO_LOG -# define CINFO_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...)\ -CVERBOSE_IF(writer, ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion), vlevel, dispatchAction, __VA_ARGS__) -#else -# define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// After N logs -#if ELPP_INFO_LOG -# define CINFO_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...)\ -CVERBOSE_IF(writer, ELPP->validateAfterNCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__) -#else -# define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// N Times logs -#if ELPP_INFO_LOG -# define CINFO_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...)\ -CVERBOSE_IF(writer, ELPP->validateNTimesCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__) -#else -# define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// -// Custom Loggers - Requires (level, dispatchAction, loggerId/s) -// -// undef existing -#undef CLOG -#undef CLOG_VERBOSE -#undef CVLOG -#undef CLOG_IF -#undef CLOG_VERBOSE_IF -#undef CVLOG_IF -#undef CLOG_EVERY_N -#undef CVLOG_EVERY_N -#undef CLOG_AFTER_N -#undef CVLOG_AFTER_N -#undef CLOG_N_TIMES -#undef CVLOG_N_TIMES -// Normal logs -#define CLOG(LEVEL, ...)\ -C##LEVEL(el::base::Writer, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG(vlevel, ...) CVERBOSE(el::base::Writer, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -// Conditional logs -#define CLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG_IF(condition, vlevel, ...)\ -CVERBOSE_IF(el::base::Writer, condition, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -// Hit counts based logs -#define CLOG_EVERY_N(n, LEVEL, ...)\ -C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG_EVERY_N(n, vlevel, ...)\ -CVERBOSE_EVERY_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CLOG_AFTER_N(n, LEVEL, ...)\ -C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG_AFTER_N(n, vlevel, ...)\ -CVERBOSE_AFTER_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CLOG_N_TIMES(n, LEVEL, ...)\ -C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG_N_TIMES(n, vlevel, ...)\ -CVERBOSE_N_TIMES(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -// -// Default Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros -// -// undef existing -#undef LOG -#undef VLOG -#undef LOG_IF -#undef VLOG_IF -#undef LOG_EVERY_N -#undef VLOG_EVERY_N -#undef LOG_AFTER_N -#undef VLOG_AFTER_N -#undef LOG_N_TIMES -#undef VLOG_N_TIMES -#undef ELPP_CURR_FILE_LOGGER_ID -#if defined(ELPP_DEFAULT_LOGGER) -# define ELPP_CURR_FILE_LOGGER_ID ELPP_DEFAULT_LOGGER -#else -# define ELPP_CURR_FILE_LOGGER_ID el::base::consts::kDefaultLoggerId -#endif -#undef ELPP_TRACE -#define ELPP_TRACE CLOG(TRACE, ELPP_CURR_FILE_LOGGER_ID) -// Normal logs -#define LOG(LEVEL) CLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG(vlevel) CVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Conditional logs -#define LOG_IF(condition, LEVEL) CLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG_IF(condition, vlevel) CVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Hit counts based logs -#define LOG_EVERY_N(n, LEVEL) CLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG_EVERY_N(n, vlevel) CVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#define LOG_AFTER_N(n, LEVEL) CLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG_AFTER_N(n, vlevel) CVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#define LOG_N_TIMES(n, LEVEL) CLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG_N_TIMES(n, vlevel) CVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Generic PLOG() -#undef CPLOG -#undef CPLOG_IF -#undef PLOG -#undef PLOG_IF -#undef DCPLOG -#undef DCPLOG_IF -#undef DPLOG -#undef DPLOG_IF -#define CPLOG(LEVEL, ...)\ -C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CPLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::PErrorWriter, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define DCPLOG(LEVEL, ...)\ -if (ELPP_DEBUG_LOG) C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define DCPLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::PErrorWriter, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define PLOG(LEVEL) CPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define PLOG_IF(condition, LEVEL) CPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DPLOG(LEVEL) DCPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DPLOG_IF(condition, LEVEL) DCPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -// Generic SYSLOG() -#undef CSYSLOG -#undef CSYSLOG_IF -#undef CSYSLOG_EVERY_N -#undef CSYSLOG_AFTER_N -#undef CSYSLOG_N_TIMES -#undef SYSLOG -#undef SYSLOG_IF -#undef SYSLOG_EVERY_N -#undef SYSLOG_AFTER_N -#undef SYSLOG_N_TIMES -#undef DCSYSLOG -#undef DCSYSLOG_IF -#undef DCSYSLOG_EVERY_N -#undef DCSYSLOG_AFTER_N -#undef DCSYSLOG_N_TIMES -#undef DSYSLOG -#undef DSYSLOG_IF -#undef DSYSLOG_EVERY_N -#undef DSYSLOG_AFTER_N -#undef DSYSLOG_N_TIMES -#if defined(ELPP_SYSLOG) -# define CSYSLOG(LEVEL, ...)\ -C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define CSYSLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define CSYSLOG_EVERY_N(n, LEVEL, ...) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define CSYSLOG_AFTER_N(n, LEVEL, ...) C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define CSYSLOG_N_TIMES(n, LEVEL, ...) C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define SYSLOG(LEVEL) CSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId) -# define SYSLOG_IF(condition, LEVEL) CSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId) -# define SYSLOG_EVERY_N(n, LEVEL) CSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define SYSLOG_AFTER_N(n, LEVEL) CSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define SYSLOG_N_TIMES(n, LEVEL) CSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define DCSYSLOG(LEVEL, ...) if (ELPP_DEBUG_LOG) C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DCSYSLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::Writer, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DCSYSLOG_EVERY_N(n, LEVEL, ...)\ -if (ELPP_DEBUG_LOG) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DCSYSLOG_AFTER_N(n, LEVEL, ...)\ -if (ELPP_DEBUG_LOG) C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DCSYSLOG_N_TIMES(n, LEVEL, ...)\ -if (ELPP_DEBUG_LOG) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DSYSLOG(LEVEL) DCSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId) -# define DSYSLOG_IF(condition, LEVEL) DCSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId) -# define DSYSLOG_EVERY_N(n, LEVEL) DCSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define DSYSLOG_AFTER_N(n, LEVEL) DCSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define DSYSLOG_N_TIMES(n, LEVEL) DCSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId) -#else -# define CSYSLOG(LEVEL, ...) el::base::NullWriter() -# define CSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter() -# define CSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter() -# define CSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter() -# define CSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter() -# define SYSLOG(LEVEL) el::base::NullWriter() -# define SYSLOG_IF(condition, LEVEL) el::base::NullWriter() -# define SYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter() -# define SYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter() -# define SYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter() -# define DCSYSLOG(LEVEL, ...) el::base::NullWriter() -# define DCSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter() -# define DCSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter() -# define DCSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter() -# define DCSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter() -# define DSYSLOG(LEVEL) el::base::NullWriter() -# define DSYSLOG_IF(condition, LEVEL) el::base::NullWriter() -# define DSYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter() -# define DSYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter() -# define DSYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter() -#endif // defined(ELPP_SYSLOG) -// -// Custom Debug Only Loggers - Requires (level, loggerId/s) -// -// undef existing -#undef DCLOG -#undef DCVLOG -#undef DCLOG_IF -#undef DCVLOG_IF -#undef DCLOG_EVERY_N -#undef DCVLOG_EVERY_N -#undef DCLOG_AFTER_N -#undef DCVLOG_AFTER_N -#undef DCLOG_N_TIMES -#undef DCVLOG_N_TIMES -// Normal logs -#define DCLOG(LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG(LEVEL, __VA_ARGS__) -#define DCLOG_VERBOSE(vlevel, ...) if (ELPP_DEBUG_LOG) CLOG_VERBOSE(vlevel, __VA_ARGS__) -#define DCVLOG(vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG(vlevel, __VA_ARGS__) -// Conditional logs -#define DCLOG_IF(condition, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_IF(condition, LEVEL, __VA_ARGS__) -#define DCVLOG_IF(condition, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_IF(condition, vlevel, __VA_ARGS__) -// Hit counts based logs -#define DCLOG_EVERY_N(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_EVERY_N(n, LEVEL, __VA_ARGS__) -#define DCVLOG_EVERY_N(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_EVERY_N(n, vlevel, __VA_ARGS__) -#define DCLOG_AFTER_N(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_AFTER_N(n, LEVEL, __VA_ARGS__) -#define DCVLOG_AFTER_N(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_AFTER_N(n, vlevel, __VA_ARGS__) -#define DCLOG_N_TIMES(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_N_TIMES(n, LEVEL, __VA_ARGS__) -#define DCVLOG_N_TIMES(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_N_TIMES(n, vlevel, __VA_ARGS__) -// -// Default Debug Only Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros -// -#if !defined(ELPP_NO_DEBUG_MACROS) -// undef existing -#undef DLOG -#undef DVLOG -#undef DLOG_IF -#undef DVLOG_IF -#undef DLOG_EVERY_N -#undef DVLOG_EVERY_N -#undef DLOG_AFTER_N -#undef DVLOG_AFTER_N -#undef DLOG_N_TIMES -#undef DVLOG_N_TIMES -// Normal logs -#define DLOG(LEVEL) DCLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG(vlevel) DCVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Conditional logs -#define DLOG_IF(condition, LEVEL) DCLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG_IF(condition, vlevel) DCVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Hit counts based logs -#define DLOG_EVERY_N(n, LEVEL) DCLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG_EVERY_N(n, vlevel) DCVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#define DLOG_AFTER_N(n, LEVEL) DCLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG_AFTER_N(n, vlevel) DCVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#define DLOG_N_TIMES(n, LEVEL) DCLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG_N_TIMES(n, vlevel) DCVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#endif // defined(ELPP_NO_DEBUG_MACROS) -#if !defined(ELPP_NO_CHECK_MACROS) -// Check macros -#undef CCHECK -#undef CPCHECK -#undef CCHECK_EQ -#undef CCHECK_NE -#undef CCHECK_LT -#undef CCHECK_GT -#undef CCHECK_LE -#undef CCHECK_GE -#undef CCHECK_BOUNDS -#undef CCHECK_NOTNULL -#undef CCHECK_STRCASEEQ -#undef CCHECK_STRCASENE -#undef CHECK -#undef PCHECK -#undef CHECK_EQ -#undef CHECK_NE -#undef CHECK_LT -#undef CHECK_GT -#undef CHECK_LE -#undef CHECK_GE -#undef CHECK_BOUNDS -#undef CHECK_NOTNULL -#undef CHECK_STRCASEEQ -#undef CHECK_STRCASENE -#define CCHECK(condition, ...) CLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] " -#define CPCHECK(condition, ...) CPLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] " -#define CHECK(condition) CCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) -#define PCHECK(condition) CPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) -#define CCHECK_EQ(a, b, ...) CCHECK(a == b, __VA_ARGS__) -#define CCHECK_NE(a, b, ...) CCHECK(a != b, __VA_ARGS__) -#define CCHECK_LT(a, b, ...) CCHECK(a < b, __VA_ARGS__) -#define CCHECK_GT(a, b, ...) CCHECK(a > b, __VA_ARGS__) -#define CCHECK_LE(a, b, ...) CCHECK(a <= b, __VA_ARGS__) -#define CCHECK_GE(a, b, ...) CCHECK(a >= b, __VA_ARGS__) -#define CCHECK_BOUNDS(val, min, max, ...) CCHECK(val >= min && val <= max, __VA_ARGS__) -#define CHECK_EQ(a, b) CCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_NE(a, b) CCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_LT(a, b) CCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_GT(a, b) CCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_LE(a, b) CCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_GE(a, b) CCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_BOUNDS(val, min, max) CCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID) -#define CCHECK_NOTNULL(ptr, ...) CCHECK((ptr) != nullptr, __VA_ARGS__) -#define CCHECK_STREQ(str1, str2, ...) CLOG_IF(!el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \ -<< "Check failed: [" << #str1 << " == " << #str2 << "] " -#define CCHECK_STRNE(str1, str2, ...) CLOG_IF(el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \ -<< "Check failed: [" << #str1 << " != " << #str2 << "] " -#define CCHECK_STRCASEEQ(str1, str2, ...) CLOG_IF(!el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \ -<< "Check failed: [" << #str1 << " == " << #str2 << "] " -#define CCHECK_STRCASENE(str1, str2, ...) CLOG_IF(el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \ -<< "Check failed: [" << #str1 << " != " << #str2 << "] " -#define CHECK_NOTNULL(ptr) CCHECK_NOTNULL((ptr), ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_STREQ(str1, str2) CCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_STRNE(str1, str2) CCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_STRCASEEQ(str1, str2) CCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_STRCASENE(str1, str2) CCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#undef DCCHECK -#undef DCCHECK_EQ -#undef DCCHECK_NE -#undef DCCHECK_LT -#undef DCCHECK_GT -#undef DCCHECK_LE -#undef DCCHECK_GE -#undef DCCHECK_BOUNDS -#undef DCCHECK_NOTNULL -#undef DCCHECK_STRCASEEQ -#undef DCCHECK_STRCASENE -#undef DCPCHECK -#undef DCHECK -#undef DCHECK_EQ -#undef DCHECK_NE -#undef DCHECK_LT -#undef DCHECK_GT -#undef DCHECK_LE -#undef DCHECK_GE -#undef DCHECK_BOUNDS_ -#undef DCHECK_NOTNULL -#undef DCHECK_STRCASEEQ -#undef DCHECK_STRCASENE -#undef DPCHECK -#define DCCHECK(condition, ...) if (ELPP_DEBUG_LOG) CCHECK(condition, __VA_ARGS__) -#define DCCHECK_EQ(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_EQ(a, b, __VA_ARGS__) -#define DCCHECK_NE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_NE(a, b, __VA_ARGS__) -#define DCCHECK_LT(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_LT(a, b, __VA_ARGS__) -#define DCCHECK_GT(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_GT(a, b, __VA_ARGS__) -#define DCCHECK_LE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_LE(a, b, __VA_ARGS__) -#define DCCHECK_GE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_GE(a, b, __VA_ARGS__) -#define DCCHECK_BOUNDS(val, min, max, ...) if (ELPP_DEBUG_LOG) CCHECK_BOUNDS(val, min, max, __VA_ARGS__) -#define DCCHECK_NOTNULL(ptr, ...) if (ELPP_DEBUG_LOG) CCHECK_NOTNULL((ptr), __VA_ARGS__) -#define DCCHECK_STREQ(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STREQ(str1, str2, __VA_ARGS__) -#define DCCHECK_STRNE(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRNE(str1, str2, __VA_ARGS__) -#define DCCHECK_STRCASEEQ(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRCASEEQ(str1, str2, __VA_ARGS__) -#define DCCHECK_STRCASENE(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRCASENE(str1, str2, __VA_ARGS__) -#define DCPCHECK(condition, ...) if (ELPP_DEBUG_LOG) CPCHECK(condition, __VA_ARGS__) -#define DCHECK(condition) DCCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_EQ(a, b) DCCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_NE(a, b) DCCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_LT(a, b) DCCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_GT(a, b) DCCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_LE(a, b) DCCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_GE(a, b) DCCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_BOUNDS(val, min, max) DCCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_NOTNULL(ptr) DCCHECK_NOTNULL((ptr), ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_STREQ(str1, str2) DCCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_STRNE(str1, str2) DCCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_STRCASEEQ(str1, str2) DCCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_STRCASENE(str1, str2) DCCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define DPCHECK(condition) DCPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) -#endif // defined(ELPP_NO_CHECK_MACROS) -#if defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING) -# define ELPP_USE_DEF_CRASH_HANDLER false -#else -# define ELPP_USE_DEF_CRASH_HANDLER true -#endif // defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING) -#define ELPP_CRASH_HANDLER_INIT -#define ELPP_INIT_EASYLOGGINGPP(val) \ -namespace el { \ -namespace base { \ -el::base::type::StoragePointer elStorage(val); \ -} \ -el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER); \ -} - -#if ELPP_ASYNC_LOGGING -# define INITIALIZE_EASYLOGGINGPP ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()),\ -new el::base::AsyncDispatchWorker())) -#else -# define INITIALIZE_EASYLOGGINGPP ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()))) -#endif // ELPP_ASYNC_LOGGING -#define INITIALIZE_NULL_EASYLOGGINGPP \ -namespace el {\ -namespace base {\ -el::base::type::StoragePointer elStorage;\ -}\ -el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\ -} -#define SHARE_EASYLOGGINGPP(initializedStorage)\ -namespace el {\ -namespace base {\ -el::base::type::StoragePointer elStorage(initializedStorage);\ -}\ -el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\ -} - -#if defined(ELPP_UNICODE) -# define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv); std::locale::global(std::locale("")) -#else -# define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv) -#endif // defined(ELPP_UNICODE) -#endif // EASYLOGGINGPP_H