Repository: psycha0s/airwave Branch: master Commit: e44976c37dde Files: 85 Total size: 440.3 KB Directory structure: gitextract_olx5gbux/ ├── CMakeLists.txt ├── LICENSE ├── README ├── README.md ├── cmake/ │ ├── FindLibDl.cmake │ └── FindLibMagic.cmake ├── config.h.in ├── fix-xembed-wine-windows.patch └── src/ ├── common/ │ ├── dataport.cpp │ ├── dataport.h │ ├── event.cpp │ ├── event.h │ ├── filesystem.cpp │ ├── filesystem.h │ ├── json.cpp │ ├── json.h │ ├── logger.cpp │ ├── logger.h │ ├── moduleinfo.cpp │ ├── moduleinfo.h │ ├── protocol.h │ ├── storage.cpp │ ├── storage.h │ ├── types.h │ ├── vst24.h │ ├── vsteventkeeper.cpp │ └── vsteventkeeper.h ├── host/ │ ├── CMakeLists.txt │ ├── host.cpp │ ├── host.h │ └── main.cpp ├── manager/ │ ├── CMakeLists.txt │ ├── airwave-manager.desktop.in │ ├── core/ │ │ ├── application.cpp │ │ ├── application.h │ │ ├── logsocket.cpp │ │ ├── logsocket.h │ │ ├── singleapplication.cpp │ │ └── singleapplication.h │ ├── forms/ │ │ ├── filedialog.cpp │ │ ├── filedialog.h │ │ ├── folderdialog.cpp │ │ ├── folderdialog.h │ │ ├── linkdialog.cpp │ │ ├── linkdialog.h │ │ ├── loaderdialog.cpp │ │ ├── loaderdialog.h │ │ ├── mainform.cpp │ │ ├── mainform.h │ │ ├── prefixdialog.cpp │ │ ├── prefixdialog.h │ │ ├── settingsdialog.cpp │ │ └── settingsdialog.h │ ├── main.cpp │ ├── models/ │ │ ├── directorymodel.cpp │ │ ├── directorymodel.h │ │ ├── generictreemodel.h │ │ ├── linksmodel.cpp │ │ ├── linksmodel.h │ │ ├── loadersmodel.cpp │ │ ├── loadersmodel.h │ │ ├── prefixesmodel.cpp │ │ └── prefixesmodel.h │ ├── resources/ │ │ └── resources.qrc │ └── widgets/ │ ├── directoryview.cpp │ ├── directoryview.h │ ├── generictreeview.h │ ├── lineedit.cpp │ ├── lineedit.h │ ├── linksview.cpp │ ├── linksview.h │ ├── loadersview.cpp │ ├── loadersview.h │ ├── logview.cpp │ ├── logview.h │ ├── nofocusdelegate.cpp │ ├── nofocusdelegate.h │ ├── prefixesview.cpp │ ├── prefixesview.h │ ├── separatorlabel.cpp │ └── separatorlabel.h └── plugin/ ├── CMakeLists.txt ├── main.cpp ├── plugin.cpp └── plugin.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: CMakeLists.txt ================================================ cmake_minimum_required(VERSION 2.8.11) set(PROJECT_NAME airwave) project(${PROJECT_NAME}) # Project version set(VERSION_MAJOR 1) set(VERSION_MINOR 3) set(VERSION_PATCH 3) # Set plugin shared library base name set(PLUGIN_BASENAME ${PROJECT_NAME}-plugin) # Set host binary base name set(HOST_BASENAME ${PROJECT_NAME}-host) # Set installation path set(INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX} CACHE PATH "") # Check for 64-bit platform if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(PLATFORM_64BIT 1) endif() # Generate config header configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/src/common/config.h ) # Check the build type and ask the user to set concrete one if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE RelWithDebInfo) message(WARNING "CMAKE_BUILD_TYPE is not set, forcing to RelWithDebInfo") endif() # Set compiler flags if(${CMAKE_CXX_COMPILER_ID} MATCHES "GNU" OR ${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wextra -D__WIDL_objidl_generated_name_0000000C=") set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g3") set(CMAKE_CXX_FLAGS_RELEASE "-O3") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O3 -g3") set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os") endif() # Setup path, where CMake would search for additional modules set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake ) # Configure the VST SDK path set(VSTSDK_PATH ${PROJECT_SOURCE_DIR}/VST3\ SDK CACHE PATH "Path to the Steinberg VST Audio Plugins SDK") message(STATUS "VSTSDK_PATH is set to " ${VSTSDK_PATH}) find_path(VSTSDK_INCLUDE_DIR NAMES aeffect.h aeffectx.h PATHS "${VSTSDK_PATH}/pluginterfaces/vst2.x/") if(NOT VSTSDK_INCLUDE_DIR) message(FATAL_ERROR "VST SDK is not found. You should set the VSTSDK_PATH variable " "to the directory, where your copy of the VST SDK is located.") endif() message(STATUS "VST SDK headers are found in ${VSTSDK_INCLUDE_DIR}") include_directories( ${CMAKE_CURRENT_BINARY_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src ) add_subdirectory(src/plugin) add_subdirectory(src/host) add_subdirectory(src/manager) ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Anton Kalmykov 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. ================================================ FILE: README ================================================ About Airwave is a wine based VST bridge, that allows for the use of Windows 32- and 64-bit VST 2.4 audio plugins with Linux VST hosts. Due to the use of shared memory, only one extra copying is made for each data transfer. Airwave also uses the XEMBED protocol to correctly embed the plugin editor into the host window. Requirements - wine, supporting XEMBED protocol (versions greater than 1.7.19 were tested, but earlier versions also may work) - libmagic - Qt5 for the airwave manager application (GUI) Building the source 1. Install the required packages: multilib-enabled GCC, cmake, git, wine, Qt5, libmagic. Arch Linux (x86_64) example: sudo pacman -S gcc-multilib cmake git wine qt5-base Fedora 20 (x86_64) example: sudo yum -y install gcc-c++ git cmake wine wine-devel wine-devel.i686 file file-devel libX11-devel libX11-devel.i686 qt5-devel glibc-devel.i686 glibc-devel Ubuntu 14.04 (x86_64) example: sudo apt-get install git cmake gcc-multilib g++-multilib libx11-dev libx11-dev:i386 qt5-default libmagic-dev sudo add-apt-repository ppa:ubuntu-wine/ppa sudo apt-get update sudo apt-get install wine1.7 wine1.7-dev 2. Get the VST Audio Plugins SDK from Steinberg (http://www.steinberg.net/en/company/developers.html). I cannot distribute it myself due to the license restrictions. 3. Unpack the VST SDK archive. Further I'll assume that you have unpacked it in your home directory: ${HOME}/VST3\ SDK. 4. Clone the airwave GIT repository git clone https://github.com/phantom-code/airwave.git 5. Go to the airwave source directory and execute the following commands: mkdir build && cd build cmake -DCMAKE_BUILD_TYPE="Release" -DCMAKE_INSTALL_PREFIX=/opt/airwave -DVSTSDK_PATH=${HOME}/VST3\ SDK .. make sudo make install Of course, you can change the CMAKE_INSTALL_PREFIX as you like. Usage 1. Run the airwave-manager 2. Press the "Create link" button on the toolbar. 3. Select desired wine loader and wine prefix in the appropriate combo boxes. 4. Enter a path to VST plugin DLL file in the "VST plugin" field (you can use the "Browse" button for convenience). Note, that the path is relative to the selected wine prefix. 5. Enter a "Link location" path (the directory, where your VST host looks for the plugins). 6. Enter a link name, if you don't like the auto-suggested one. 7. Select a desired log level for this link. The higher the log level, the more messages you'll receive. The 'default' log level is a special value. It corresponds to the 'Default log level' value from the settings dialog. In most cases, the 'default' log level is the right choice. For maximum performance do not use a higher level than 'trace'. 7. Press the OK button. At this point, your VST host should be able to find a new plugin inside of the "Link location" directory. Note: After you have created the link you cannot move/rename it with a file manager. All updates have to be done inside the airwave-manager. Also, you should update your links after updating the airwave itself. This could be achived by pressing the "Update links" button. Under the hood The bridge consists of four components: - Plugin endpoint (airwave-plugin-.so) - Host endpoint (airwave-host-.exe.so and airwave-host-.exe launcher script) - Configuration file (${XDG_CONFIG_PATH}/airwave/airwave.conf) - GUI configurator (airwave-manager) When the airwave-plugin is loaded by the VST host, it obtains its absolute path and use it as the key to get the linked VST DLL from the configuration. Then it starts the airwave-host process and passes the path to the linked VST file. The airwave-host loads the VST DLL and works as a fake VST host. Starting from this point, the airwave-plugin and airwave-host act together like a proxy, translating commands between the native VST host and the Windows VST plugin. Known issues - Due to a bug in wine, there is some hacking involved when embedding the editor window. There is a chance that you get a black window instead of the plugin GUI. Also some areas might not update correctly when increasing the window size. On some hosts (Bitwig Studio for example) this can be solved by closing and re-opening the plugin window. ================================================ FILE: README.md ================================================ ## About Airwave is a [wine](https://www.winehq.org/) based VST bridge, that allows for the use of Windows 32- and 64-bit VST 2.4 audio plugins with Linux VST hosts. Due to the use of shared memory, only one extra copying is made for each data transfer. Airwave also uses the XEMBED protocol to correctly embed the plugin editor into the host window. ## Requirements - wine, supporting XEMBED protocol (versions greater than 1.7.19 were tested, but earlier versions also may work). To solve the blank window issue you can apply [this patch](https://github.com/phantom-code/airwave/blob/develop/fix-xembed-wine-windows.patch) to wine. - libmagic - Qt5 for the airwave manager application (GUI) ## Building the source 1. Install the required packages: multilib-enabled GCC, cmake, git, wine, Qt5, libmagic. * **Arch Linux (x86_64)** example: ``` sudo pacman -S gcc-multilib cmake git wine qt5-base ``` * **Fedora 20 (x86_64)** example: ``` sudo yum -y install gcc-c++ git cmake wine wine-devel wine-devel.i686 file file-devel libX11-devel libX11-devel.i686 qt5-devel glibc-devel.i686 glibc-devel ``` * **Ubuntu 14.04 (x86_64)** example: ``` sudo apt-get install git cmake gcc-multilib g++-multilib libx11-dev libx11-dev:i386 qt5-default libmagic-dev sudo add-apt-repository ppa:ubuntu-wine/ppa sudo apt-get update sudo apt-get install wine1.7 wine1.7-dev ``` 2. Get the VST Audio Plugins SDK [from Steinberg](http://www.steinberg.net/en/company/developers.html). I cannot distribute it myself due to the license restrictions. 3. Unpack the VST SDK archive. Further I'll assume that you have unpacked it in your home directory: ${HOME}/VST3\ SDK. 4. Clone the airwave GIT repository ``` git clone https://github.com/phantom-code/airwave.git ``` 5. Go to the airwave source directory and execute the following commands: ``` mkdir build && cd build cmake -DCMAKE_BUILD_TYPE="Release" -DCMAKE_INSTALL_PREFIX=/opt/airwave -DVSTSDK_PATH=${HOME}/VST3\ SDK .. make sudo make install ``` Of course, you can change the CMAKE_INSTALL_PREFIX as you like. ## Usage 1. Run the airwave-manager 2. Press the "Create link" button on the toolbar. 3. Select desired wine loader and wine prefix in the appropriate combo boxes. 4. Enter a path to VST plugin DLL file in the "VST plugin" field (you can use the "Browse" button for convenience). Note, that the path is relative to the selected wine prefix. 5. Enter a "Link location" path (the directory, where your VST host looks for the plugins). 6. Enter a link name, if you don't like the auto-suggested one. 7. Select a desired log level for this link. The higher the log level, the more messages you'll receive. The 'default' log level is a special value. It corresponds to the 'Default log level' value from the settings dialog. In most cases, the 'default' log level is the right choice. For maximum performance do not use a higher level than 'trace'. 7. Press the "OK" button. At this point, your VST host should be able to find a new plugin inside of the "Link location" directory. **Note:** After you have created the link you cannot move/rename it with a file manager. All updates have to be done inside the airwave-manager. Also, you should update your links after updating the airwave itself. This could be achived by pressing the "Update links" button. ## Under the hood The bridge consists of four components: - Plugin endpoint (airwave-plugin.so) - Host endpoint (airwave-host-{arch}.exe.so and airwave-host-{arch}.exe launcher script) - Configuration file (${XDG_CONFIG_PATH}/airwave/airwave.conf) - GUI configurator (airwave-manager) When the airwave-plugin is loaded by the VST host, it obtains its absolute path and use it as the key to get the linked VST DLL from the configuration. Then it starts the airwave-host process and passes the path to the linked VST file. The airwave-host loads the VST DLL and works as a fake VST host. Starting from this point, the airwave-plugin and airwave-host act together like a proxy, translating commands between the native VST host and the Windows VST plugin. ## Known issues - Due to a bug in wine, there is some hacking involved when embedding the editor window. There is a chance that you get a black window instead of the plugin GUI. Also some areas might not update correctly when increasing the window size. You can workaround this issue by patching wine with [this patch](https://github.com/phantom-code/airwave/blob/develop/fix-xembed-wine-windows.patch). ## Compatibility The following list is not complete. It contains only plugins, that have been tested by me or by people, who sent me a report. Please note about d2d1.dll mentioned in the list: currently I know that only one version of d2d1.dll is working: version: 6.1.7601.17514 size: 827904 bytes md5 hash: 3e0a1bf9e17349a8392455845721f92f If you will get success with another version, please contact me and I will update this information. VST-Plugins | works? | Notes | ------------:|:----------:|:-------| AlgoMusic CZynthia | yes | Aly James LAB OB-Xtreme | yes | Analogic Delay by interrruptor | yes | Bionic Delay by interrruptor | yes | Blue Cat Audio Oscilloscope Multi | no | doesn't work with wine Cableguys Volume Shaper | yes | you need to install native d2d1.dll and override it in winecfg Credland Audio BigKick | yes | you need to install native d2d1.dll and override it in winecfg FabFilter plugins | yes | haven't tested them all Green Oak Software Crystal | yes | Image-Line Harmless | yes | Image-Line Sytrus | yes | LennarDigital Sylenth1 | yes | you need to override d2d1.dll in winecfg LePou Plugins | yes | LeCab2 has slight GUI redrawing issues NI Absynth | yes | NI FM8 | yes | NI Guitar Rig 5 | yes | activation doesn't work NI Kontakt 5 | mostly | up to v5.3.1, can import libraries only in Windows XP mode NI Massive | yes | only 32-bit NI Reaktor 5 | yes | Magnus Choir | yes | Martin Lüders pg8x | yes | Meesha Damatriks | yes | Odo Synths Double Six | partly | GUI issues Peavey Revalver Mark III.V | yes | ReFX Nexus2 | yes | ReFX Vanguard | yes | Reveal Sound Spire | yes | starting from 1.0.19 you need to override d2d1.dll in winecfg Sonic Academy A.N.A. | yes | Sonic Academy KICK | yes | Sonic Cat LFX-1310 | yes | Sonic Charge Cyclone | yes | Smartelectronix s(M)exoscope | yes | Spectrasonics Omnisphere | yes | Spectrasonics Omnisphere 2 | yes | May require copying STEAM dir manually to place on install. Runs too slow with many presets to be usable on a decent laptop. SQ8L by Siegfried Kullmann | yes | SuperWave P8 | yes | Synapse Audio DUNE 2 | yes | Synth1 by Ichiro Toda | yes | Tone2 FireBird | yes | Tone2 Nemesis | yes | Tone2 Saurus | yes | u-he plugins | yes | Linux version is also available Variety of Sound plugins | yes | Voxengo plugins | mostly | inter plugin routing doesn't work (architecture issue) Xfer Serum | yes | install native GDI+ (run `winetricks gdiplus`) EZDrummer2, BFD3, XLN AD2 | yes | host need multi-channel support ================================================ FILE: cmake/FindLibDl.cmake ================================================ # - Find libdl # Find the native LIBDL includes and library # # LIBDL_INCLUDE_DIR - where to find dlfcn.h, etc. # LIBDL_LIBRARIES - List of libraries when using libdl. # LIBDL_FOUND - True if libdl found. if(LIBDL_INCLUDE_DIR) # Already in cache, be silent set(LIBDL_FIND_QUIETLY TRUE) endif(LIBDL_INCLUDE_DIR) find_path(LIBDL_INCLUDE_DIR dlfcn.h) set(LIBDL_NAMES dl libdl ltdl libltdl) find_library(LIBDL_LIBRARY NAMES ${LIBDL_NAMES}) # handle the QUIETLY and REQUIRED arguments and set LIBDL_FOUND to TRUE if # all listed variables are TRUE include(FindPackageHandleStandardArgs) find_package_handle_standard_args(LibDL DEFAULT_MSG LIBDL_LIBRARY LIBDL_INCLUDE_DIR) if(LIBDL_FOUND) set(LIBDL_LIBRARIES ${LIBDL_LIBRARY}) else(LIBDL_FOUND) set(LIBDL_LIBRARIES) endif(LIBDL_FOUND) mark_as_advanced(LIBDL_LIBRARY LIBDL_INCLUDE_DIR) ================================================ FILE: cmake/FindLibMagic.cmake ================================================ # - Try to find libmagic header and library # # Usage of this module as follows: # # find_package(LibMagic) # # Variables used by this module, they can change the default behaviour and need # to be set before calling find_package: # # LIBMAGIC_ROOT_DIR Set this variable to the root installation of # libmagic if the module has problems finding the # proper installation path. # # Variables defined by this module: # # LIBMAGIC_FOUND System has libmagic, magic.h, and file # LIBMAGIC_FILE_EXE Path to the 'file' command # LIBMAGIC_VERSION Version of libmagic # LIBMAGIC_LIBRARY The libmagic library # LIBMAGIC_INCLUDE_DIR The location of magic.h find_path(LIBMAGIC_ROOT_DIR NAMES include/magic.h ) if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") # the static version of the library is preferred on OS X for the # purposes of making packages (libmagic doesn't ship w/ OS X) set(LIBMAGIC_NAMES libmagic.a magic) else () set(LIBMAGIC_NAMES magic) endif () find_file(LIBMAGIC_FILE_EXE NAMES file HINTS ${LIBMAGIC_ROOT_DIR}/bin ) find_library(LIBMAGIC_LIBRARY NAMES ${LIBMAGIC_NAMES} HINTS ${LIBMAGIC_ROOT_DIR}/lib ) find_path(LIBMAGIC_INCLUDE_DIR NAMES magic.h HINTS ${LIBMAGIC_ROOT_DIR}/include ) if (LIBMAGIC_FILE_EXE) execute_process(COMMAND "${LIBMAGIC_FILE_EXE}" --version ERROR_VARIABLE LIBMAGIC_VERSION OUTPUT_VARIABLE LIBMAGIC_VERSION) string(REGEX REPLACE "^file-([0-9.]+).*$" "\\1" LIBMAGIC_VERSION "${LIBMAGIC_VERSION}") message(STATUS "libmagic version: ${LIBMAGIC_VERSION}") else () set(LIBMAGIC_VERSION NOTFOUND) endif () include(FindPackageHandleStandardArgs) find_package_handle_standard_args(LibMagic DEFAULT_MSG LIBMAGIC_LIBRARY LIBMAGIC_INCLUDE_DIR LIBMAGIC_FILE_EXE LIBMAGIC_VERSION ) mark_as_advanced( LIBMAGIC_ROOT_DIR LIBMAGIC_FILE_EXE LIBMAGIC_VERSION LIBMAGIC_LIBRARY LIBMAGIC_INCLUDE_DIR ) ================================================ FILE: config.h.in ================================================ // This file has been generated automatically by CMake. Do not edit it manually, as all // changes will be overwritten in the future. #ifndef CORE_CONFIG_H #define CORE_CONFIG_H #define PROJECT_NAME "@PROJECT_NAME@" // Program version #define VERSION_MAJOR @VERSION_MAJOR@ #define VERSION_MINOR @VERSION_MINOR@ #define VERSION_PATCH @VERSION_PATCH@ #define VERSION_STRING "@VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@" // Various constants #cmakedefine PLATFORM_64BIT #define INSTALL_PREFIX "@INSTALL_PREFIX@" #define PLUGIN_BASENAME "@PLUGIN_BASENAME@" #define HOST_BASENAME "@HOST_BASENAME@" #endif // CORE_CONFIG_H ================================================ FILE: fix-xembed-wine-windows.patch ================================================ diff -Naurb ./wine-1.7.52/dlls/winex11.drv/event.c ./wine-1.7.52-patched/dlls/winex11.drv/event.c --- ./wine-1.7.52/dlls/winex11.drv/event.c 2015-10-02 17:20:05.000000000 +0300 +++ ./wine-1.7.52-patched/dlls/winex11.drv/event.c 2015-10-13 14:25:12.000000000 +0300 @@ -1036,7 +1036,7 @@ if (!data->mapped || data->iconic) goto done; if (data->whole_window && !data->managed) goto done; /* ignore synthetic events on foreign windows */ - if (event->send_event && !data->whole_window) goto done; + // if (event->send_event && !data->whole_window) goto done; if (data->configure_serial && (long)(data->configure_serial - event->serial) > 0) { TRACE( "win %p/%lx event %d,%d,%dx%d ignoring old serial %lu/%lu\n", diff -Naurb ./wine-1.7.52/dlls/winex11.drv/window.c ./wine-1.7.52-patched/dlls/winex11.drv/window.c --- ./wine-1.7.52/dlls/winex11.drv/window.c 2015-10-02 17:20:05.000000000 +0300 +++ ./wine-1.7.52-patched/dlls/winex11.drv/window.c 2015-10-13 15:59:29.968686454 +0300 @@ -1131,7 +1131,11 @@ if (data->surface && data->vis.visualid != default_visual.visualid) data->surface->funcs->flush( data->surface ); } - else set_xembed_flags( data, XEMBED_MAPPED ); + else { + XMapWindow( data->display, data->whole_window ); + XFlush( data->display ); + set_xembed_flags( data, XEMBED_MAPPED ); + } data->mapped = TRUE; data->iconic = (new_style & WS_MINIMIZE) != 0; ================================================ FILE: src/common/dataport.cpp ================================================ #include "dataport.h" #include #include #include #include #include "common/logger.h" namespace Airwave { DataPort::DataPort() : id_(-1), frameSize_(0), buffer_(nullptr) { } DataPort::~DataPort() { disconnect(); } bool DataPort::create(size_t frameSize) { if(!isNull()) { ERROR("Unable to create, port is already created"); return false; } size_t bufferSize = sizeof(ControlBlock) + frameSize; id_ = shmget(IPC_PRIVATE, bufferSize, S_IRUSR | S_IWUSR); if(id_ < 0) { ERROR("Unable to allocate %d bytes of shared memory", bufferSize); return false; } buffer_ = shmat(id_, nullptr, 0); if(buffer_ == reinterpret_cast(-1)) { ERROR("Unable to attach shared memory segment with id %d", id_); shmctl(id_, IPC_RMID, nullptr); id_ = -1; return false; } new (controlBlock()) ControlBlock; frameSize_ = frameSize; return true; } bool DataPort::connect(int id) { if(!isNull()) { ERROR("Unable to connect on already initialized port"); return false; } buffer_ = shmat(id, nullptr, 0); if(buffer_ == reinterpret_cast(-1)) { ERROR("Unable to attach shared memory segment with id %d", id); return false; } shmid_ds info; if(shmctl(id, IPC_STAT, &info) != 0) { ERROR("Unable to get info about shared memory segment with id %d", id); shmdt(buffer_); id_ = -1; return false; } size_t bufferSize = info.shm_segsz; frameSize_ = bufferSize - sizeof(ControlBlock); id_ = id; return true; } void DataPort::disconnect() { if(!isNull()) { if(!isConnected()) { // ControlBlock* control = controlBlock(); // sem_destroy(&control->request); // sem_destroy(&control->response); } shmdt(buffer_); shmctl(id_, IPC_RMID, nullptr); id_ = -1; buffer_ = nullptr; frameSize_ = 0; } } bool DataPort::isNull() const { return id_ < 0; } bool DataPort::isConnected() const { shmid_ds info; if(shmctl(id_, IPC_STAT, &info) != 0) { ERROR("Unable to get shared memory segment (%d) info", id_); return false; } return info.shm_nattch > 1; } int DataPort::id() const { return id_; } size_t DataPort::frameSize() const { return frameSize_; } void* DataPort::frameBuffer() { return controlBlock() + 1; } void DataPort::sendRequest() { if(!isNull()) controlBlock()->request.post(); } void DataPort::sendResponse() { if(!isNull()) controlBlock()->response.post(); } bool DataPort::waitRequest(int msecs) { return controlBlock()->request.wait(msecs); } bool DataPort::waitResponse(int msecs) { return controlBlock()->response.wait(msecs); } DataPort::ControlBlock* DataPort::controlBlock() { return static_cast(buffer_); } } // namespace Airwave ================================================ FILE: src/common/dataport.h ================================================ #ifndef COMMON_DATAPORT_H #define COMMON_DATAPORT_H #include "common/event.h" #include "common/types.h" namespace Airwave { class DataPort { public: DataPort(); ~DataPort(); bool create(size_t frameSize); bool connect(int id); void disconnect(); bool isNull() const; bool isConnected() const; int id() const; size_t frameSize() const; void* frameBuffer(); template T* frame(); void sendRequest(); void sendResponse(); bool waitRequest(int msecs = -1); bool waitResponse(int msecs = -1); private: struct ControlBlock { Event request; Event response; }; int id_; size_t frameSize_; void* buffer_; ControlBlock* controlBlock(); }; template T* DataPort::frame() { return static_cast(frameBuffer()); } } // namespace Airwave #endif // COMMON_DATAPORT_H ================================================ FILE: src/common/event.cpp ================================================ #include "event.h" #include #include #include #include #include #define futex_wait(futex, count, timeout) \ (syscall(SYS_futex, futex, FUTEX_WAIT, count, timeout, nullptr, 0) == 0) #define futex_post(futex, count) \ (syscall(SYS_futex, futex, FUTEX_WAKE, count, nullptr, nullptr, 0) == 0) Event::Event() : count_(0) { } Event::~Event() { // FIXME The current implementation is not correct as it wakes only the one waiter. futex_post(&count_, 1); } bool Event::wait(int msecs) { timespec* timeout = nullptr; timespec tm; if(msecs >= 0) { int seconds = msecs / 1000; msecs %= 1000; tm.tv_sec = seconds; tm.tv_nsec = msecs * 1000000; timeout = &tm; } while(count_ == 0) { if(!futex_wait(&count_, 0, timeout) && errno != EWOULDBLOCK) return false; } count_--; return true; } void Event::post() { count_++; futex_post(&count_, 1); } ================================================ FILE: src/common/event.h ================================================ #ifndef COMMON_EVENT_H #define COMMON_EVENT_H #include #ifdef bool #undef bool #endif class Event { public: static const int kInfinite = -1; Event(); ~Event(); bool wait(int msecs = kInfinite); void post(); private: std::atomic count_; }; #endif // COMMON_EVENT_H ================================================ FILE: src/common/filesystem.cpp ================================================ #include "filesystem.h" #include #include #include #include #include namespace Airwave { std::string FileSystem::realPath(const std::string& path) { if(!path.empty()) { std::string result; if(path[0] == '~') { struct passwd* pw = getpwuid(getuid()); result = pw->pw_dir; result += path.substr(1); } else { result = path; } char buffer[PATH_MAX]; if(realpath(result.c_str(), buffer)) return std::string(buffer); } return std::string(); } bool FileSystem::isFileExists(const std::string& path) { return access(path.c_str(), F_OK) != -1; } bool FileSystem::isDirExists(const std::string& path) { struct stat info; return stat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode); } bool FileSystem::makePath(const std::string& path) { std::size_t begin = 0; std::size_t pos; std::string dir; while(begin < path.length()) { pos = path.find('/', begin); if(pos == std::string::npos) { dir = path; pos = path.length(); } else { dir = path.substr(0, pos + 1); } if(!isDirExists(dir)) break; begin = pos + 1; } while(begin < path.length()) { pos = path.find('/', begin); if(pos == std::string::npos) { dir = path; pos = path.length(); } else { dir = path.substr(0, pos + 1); } if(!makeDir(dir)) return false; begin = pos + 1; } return true; } bool FileSystem::makeDir(const std::string& path) { mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; if(mkdir(path.c_str(), mode) != 0) return false; return true; } std::string FileSystem::fullNameFromPath(const std::string& fileName) { std::string path = getenv("PATH"); size_t begin = 0; size_t pos = begin; while(pos < path.length()) { pos = path.find(':', begin); std::string fullName = path.substr(begin, pos - begin); fullName += '/' + fileName; if(isFileExists(fullName)) return fullName; begin = pos + 1; } return fileName; } std::string FileSystem::baseName(const std::string& path) { size_t pos = path.rfind('/'); if(pos != std::string::npos) return path.substr(pos + 1); return path; } } // namespace Airwave ================================================ FILE: src/common/filesystem.h ================================================ #ifndef COMMON_FILESYSTEM_H #define COMMON_FILESYSTEM_H #include namespace Airwave { class FileSystem { public: static std::string realPath(const std::string& path); static bool isFileExists(const std::string& path); static bool isDirExists(const std::string &path); static bool makePath(const std::string& path); static bool makeDir(const std::string& path); static std::string fullNameFromPath(const std::string& fileName); static std::string baseName(const std::string& path); }; } // namespace Airwave #endif // COMMON_FILESYSTEM_H ================================================ FILE: src/common/json.cpp ================================================ /// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/). /// It is intended to be used with #include "json.h" // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: LICENSE // ////////////////////////////////////////////////////////////////////// /* The JsonCpp library's source code, including accompanying documentation, tests and demonstration applications, are licensed under the following conditions... The author (Baptiste Lepilleur) explicitly disclaims copyright in all jurisdictions which recognize such a disclaimer. In such jurisdictions, this software is released into the Public Domain. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is released under the terms of the MIT License (see below). In jurisdictions which recognize Public Domain property, the user of this software may choose to accept it either as 1) Public Domain, 2) under the conditions of the MIT License (see below), or 3) under the terms of dual Public Domain/MIT License conditions described here, as they choose. The MIT License is about as close to Public Domain as a license can get, and is described in clear, concise terms at: http://en.wikipedia.org/wiki/MIT_License The full text of the MIT License follows: ======================================================================== Copyright (c) 2007-2010 Baptiste Lepilleur 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. ======================================================================== (END LICENSE TEXT) The MIT license is compatible with both the GPL and commercial software, affording one all of the rights of Public Domain with the minor nuisance of being required to keep the above copyright notice and license text in the source code. Note also that by accepting the Public Domain "license" you can re-license your copy using whatever license you like. */ // ////////////////////////////////////////////////////////////////////// // End of content of file: LICENSE // ////////////////////////////////////////////////////////////////////// #include "json.h" #ifndef JSON_IS_AMALGAMATION #error "Compile with -I PATH_TO_JSON_DIRECTORY" #endif // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: src/lib_json/json_tool.h // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED #define LIB_JSONCPP_JSON_TOOL_H_INCLUDED /* This header provides common string manipulation support, such as UTF-8, * portable conversion from/to string... * * It is an internal header that must not be exposed. */ namespace Json { /// Converts a unicode code-point to UTF-8. static inline std::string codePointToUTF8(unsigned int cp) { std::string result; // based on description from http://en.wikipedia.org/wiki/UTF-8 if (cp <= 0x7f) { result.resize(1); result[0] = static_cast(cp); } else if (cp <= 0x7FF) { result.resize(2); result[1] = static_cast(0x80 | (0x3f & cp)); result[0] = static_cast(0xC0 | (0x1f & (cp >> 6))); } else if (cp <= 0xFFFF) { result.resize(3); result[2] = static_cast(0x80 | (0x3f & cp)); result[1] = 0x80 | static_cast((0x3f & (cp >> 6))); result[0] = 0xE0 | static_cast((0xf & (cp >> 12))); } else if (cp <= 0x10FFFF) { result.resize(4); result[3] = static_cast(0x80 | (0x3f & cp)); result[2] = static_cast(0x80 | (0x3f & (cp >> 6))); result[1] = static_cast(0x80 | (0x3f & (cp >> 12))); result[0] = static_cast(0xF0 | (0x7 & (cp >> 18))); } return result; } /// Returns true if ch is a control character (in range [0,32[). static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; } enum { /// Constant that specify the size of the buffer that must be passed to /// uintToString. uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1 }; // Defines a char buffer for use with uintToString(). typedef char UIntToStringBuffer[uintToStringBufferSize]; /** Converts an unsigned integer to string. * @param value Unsigned interger to convert to string * @param current Input/Output string buffer. * Must have at least uintToStringBufferSize chars free. */ static inline void uintToString(LargestUInt value, char*& current) { *--current = 0; do { *--current = char(value % 10) + '0'; value /= 10; } while (value != 0); } /** Change ',' to '.' everywhere in buffer. * * We had a sophisticated way, but it did not work in WinCE. * @see https://github.com/open-target-parsers/jsoncpp/pull/9 */ static inline void fixNumericLocale(char* begin, char* end) { while (begin < end) { if (*begin == ',') { *begin = '.'; } ++begin; } } } // namespace Json { #endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: src/lib_json/json_tool.h // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: src/lib_json/json_reader.cpp // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2011 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #if !defined(JSON_IS_AMALGAMATION) #include #include #include #include "json_tool.h" #endif // if !defined(JSON_IS_AMALGAMATION) #include #include #include #include #include #include #include #include #if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below #define snprintf _snprintf #endif #if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0 // Disable warning about strdup being deprecated. #pragma warning(disable : 4996) #endif static int const stackLimit_g = 1000; static int stackDepth_g = 0; // see readValue() namespace Json { #if __cplusplus >= 201103L typedef std::unique_ptr CharReaderPtr; #else typedef std::auto_ptr CharReaderPtr; #endif // Implementation of class Features // //////////////////////////////// Features::Features() : allowComments_(true), strictRoot_(false), allowDroppedNullPlaceholders_(false), allowNumericKeys_(false) {} Features Features::all() { return Features(); } Features Features::strictMode() { Features features; features.allowComments_ = false; features.strictRoot_ = true; features.allowDroppedNullPlaceholders_ = false; features.allowNumericKeys_ = false; return features; } // Implementation of class Reader // //////////////////////////////// static bool containsNewLine(Reader::Location begin, Reader::Location end) { for (; begin < end; ++begin) if (*begin == '\n' || *begin == '\r') return true; return false; } // Class Reader // ////////////////////////////////////////////////////////////////// Reader::Reader() : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(), lastValue_(), commentsBefore_(), features_(Features::all()), collectComments_() {} Reader::Reader(const Features& features) : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(), lastValue_(), commentsBefore_(), features_(features), collectComments_() { } bool Reader::parse(const std::string& document, Value& root, bool collectComments) { document_ = document; const char* begin = document_.c_str(); const char* end = begin + document_.length(); return parse(begin, end, root, collectComments); } bool Reader::parse(std::istream& sin, Value& root, bool collectComments) { // std::istream_iterator begin(sin); // std::istream_iterator end; // Those would allow streamed input from a file, if parse() were a // template function. // Since std::string is reference-counted, this at least does not // create an extra copy. std::string doc; std::getline(sin, doc, (char)EOF); return parse(doc, root, collectComments); } bool Reader::parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments) { if (!features_.allowComments_) { collectComments = false; } begin_ = beginDoc; end_ = endDoc; collectComments_ = collectComments; current_ = begin_; lastValueEnd_ = 0; lastValue_ = 0; commentsBefore_ = ""; errors_.clear(); while (!nodes_.empty()) nodes_.pop(); nodes_.push(&root); stackDepth_g = 0; // Yes, this is bad coding, but options are limited. bool successful = readValue(); Token token; skipCommentTokens(token); if (collectComments_ && !commentsBefore_.empty()) root.setComment(commentsBefore_, commentAfter); if (features_.strictRoot_) { if (!root.isArray() && !root.isObject()) { // Set error location to start of doc, ideally should be first token found // in doc token.type_ = tokenError; token.start_ = beginDoc; token.end_ = endDoc; addError( "A valid JSON document must be either an array or an object value.", token); return false; } } return successful; } bool Reader::readValue() { // This is a non-reentrant way to support a stackLimit. Terrible! // But this deprecated class has a security problem: Bad input can // cause a seg-fault. This seems like a fair, binary-compatible way // to prevent the problem. if (stackDepth_g >= stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue()."); ++stackDepth_g; Token token; skipCommentTokens(token); bool successful = true; if (collectComments_ && !commentsBefore_.empty()) { currentValue().setComment(commentsBefore_, commentBefore); commentsBefore_ = ""; } switch (token.type_) { case tokenObjectBegin: successful = readObject(token); currentValue().setOffsetLimit(current_ - begin_); break; case tokenArrayBegin: successful = readArray(token); currentValue().setOffsetLimit(current_ - begin_); break; case tokenNumber: successful = decodeNumber(token); break; case tokenString: successful = decodeString(token); break; case tokenTrue: { Value v(true); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenFalse: { Value v(false); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenNull: { Value v; currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenArraySeparator: case tokenObjectEnd: case tokenArrayEnd: if (features_.allowDroppedNullPlaceholders_) { // "Un-read" the current token and mark the current value as a null // token. current_--; Value v; currentValue().swapPayload(v); currentValue().setOffsetStart(current_ - begin_ - 1); currentValue().setOffsetLimit(current_ - begin_); break; } // Else, fall through... default: currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return addError("Syntax error: value, object or array expected.", token); } if (collectComments_) { lastValueEnd_ = current_; lastValue_ = ¤tValue(); } --stackDepth_g; return successful; } void Reader::skipCommentTokens(Token& token) { if (features_.allowComments_) { do { readToken(token); } while (token.type_ == tokenComment); } else { readToken(token); } } bool Reader::readToken(Token& token) { skipSpaces(); token.start_ = current_; Char c = getNextChar(); bool ok = true; switch (c) { case '{': token.type_ = tokenObjectBegin; break; case '}': token.type_ = tokenObjectEnd; break; case '[': token.type_ = tokenArrayBegin; break; case ']': token.type_ = tokenArrayEnd; break; case '"': token.type_ = tokenString; ok = readString(); break; case '/': token.type_ = tokenComment; ok = readComment(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': token.type_ = tokenNumber; readNumber(); break; case 't': token.type_ = tokenTrue; ok = match("rue", 3); break; case 'f': token.type_ = tokenFalse; ok = match("alse", 4); break; case 'n': token.type_ = tokenNull; ok = match("ull", 3); break; case ',': token.type_ = tokenArraySeparator; break; case ':': token.type_ = tokenMemberSeparator; break; case 0: token.type_ = tokenEndOfStream; break; default: ok = false; break; } if (!ok) token.type_ = tokenError; token.end_ = current_; return true; } void Reader::skipSpaces() { while (current_ != end_) { Char c = *current_; if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++current_; else break; } } bool Reader::match(Location pattern, int patternLength) { if (end_ - current_ < patternLength) return false; int index = patternLength; while (index--) if (current_[index] != pattern[index]) return false; current_ += patternLength; return true; } bool Reader::readComment() { Location commentBegin = current_ - 1; Char c = getNextChar(); bool successful = false; if (c == '*') successful = readCStyleComment(); else if (c == '/') successful = readCppStyleComment(); if (!successful) return false; if (collectComments_) { CommentPlacement placement = commentBefore; if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) { if (c != '*' || !containsNewLine(commentBegin, current_)) placement = commentAfterOnSameLine; } addComment(commentBegin, current_, placement); } return true; } static std::string normalizeEOL(Reader::Location begin, Reader::Location end) { std::string normalized; normalized.reserve(end - begin); Reader::Location current = begin; while (current != end) { char c = *current++; if (c == '\r') { if (current != end && *current == '\n') // convert dos EOL ++current; // convert Mac EOL normalized += '\n'; } else { normalized += c; } } return normalized; } void Reader::addComment(Location begin, Location end, CommentPlacement placement) { assert(collectComments_); const std::string& normalized = normalizeEOL(begin, end); if (placement == commentAfterOnSameLine) { assert(lastValue_ != 0); lastValue_->setComment(normalized, placement); } else { commentsBefore_ += normalized; } } bool Reader::readCStyleComment() { while (current_ != end_) { Char c = getNextChar(); if (c == '*' && *current_ == '/') break; } return getNextChar() == '/'; } bool Reader::readCppStyleComment() { while (current_ != end_) { Char c = getNextChar(); if (c == '\n') break; if (c == '\r') { // Consume DOS EOL. It will be normalized in addComment. if (current_ != end_ && *current_ == '\n') getNextChar(); // Break on Moc OS 9 EOL. break; } } return true; } void Reader::readNumber() { const char *p = current_; char c = '0'; // stopgap for already consumed character // integral part while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : 0; // fractional part if (c == '.') { c = (current_ = p) < end_ ? *p++ : 0; while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : 0; } // exponential part if (c == 'e' || c == 'E') { c = (current_ = p) < end_ ? *p++ : 0; if (c == '+' || c == '-') c = (current_ = p) < end_ ? *p++ : 0; while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : 0; } } bool Reader::readString() { Char c = 0; while (current_ != end_) { c = getNextChar(); if (c == '\\') getNextChar(); else if (c == '"') break; } return c == '"'; } bool Reader::readObject(Token& tokenStart) { Token tokenName; std::string name; Value init(objectValue); currentValue().swapPayload(init); currentValue().setOffsetStart(tokenStart.start_ - begin_); while (readToken(tokenName)) { bool initialTokenOk = true; while (tokenName.type_ == tokenComment && initialTokenOk) initialTokenOk = readToken(tokenName); if (!initialTokenOk) break; if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object return true; name = ""; if (tokenName.type_ == tokenString) { if (!decodeString(tokenName, name)) return recoverFromError(tokenObjectEnd); } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) { Value numberName; if (!decodeNumber(tokenName, numberName)) return recoverFromError(tokenObjectEnd); name = numberName.asString(); } else { break; } Token colon; if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { return addErrorAndRecover( "Missing ':' after object member name", colon, tokenObjectEnd); } Value& value = currentValue()[name]; nodes_.push(&value); bool ok = readValue(); nodes_.pop(); if (!ok) // error already set return recoverFromError(tokenObjectEnd); Token comma; if (!readToken(comma) || (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment)) { return addErrorAndRecover( "Missing ',' or '}' in object declaration", comma, tokenObjectEnd); } bool finalizeTokenOk = true; while (comma.type_ == tokenComment && finalizeTokenOk) finalizeTokenOk = readToken(comma); if (comma.type_ == tokenObjectEnd) return true; } return addErrorAndRecover( "Missing '}' or object member name", tokenName, tokenObjectEnd); } bool Reader::readArray(Token& tokenStart) { Value init(arrayValue); currentValue().swapPayload(init); currentValue().setOffsetStart(tokenStart.start_ - begin_); skipSpaces(); if (*current_ == ']') // empty array { Token endArray; readToken(endArray); return true; } int index = 0; for (;;) { Value& value = currentValue()[index++]; nodes_.push(&value); bool ok = readValue(); nodes_.pop(); if (!ok) // error already set return recoverFromError(tokenArrayEnd); Token token; // Accept Comment after last item in the array. ok = readToken(token); while (token.type_ == tokenComment && ok) { ok = readToken(token); } bool badTokenType = (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd); if (!ok || badTokenType) { return addErrorAndRecover( "Missing ',' or ']' in array declaration", token, tokenArrayEnd); } if (token.type_ == tokenArrayEnd) break; } return true; } bool Reader::decodeNumber(Token& token) { Value decoded; if (!decodeNumber(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool Reader::decodeNumber(Token& token, Value& decoded) { // Attempts to parse the number as an integer. If the number is // larger than the maximum supported value of an integer then // we decode the number as a double. Location current = token.start_; bool isNegative = *current == '-'; if (isNegative) ++current; // TODO: Help the compiler do the div and mod at compile time or get rid of them. Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(-Value::minLargestInt) : Value::maxLargestUInt; Value::LargestUInt threshold = maxIntegerValue / 10; Value::LargestUInt value = 0; while (current < token.end_) { Char c = *current++; if (c < '0' || c > '9') return decodeDouble(token, decoded); Value::UInt digit(c - '0'); if (value >= threshold) { // We've hit or exceeded the max value divided by 10 (rounded down). If // a) we've only just touched the limit, b) this is the last digit, and // c) it's small enough to fit in that rounding delta, we're okay. // Otherwise treat this number as a double to avoid overflow. if (value > threshold || current != token.end_ || digit > maxIntegerValue % 10) { return decodeDouble(token, decoded); } } value = value * 10 + digit; } if (isNegative) decoded = -Value::LargestInt(value); else if (value <= Value::LargestUInt(Value::maxInt)) decoded = Value::LargestInt(value); else decoded = value; return true; } bool Reader::decodeDouble(Token& token) { Value decoded; if (!decodeDouble(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool Reader::decodeDouble(Token& token, Value& decoded) { double value = 0; const int bufferSize = 32; int count; int length = int(token.end_ - token.start_); // Sanity check to avoid buffer overflow exploits. if (length < 0) { return addError("Unable to parse token length", token); } // Avoid using a string constant for the format control string given to // sscanf, as this can cause hard to debug crashes on OS X. See here for more // info: // // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html char format[] = "%lf"; if (length <= bufferSize) { Char buffer[bufferSize + 1]; memcpy(buffer, token.start_, length); buffer[length] = 0; count = sscanf(buffer, format, &value); } else { std::string buffer(token.start_, token.end_); count = sscanf(buffer.c_str(), format, &value); } if (count != 1) return addError("'" + std::string(token.start_, token.end_) + "' is not a number.", token); decoded = value; return true; } bool Reader::decodeString(Token& token) { std::string decoded_string; if (!decodeString(token, decoded_string)) return false; Value decoded(decoded_string); currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool Reader::decodeString(Token& token, std::string& decoded) { decoded.reserve(token.end_ - token.start_ - 2); Location current = token.start_ + 1; // skip '"' Location end = token.end_ - 1; // do not include '"' while (current != end) { Char c = *current++; if (c == '"') break; else if (c == '\\') { if (current == end) return addError("Empty escape sequence in string", token, current); Char escape = *current++; switch (escape) { case '"': decoded += '"'; break; case '/': decoded += '/'; break; case '\\': decoded += '\\'; break; case 'b': decoded += '\b'; break; case 'f': decoded += '\f'; break; case 'n': decoded += '\n'; break; case 'r': decoded += '\r'; break; case 't': decoded += '\t'; break; case 'u': { unsigned int unicode; if (!decodeUnicodeCodePoint(token, current, end, unicode)) return false; decoded += codePointToUTF8(unicode); } break; default: return addError("Bad escape sequence in string", token, current); } } else { decoded += c; } } return true; } bool Reader::decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode) { if (!decodeUnicodeEscapeSequence(token, current, end, unicode)) return false; if (unicode >= 0xD800 && unicode <= 0xDBFF) { // surrogate pairs if (end - current < 6) return addError( "additional six characters expected to parse unicode surrogate pair.", token, current); unsigned int surrogatePair; if (*(current++) == '\\' && *(current++) == 'u') { if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) { unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); } else return false; } else return addError("expecting another \\u token to begin the second half of " "a unicode surrogate pair", token, current); } return true; } bool Reader::decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode) { if (end - current < 4) return addError( "Bad unicode escape sequence in string: four digits expected.", token, current); unicode = 0; for (int index = 0; index < 4; ++index) { Char c = *current++; unicode *= 16; if (c >= '0' && c <= '9') unicode += c - '0'; else if (c >= 'a' && c <= 'f') unicode += c - 'a' + 10; else if (c >= 'A' && c <= 'F') unicode += c - 'A' + 10; else return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current); } return true; } bool Reader::addError(const std::string& message, Token& token, Location extra) { ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = extra; errors_.push_back(info); return false; } bool Reader::recoverFromError(TokenType skipUntilToken) { int errorCount = int(errors_.size()); Token skip; for (;;) { if (!readToken(skip)) errors_.resize(errorCount); // discard errors caused by recovery if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream) break; } errors_.resize(errorCount); return false; } bool Reader::addErrorAndRecover(const std::string& message, Token& token, TokenType skipUntilToken) { addError(message, token); return recoverFromError(skipUntilToken); } Value& Reader::currentValue() { return *(nodes_.top()); } Reader::Char Reader::getNextChar() { if (current_ == end_) return 0; return *current_++; } void Reader::getLocationLineAndColumn(Location location, int& line, int& column) const { Location current = begin_; Location lastLineStart = current; line = 0; while (current < location && current != end_) { Char c = *current++; if (c == '\r') { if (*current == '\n') ++current; lastLineStart = current; ++line; } else if (c == '\n') { lastLineStart = current; ++line; } } // column & line start at 1 column = int(location - lastLineStart) + 1; ++line; } std::string Reader::getLocationLineAndColumn(Location location) const { int line, column; getLocationLineAndColumn(location, line, column); char buffer[18 + 16 + 16 + 1]; #if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) #if defined(WINCE) _snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column); #else sprintf_s(buffer, sizeof(buffer), "Line %d, Column %d", line, column); #endif #else snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column); #endif return buffer; } // Deprecated. Preserved for backward compatibility std::string Reader::getFormatedErrorMessages() const { return getFormattedErrorMessages(); } std::string Reader::getFormattedErrorMessages() const { std::string formattedMessage; for (Errors::const_iterator itError = errors_.begin(); itError != errors_.end(); ++itError) { const ErrorInfo& error = *itError; formattedMessage += "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; formattedMessage += " " + error.message_ + "\n"; if (error.extra_) formattedMessage += "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n"; } return formattedMessage; } std::vector Reader::getStructuredErrors() const { std::vector allErrors; for (Errors::const_iterator itError = errors_.begin(); itError != errors_.end(); ++itError) { const ErrorInfo& error = *itError; Reader::StructuredError structured; structured.offset_start = error.token_.start_ - begin_; structured.offset_limit = error.token_.end_ - begin_; structured.message = error.message_; allErrors.push_back(structured); } return allErrors; } bool Reader::pushError(const Value& value, const std::string& message) { size_t length = end_ - begin_; if(value.getOffsetStart() > length || value.getOffsetLimit() > length) return false; Token token; token.type_ = tokenError; token.start_ = begin_ + value.getOffsetStart(); token.end_ = end_ + value.getOffsetLimit(); ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = 0; errors_.push_back(info); return true; } bool Reader::pushError(const Value& value, const std::string& message, const Value& extra) { size_t length = end_ - begin_; if(value.getOffsetStart() > length || value.getOffsetLimit() > length || extra.getOffsetLimit() > length) return false; Token token; token.type_ = tokenError; token.start_ = begin_ + value.getOffsetStart(); token.end_ = begin_ + value.getOffsetLimit(); ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = begin_ + extra.getOffsetStart(); errors_.push_back(info); return true; } bool Reader::good() const { return !errors_.size(); } // exact copy of Features class OurFeatures { public: static OurFeatures all(); OurFeatures(); bool allowComments_; bool strictRoot_; bool allowDroppedNullPlaceholders_; bool allowNumericKeys_; bool allowSingleQuotes_; bool failIfExtra_; bool rejectDupKeys_; int stackLimit_; }; // OurFeatures // exact copy of Implementation of class Features // //////////////////////////////// OurFeatures::OurFeatures() : allowComments_(true), strictRoot_(false) , allowDroppedNullPlaceholders_(false), allowNumericKeys_(false) , allowSingleQuotes_(false) , failIfExtra_(false) { } OurFeatures OurFeatures::all() { return OurFeatures(); } // Implementation of class Reader // //////////////////////////////// // exact copy of Reader, renamed to OurReader class OurReader { public: typedef char Char; typedef const Char* Location; struct StructuredError { size_t offset_start; size_t offset_limit; std::string message; }; OurReader(OurFeatures const& features); bool parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments = true); std::string getFormattedErrorMessages() const; std::vector getStructuredErrors() const; bool pushError(const Value& value, const std::string& message); bool pushError(const Value& value, const std::string& message, const Value& extra); bool good() const; private: OurReader(OurReader const&); // no impl void operator=(OurReader const&); // no impl enum TokenType { tokenEndOfStream = 0, tokenObjectBegin, tokenObjectEnd, tokenArrayBegin, tokenArrayEnd, tokenString, tokenNumber, tokenTrue, tokenFalse, tokenNull, tokenArraySeparator, tokenMemberSeparator, tokenComment, tokenError }; class Token { public: TokenType type_; Location start_; Location end_; }; class ErrorInfo { public: Token token_; std::string message_; Location extra_; }; typedef std::deque Errors; bool readToken(Token& token); void skipSpaces(); bool match(Location pattern, int patternLength); bool readComment(); bool readCStyleComment(); bool readCppStyleComment(); bool readString(); bool readStringSingleQuote(); void readNumber(); bool readValue(); bool readObject(Token& token); bool readArray(Token& token); bool decodeNumber(Token& token); bool decodeNumber(Token& token, Value& decoded); bool decodeString(Token& token); bool decodeString(Token& token, std::string& decoded); bool decodeDouble(Token& token); bool decodeDouble(Token& token, Value& decoded); bool decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode); bool decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode); bool addError(const std::string& message, Token& token, Location extra = 0); bool recoverFromError(TokenType skipUntilToken); bool addErrorAndRecover(const std::string& message, Token& token, TokenType skipUntilToken); void skipUntilSpace(); Value& currentValue(); Char getNextChar(); void getLocationLineAndColumn(Location location, int& line, int& column) const; std::string getLocationLineAndColumn(Location location) const; void addComment(Location begin, Location end, CommentPlacement placement); void skipCommentTokens(Token& token); typedef std::stack Nodes; Nodes nodes_; Errors errors_; std::string document_; Location begin_; Location end_; Location current_; Location lastValueEnd_; Value* lastValue_; std::string commentsBefore_; int stackDepth_; OurFeatures const features_; bool collectComments_; }; // OurReader // complete copy of Read impl, for OurReader OurReader::OurReader(OurFeatures const& features) : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(), lastValue_(), commentsBefore_(), features_(features), collectComments_() { } bool OurReader::parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments) { if (!features_.allowComments_) { collectComments = false; } begin_ = beginDoc; end_ = endDoc; collectComments_ = collectComments; current_ = begin_; lastValueEnd_ = 0; lastValue_ = 0; commentsBefore_ = ""; errors_.clear(); while (!nodes_.empty()) nodes_.pop(); nodes_.push(&root); stackDepth_ = 0; bool successful = readValue(); Token token; skipCommentTokens(token); if (features_.failIfExtra_) { if (token.type_ != tokenError && token.type_ != tokenEndOfStream) { addError("Extra non-whitespace after JSON value.", token); return false; } } if (collectComments_ && !commentsBefore_.empty()) root.setComment(commentsBefore_, commentAfter); if (features_.strictRoot_) { if (!root.isArray() && !root.isObject()) { // Set error location to start of doc, ideally should be first token found // in doc token.type_ = tokenError; token.start_ = beginDoc; token.end_ = endDoc; addError( "A valid JSON document must be either an array or an object value.", token); return false; } } return successful; } bool OurReader::readValue() { if (stackDepth_ >= features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue()."); ++stackDepth_; Token token; skipCommentTokens(token); bool successful = true; if (collectComments_ && !commentsBefore_.empty()) { currentValue().setComment(commentsBefore_, commentBefore); commentsBefore_ = ""; } switch (token.type_) { case tokenObjectBegin: successful = readObject(token); currentValue().setOffsetLimit(current_ - begin_); break; case tokenArrayBegin: successful = readArray(token); currentValue().setOffsetLimit(current_ - begin_); break; case tokenNumber: successful = decodeNumber(token); break; case tokenString: successful = decodeString(token); break; case tokenTrue: { Value v(true); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenFalse: { Value v(false); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenNull: { Value v; currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenArraySeparator: case tokenObjectEnd: case tokenArrayEnd: if (features_.allowDroppedNullPlaceholders_) { // "Un-read" the current token and mark the current value as a null // token. current_--; Value v; currentValue().swapPayload(v); currentValue().setOffsetStart(current_ - begin_ - 1); currentValue().setOffsetLimit(current_ - begin_); break; } // else, fall through ... default: currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return addError("Syntax error: value, object or array expected.", token); } if (collectComments_) { lastValueEnd_ = current_; lastValue_ = ¤tValue(); } --stackDepth_; return successful; } void OurReader::skipCommentTokens(Token& token) { if (features_.allowComments_) { do { readToken(token); } while (token.type_ == tokenComment); } else { readToken(token); } } bool OurReader::readToken(Token& token) { skipSpaces(); token.start_ = current_; Char c = getNextChar(); bool ok = true; switch (c) { case '{': token.type_ = tokenObjectBegin; break; case '}': token.type_ = tokenObjectEnd; break; case '[': token.type_ = tokenArrayBegin; break; case ']': token.type_ = tokenArrayEnd; break; case '"': token.type_ = tokenString; ok = readString(); break; case '\'': if (features_.allowSingleQuotes_) { token.type_ = tokenString; ok = readStringSingleQuote(); break; } // else continue case '/': token.type_ = tokenComment; ok = readComment(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': token.type_ = tokenNumber; readNumber(); break; case 't': token.type_ = tokenTrue; ok = match("rue", 3); break; case 'f': token.type_ = tokenFalse; ok = match("alse", 4); break; case 'n': token.type_ = tokenNull; ok = match("ull", 3); break; case ',': token.type_ = tokenArraySeparator; break; case ':': token.type_ = tokenMemberSeparator; break; case 0: token.type_ = tokenEndOfStream; break; default: ok = false; break; } if (!ok) token.type_ = tokenError; token.end_ = current_; return true; } void OurReader::skipSpaces() { while (current_ != end_) { Char c = *current_; if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++current_; else break; } } bool OurReader::match(Location pattern, int patternLength) { if (end_ - current_ < patternLength) return false; int index = patternLength; while (index--) if (current_[index] != pattern[index]) return false; current_ += patternLength; return true; } bool OurReader::readComment() { Location commentBegin = current_ - 1; Char c = getNextChar(); bool successful = false; if (c == '*') successful = readCStyleComment(); else if (c == '/') successful = readCppStyleComment(); if (!successful) return false; if (collectComments_) { CommentPlacement placement = commentBefore; if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) { if (c != '*' || !containsNewLine(commentBegin, current_)) placement = commentAfterOnSameLine; } addComment(commentBegin, current_, placement); } return true; } void OurReader::addComment(Location begin, Location end, CommentPlacement placement) { assert(collectComments_); const std::string& normalized = normalizeEOL(begin, end); if (placement == commentAfterOnSameLine) { assert(lastValue_ != 0); lastValue_->setComment(normalized, placement); } else { commentsBefore_ += normalized; } } bool OurReader::readCStyleComment() { while (current_ != end_) { Char c = getNextChar(); if (c == '*' && *current_ == '/') break; } return getNextChar() == '/'; } bool OurReader::readCppStyleComment() { while (current_ != end_) { Char c = getNextChar(); if (c == '\n') break; if (c == '\r') { // Consume DOS EOL. It will be normalized in addComment. if (current_ != end_ && *current_ == '\n') getNextChar(); // Break on Moc OS 9 EOL. break; } } return true; } void OurReader::readNumber() { const char *p = current_; char c = '0'; // stopgap for already consumed character // integral part while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : 0; // fractional part if (c == '.') { c = (current_ = p) < end_ ? *p++ : 0; while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : 0; } // exponential part if (c == 'e' || c == 'E') { c = (current_ = p) < end_ ? *p++ : 0; if (c == '+' || c == '-') c = (current_ = p) < end_ ? *p++ : 0; while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : 0; } } bool OurReader::readString() { Char c = 0; while (current_ != end_) { c = getNextChar(); if (c == '\\') getNextChar(); else if (c == '"') break; } return c == '"'; } bool OurReader::readStringSingleQuote() { Char c = 0; while (current_ != end_) { c = getNextChar(); if (c == '\\') getNextChar(); else if (c == '\'') break; } return c == '\''; } bool OurReader::readObject(Token& tokenStart) { Token tokenName; std::string name; Value init(objectValue); currentValue().swapPayload(init); currentValue().setOffsetStart(tokenStart.start_ - begin_); while (readToken(tokenName)) { bool initialTokenOk = true; while (tokenName.type_ == tokenComment && initialTokenOk) initialTokenOk = readToken(tokenName); if (!initialTokenOk) break; if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object return true; name = ""; if (tokenName.type_ == tokenString) { if (!decodeString(tokenName, name)) return recoverFromError(tokenObjectEnd); } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) { Value numberName; if (!decodeNumber(tokenName, numberName)) return recoverFromError(tokenObjectEnd); name = numberName.asString(); } else { break; } Token colon; if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { return addErrorAndRecover( "Missing ':' after object member name", colon, tokenObjectEnd); } if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30"); if (features_.rejectDupKeys_ && currentValue().isMember(name)) { std::string msg = "Duplicate key: '" + name + "'"; return addErrorAndRecover( msg, tokenName, tokenObjectEnd); } Value& value = currentValue()[name]; nodes_.push(&value); bool ok = readValue(); nodes_.pop(); if (!ok) // error already set return recoverFromError(tokenObjectEnd); Token comma; if (!readToken(comma) || (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment)) { return addErrorAndRecover( "Missing ',' or '}' in object declaration", comma, tokenObjectEnd); } bool finalizeTokenOk = true; while (comma.type_ == tokenComment && finalizeTokenOk) finalizeTokenOk = readToken(comma); if (comma.type_ == tokenObjectEnd) return true; } return addErrorAndRecover( "Missing '}' or object member name", tokenName, tokenObjectEnd); } bool OurReader::readArray(Token& tokenStart) { Value init(arrayValue); currentValue().swapPayload(init); currentValue().setOffsetStart(tokenStart.start_ - begin_); skipSpaces(); if (*current_ == ']') // empty array { Token endArray; readToken(endArray); return true; } int index = 0; for (;;) { Value& value = currentValue()[index++]; nodes_.push(&value); bool ok = readValue(); nodes_.pop(); if (!ok) // error already set return recoverFromError(tokenArrayEnd); Token token; // Accept Comment after last item in the array. ok = readToken(token); while (token.type_ == tokenComment && ok) { ok = readToken(token); } bool badTokenType = (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd); if (!ok || badTokenType) { return addErrorAndRecover( "Missing ',' or ']' in array declaration", token, tokenArrayEnd); } if (token.type_ == tokenArrayEnd) break; } return true; } bool OurReader::decodeNumber(Token& token) { Value decoded; if (!decodeNumber(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool OurReader::decodeNumber(Token& token, Value& decoded) { // Attempts to parse the number as an integer. If the number is // larger than the maximum supported value of an integer then // we decode the number as a double. Location current = token.start_; bool isNegative = *current == '-'; if (isNegative) ++current; // TODO: Help the compiler do the div and mod at compile time or get rid of them. Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(-Value::minLargestInt) : Value::maxLargestUInt; Value::LargestUInt threshold = maxIntegerValue / 10; Value::LargestUInt value = 0; while (current < token.end_) { Char c = *current++; if (c < '0' || c > '9') return decodeDouble(token, decoded); Value::UInt digit(c - '0'); if (value >= threshold) { // We've hit or exceeded the max value divided by 10 (rounded down). If // a) we've only just touched the limit, b) this is the last digit, and // c) it's small enough to fit in that rounding delta, we're okay. // Otherwise treat this number as a double to avoid overflow. if (value > threshold || current != token.end_ || digit > maxIntegerValue % 10) { return decodeDouble(token, decoded); } } value = value * 10 + digit; } if (isNegative) decoded = -Value::LargestInt(value); else if (value <= Value::LargestUInt(Value::maxInt)) decoded = Value::LargestInt(value); else decoded = value; return true; } bool OurReader::decodeDouble(Token& token) { Value decoded; if (!decodeDouble(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool OurReader::decodeDouble(Token& token, Value& decoded) { double value = 0; const int bufferSize = 32; int count; int length = int(token.end_ - token.start_); // Sanity check to avoid buffer overflow exploits. if (length < 0) { return addError("Unable to parse token length", token); } // Avoid using a string constant for the format control string given to // sscanf, as this can cause hard to debug crashes on OS X. See here for more // info: // // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html char format[] = "%lf"; if (length <= bufferSize) { Char buffer[bufferSize + 1]; memcpy(buffer, token.start_, length); buffer[length] = 0; count = sscanf(buffer, format, &value); } else { std::string buffer(token.start_, token.end_); count = sscanf(buffer.c_str(), format, &value); } if (count != 1) return addError("'" + std::string(token.start_, token.end_) + "' is not a number.", token); decoded = value; return true; } bool OurReader::decodeString(Token& token) { std::string decoded_string; if (!decodeString(token, decoded_string)) return false; Value decoded(decoded_string); currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool OurReader::decodeString(Token& token, std::string& decoded) { decoded.reserve(token.end_ - token.start_ - 2); Location current = token.start_ + 1; // skip '"' Location end = token.end_ - 1; // do not include '"' while (current != end) { Char c = *current++; if (c == '"') break; else if (c == '\\') { if (current == end) return addError("Empty escape sequence in string", token, current); Char escape = *current++; switch (escape) { case '"': decoded += '"'; break; case '/': decoded += '/'; break; case '\\': decoded += '\\'; break; case 'b': decoded += '\b'; break; case 'f': decoded += '\f'; break; case 'n': decoded += '\n'; break; case 'r': decoded += '\r'; break; case 't': decoded += '\t'; break; case 'u': { unsigned int unicode; if (!decodeUnicodeCodePoint(token, current, end, unicode)) return false; decoded += codePointToUTF8(unicode); } break; default: return addError("Bad escape sequence in string", token, current); } } else { decoded += c; } } return true; } bool OurReader::decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode) { if (!decodeUnicodeEscapeSequence(token, current, end, unicode)) return false; if (unicode >= 0xD800 && unicode <= 0xDBFF) { // surrogate pairs if (end - current < 6) return addError( "additional six characters expected to parse unicode surrogate pair.", token, current); unsigned int surrogatePair; if (*(current++) == '\\' && *(current++) == 'u') { if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) { unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); } else return false; } else return addError("expecting another \\u token to begin the second half of " "a unicode surrogate pair", token, current); } return true; } bool OurReader::decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode) { if (end - current < 4) return addError( "Bad unicode escape sequence in string: four digits expected.", token, current); unicode = 0; for (int index = 0; index < 4; ++index) { Char c = *current++; unicode *= 16; if (c >= '0' && c <= '9') unicode += c - '0'; else if (c >= 'a' && c <= 'f') unicode += c - 'a' + 10; else if (c >= 'A' && c <= 'F') unicode += c - 'A' + 10; else return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current); } return true; } bool OurReader::addError(const std::string& message, Token& token, Location extra) { ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = extra; errors_.push_back(info); return false; } bool OurReader::recoverFromError(TokenType skipUntilToken) { int errorCount = int(errors_.size()); Token skip; for (;;) { if (!readToken(skip)) errors_.resize(errorCount); // discard errors caused by recovery if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream) break; } errors_.resize(errorCount); return false; } bool OurReader::addErrorAndRecover(const std::string& message, Token& token, TokenType skipUntilToken) { addError(message, token); return recoverFromError(skipUntilToken); } Value& OurReader::currentValue() { return *(nodes_.top()); } OurReader::Char OurReader::getNextChar() { if (current_ == end_) return 0; return *current_++; } void OurReader::getLocationLineAndColumn(Location location, int& line, int& column) const { Location current = begin_; Location lastLineStart = current; line = 0; while (current < location && current != end_) { Char c = *current++; if (c == '\r') { if (*current == '\n') ++current; lastLineStart = current; ++line; } else if (c == '\n') { lastLineStart = current; ++line; } } // column & line start at 1 column = int(location - lastLineStart) + 1; ++line; } std::string OurReader::getLocationLineAndColumn(Location location) const { int line, column; getLocationLineAndColumn(location, line, column); char buffer[18 + 16 + 16 + 1]; #if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) #if defined(WINCE) _snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column); #else sprintf_s(buffer, sizeof(buffer), "Line %d, Column %d", line, column); #endif #else snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column); #endif return buffer; } std::string OurReader::getFormattedErrorMessages() const { std::string formattedMessage; for (Errors::const_iterator itError = errors_.begin(); itError != errors_.end(); ++itError) { const ErrorInfo& error = *itError; formattedMessage += "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; formattedMessage += " " + error.message_ + "\n"; if (error.extra_) formattedMessage += "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n"; } return formattedMessage; } std::vector OurReader::getStructuredErrors() const { std::vector allErrors; for (Errors::const_iterator itError = errors_.begin(); itError != errors_.end(); ++itError) { const ErrorInfo& error = *itError; OurReader::StructuredError structured; structured.offset_start = error.token_.start_ - begin_; structured.offset_limit = error.token_.end_ - begin_; structured.message = error.message_; allErrors.push_back(structured); } return allErrors; } bool OurReader::pushError(const Value& value, const std::string& message) { size_t length = end_ - begin_; if(value.getOffsetStart() > length || value.getOffsetLimit() > length) return false; Token token; token.type_ = tokenError; token.start_ = begin_ + value.getOffsetStart(); token.end_ = end_ + value.getOffsetLimit(); ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = 0; errors_.push_back(info); return true; } bool OurReader::pushError(const Value& value, const std::string& message, const Value& extra) { size_t length = end_ - begin_; if(value.getOffsetStart() > length || value.getOffsetLimit() > length || extra.getOffsetLimit() > length) return false; Token token; token.type_ = tokenError; token.start_ = begin_ + value.getOffsetStart(); token.end_ = begin_ + value.getOffsetLimit(); ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = begin_ + extra.getOffsetStart(); errors_.push_back(info); return true; } bool OurReader::good() const { return !errors_.size(); } class OurCharReader : public CharReader { bool const collectComments_; OurReader reader_; public: OurCharReader( bool collectComments, OurFeatures const& features) : collectComments_(collectComments) , reader_(features) {} virtual bool parse( char const* beginDoc, char const* endDoc, Value* root, std::string* errs) { bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_); if (errs) { *errs = reader_.getFormattedErrorMessages(); } return ok; } }; CharReaderBuilder::CharReaderBuilder() { setDefaults(&settings_); } CharReaderBuilder::~CharReaderBuilder() {} CharReader* CharReaderBuilder::newCharReader() const { bool collectComments = settings_["collectComments"].asBool(); OurFeatures features = OurFeatures::all(); features.allowComments_ = settings_["allowComments"].asBool(); features.strictRoot_ = settings_["strictRoot"].asBool(); features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool(); features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool(); features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool(); features.stackLimit_ = settings_["stackLimit"].asInt(); features.failIfExtra_ = settings_["failIfExtra"].asBool(); features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool(); return new OurCharReader(collectComments, features); } static void getValidReaderKeys(std::set* valid_keys) { valid_keys->clear(); valid_keys->insert("collectComments"); valid_keys->insert("allowComments"); valid_keys->insert("strictRoot"); valid_keys->insert("allowDroppedNullPlaceholders"); valid_keys->insert("allowNumericKeys"); valid_keys->insert("allowSingleQuotes"); valid_keys->insert("stackLimit"); valid_keys->insert("failIfExtra"); valid_keys->insert("rejectDupKeys"); } bool CharReaderBuilder::validate(Json::Value* invalid) const { Json::Value my_invalid; if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL Json::Value& inv = *invalid; std::set valid_keys; getValidReaderKeys(&valid_keys); Value::Members keys = settings_.getMemberNames(); size_t n = keys.size(); for (size_t i = 0; i < n; ++i) { std::string const& key = keys[i]; if (valid_keys.find(key) == valid_keys.end()) { inv[key] = settings_[key]; } } return 0u == inv.size(); } Value& CharReaderBuilder::operator[](std::string key) { return settings_[key]; } // static void CharReaderBuilder::strictMode(Json::Value* settings) { //! [CharReaderBuilderStrictMode] (*settings)["allowComments"] = false; (*settings)["strictRoot"] = true; (*settings)["allowDroppedNullPlaceholders"] = false; (*settings)["allowNumericKeys"] = false; (*settings)["allowSingleQuotes"] = false; (*settings)["failIfExtra"] = true; (*settings)["rejectDupKeys"] = true; //! [CharReaderBuilderStrictMode] } // static void CharReaderBuilder::setDefaults(Json::Value* settings) { //! [CharReaderBuilderDefaults] (*settings)["collectComments"] = true; (*settings)["allowComments"] = true; (*settings)["strictRoot"] = false; (*settings)["allowDroppedNullPlaceholders"] = false; (*settings)["allowNumericKeys"] = false; (*settings)["allowSingleQuotes"] = false; (*settings)["stackLimit"] = 1000; (*settings)["failIfExtra"] = false; (*settings)["rejectDupKeys"] = false; //! [CharReaderBuilderDefaults] } ////////////////////////////////// // global functions bool parseFromStream( CharReader::Factory const& fact, std::istream& sin, Value* root, std::string* errs) { std::ostringstream ssin; ssin << sin.rdbuf(); std::string doc = ssin.str(); char const* begin = doc.data(); char const* end = begin + doc.size(); // Note that we do not actually need a null-terminator. CharReaderPtr const reader(fact.newCharReader()); return reader->parse(begin, end, root, errs); } std::istream& operator>>(std::istream& sin, Value& root) { CharReaderBuilder b; std::string errs; bool ok = parseFromStream(b, sin, &root, &errs); if (!ok) { fprintf(stderr, "Error from reader: %s", errs.c_str()); throwRuntimeError("reader error"); } return sin; } } // namespace Json // ////////////////////////////////////////////////////////////////////// // End of content of file: src/lib_json/json_reader.cpp // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: src/lib_json/json_valueiterator.inl // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE // included by json_value.cpp namespace Json { // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class ValueIteratorBase // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// ValueIteratorBase::ValueIteratorBase() : current_(), isNull_(true) { } ValueIteratorBase::ValueIteratorBase( const Value::ObjectValues::iterator& current) : current_(current), isNull_(false) {} Value& ValueIteratorBase::deref() const { return current_->second; } void ValueIteratorBase::increment() { ++current_; } void ValueIteratorBase::decrement() { --current_; } ValueIteratorBase::difference_type ValueIteratorBase::computeDistance(const SelfType& other) const { #ifdef JSON_USE_CPPTL_SMALLMAP return other.current_ - current_; #else // Iterator for null value are initialized using the default // constructor, which initialize current_ to the default // std::map::iterator. As begin() and end() are two instance // of the default std::map::iterator, they can not be compared. // To allow this, we handle this comparison specifically. if (isNull_ && other.isNull_) { return 0; } // Usage of std::distance is not portable (does not compile with Sun Studio 12 // RogueWave STL, // which is the one used by default). // Using a portable hand-made version for non random iterator instead: // return difference_type( std::distance( current_, other.current_ ) ); difference_type myDistance = 0; for (Value::ObjectValues::iterator it = current_; it != other.current_; ++it) { ++myDistance; } return myDistance; #endif } bool ValueIteratorBase::isEqual(const SelfType& other) const { if (isNull_) { return other.isNull_; } return current_ == other.current_; } void ValueIteratorBase::copy(const SelfType& other) { current_ = other.current_; isNull_ = other.isNull_; } Value ValueIteratorBase::key() const { const Value::CZString czstring = (*current_).first; if (czstring.data()) { if (czstring.isStaticString()) return Value(StaticString(czstring.data())); return Value(czstring.data(), czstring.data() + czstring.length()); } return Value(czstring.index()); } UInt ValueIteratorBase::index() const { const Value::CZString czstring = (*current_).first; if (!czstring.data()) return czstring.index(); return Value::UInt(-1); } std::string ValueIteratorBase::name() const { char const* key; char const* end; key = memberName(&end); if (!key) return std::string(); return std::string(key, end); } char const* ValueIteratorBase::memberName() const { const char* name = (*current_).first.data(); return name ? name : ""; } char const* ValueIteratorBase::memberName(char const** end) const { const char* name = (*current_).first.data(); if (!name) { *end = NULL; return NULL; } *end = name + (*current_).first.length(); return name; } // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class ValueConstIterator // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// ValueConstIterator::ValueConstIterator() {} ValueConstIterator::ValueConstIterator( const Value::ObjectValues::iterator& current) : ValueIteratorBase(current) {} ValueConstIterator& ValueConstIterator:: operator=(const ValueIteratorBase& other) { copy(other); return *this; } // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class ValueIterator // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// ValueIterator::ValueIterator() {} ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current) : ValueIteratorBase(current) {} ValueIterator::ValueIterator(const ValueConstIterator& other) : ValueIteratorBase(other) {} ValueIterator::ValueIterator(const ValueIterator& other) : ValueIteratorBase(other) {} ValueIterator& ValueIterator::operator=(const SelfType& other) { copy(other); return *this; } } // namespace Json // ////////////////////////////////////////////////////////////////////// // End of content of file: src/lib_json/json_valueiterator.inl // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: src/lib_json/json_value.cpp // ////////////////////////////////////////////////////////////////////// // Copyright 2011 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #if !defined(JSON_IS_AMALGAMATION) #include #include #include #endif // if !defined(JSON_IS_AMALGAMATION) #include #include #include #include #include #ifdef JSON_USE_CPPTL #include #endif #include // size_t #include // min() #define JSON_ASSERT_UNREACHABLE assert(false) namespace Json { // This is a walkaround to avoid the static initialization of Value::null. // kNull must be word-aligned to avoid crashing on ARM. We use an alignment of // 8 (instead of 4) as a bit of future-proofing. #if defined(__ARMEL__) #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment))) #else #define ALIGNAS(byte_alignment) #endif static const unsigned char ALIGNAS(8) kNull[sizeof(Value)] = { 0 }; const unsigned char& kNullRef = kNull[0]; const Value& Value::null = reinterpret_cast(kNullRef); const Value& Value::nullRef = null; const Int Value::minInt = Int(~(UInt(-1) / 2)); const Int Value::maxInt = Int(UInt(-1) / 2); const UInt Value::maxUInt = UInt(-1); #if defined(JSON_HAS_INT64) const Int64 Value::minInt64 = Int64(~(UInt64(-1) / 2)); const Int64 Value::maxInt64 = Int64(UInt64(-1) / 2); const UInt64 Value::maxUInt64 = UInt64(-1); // The constant is hard-coded because some compiler have trouble // converting Value::maxUInt64 to a double correctly (AIX/xlC). // Assumes that UInt64 is a 64 bits integer. static const double maxUInt64AsDouble = 18446744073709551615.0; #endif // defined(JSON_HAS_INT64) const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2)); const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2); const LargestUInt Value::maxLargestUInt = LargestUInt(-1); #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) template static inline bool InRange(double d, T min, U max) { return d >= min && d <= max; } #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) static inline double integerToDouble(Json::UInt64 value) { return static_cast(Int64(value / 2)) * 2.0 + Int64(value & 1); } template static inline double integerToDouble(T value) { return static_cast(value); } template static inline bool InRange(double d, T min, U max) { return d >= integerToDouble(min) && d <= integerToDouble(max); } #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) /** Duplicates the specified string value. * @param value Pointer to the string to duplicate. Must be zero-terminated if * length is "unknown". * @param length Length of the value. if equals to unknown, then it will be * computed using strlen(value). * @return Pointer on the duplicate instance of string. */ static inline char* duplicateStringValue(const char* value, size_t length) { // Avoid an integer overflow in the call to malloc below by limiting length // to a sane value. if (length >= (size_t)Value::maxInt) length = Value::maxInt - 1; char* newString = static_cast(malloc(length + 1)); if (newString == NULL) { throwRuntimeError( "in Json::Value::duplicateStringValue(): " "Failed to allocate string value buffer"); } memcpy(newString, value, length); newString[length] = 0; return newString; } /* Record the length as a prefix. */ static inline char* duplicateAndPrefixStringValue( const char* value, unsigned int length) { // Avoid an integer overflow in the call to malloc below by limiting length // to a sane value. JSON_ASSERT_MESSAGE(length <= (unsigned)Value::maxInt - sizeof(unsigned) - 1U, "in Json::Value::duplicateAndPrefixStringValue(): " "length too big for prefixing"); unsigned actualLength = length + sizeof(unsigned) + 1U; char* newString = static_cast(malloc(actualLength)); if (newString == 0) { throwRuntimeError( "in Json::Value::duplicateAndPrefixStringValue(): " "Failed to allocate string value buffer"); } *reinterpret_cast(newString) = length; memcpy(newString + sizeof(unsigned), value, length); newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later return newString; } inline static void decodePrefixedString( bool isPrefixed, char const* prefixed, unsigned* length, char const** value) { if (!isPrefixed) { *length = strlen(prefixed); *value = prefixed; } else { *length = *reinterpret_cast(prefixed); *value = prefixed + sizeof(unsigned); } } /** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue(). */ static inline void releaseStringValue(char* value) { free(value); } } // namespace Json // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ValueInternals... // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// #if !defined(JSON_IS_AMALGAMATION) #include "json_valueiterator.inl" #endif // if !defined(JSON_IS_AMALGAMATION) namespace Json { class JSON_API Exception : public std::exception { public: Exception(std::string const& msg); virtual ~Exception() throw(); virtual char const* what() const throw(); protected: std::string const msg_; }; class JSON_API RuntimeError : public Exception { public: RuntimeError(std::string const& msg); }; class JSON_API LogicError : public Exception { public: LogicError(std::string const& msg); }; Exception::Exception(std::string const& msg) : msg_(msg) {} Exception::~Exception() throw() {} char const* Exception::what() const throw() { return msg_.c_str(); } RuntimeError::RuntimeError(std::string const& msg) : Exception(msg) {} LogicError::LogicError(std::string const& msg) : Exception(msg) {} void throwRuntimeError(std::string const& msg) { throw RuntimeError(msg); } void throwLogicError(std::string const& msg) { throw LogicError(msg); } // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class Value::CommentInfo // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// Value::CommentInfo::CommentInfo() : comment_(0) {} Value::CommentInfo::~CommentInfo() { if (comment_) releaseStringValue(comment_); } void Value::CommentInfo::setComment(const char* text, size_t len) { if (comment_) { releaseStringValue(comment_); comment_ = 0; } JSON_ASSERT(text != 0); JSON_ASSERT_MESSAGE( text[0] == '\0' || text[0] == '/', "in Json::Value::setComment(): Comments must start with /"); // It seems that /**/ style comments are acceptable as well. comment_ = duplicateStringValue(text, len); } // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class Value::CZString // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // Notes: policy_ indicates if the string was allocated when // a string is stored. Value::CZString::CZString(ArrayIndex index) : cstr_(0), index_(index) {} Value::CZString::CZString(char const* str, unsigned length, DuplicationPolicy allocate) : cstr_(str) { // allocate != duplicate storage_.policy_ = allocate; storage_.length_ = length; } Value::CZString::CZString(const CZString& other) : cstr_(other.storage_.policy_ != noDuplication && other.cstr_ != 0 ? duplicateStringValue(other.cstr_, other.storage_.length_) : other.cstr_) { storage_.policy_ = (other.cstr_ ? (other.storage_.policy_ == noDuplication ? noDuplication : duplicate) : other.storage_.policy_); storage_.length_ = other.storage_.length_; } Value::CZString::~CZString() { if (cstr_ && storage_.policy_ == duplicate) releaseStringValue(const_cast(cstr_)); } void Value::CZString::swap(CZString& other) { std::swap(cstr_, other.cstr_); std::swap(index_, other.index_); } Value::CZString& Value::CZString::operator=(CZString other) { swap(other); return *this; } bool Value::CZString::operator<(const CZString& other) const { if (!cstr_) return index_ < other.index_; //return strcmp(cstr_, other.cstr_) < 0; // Assume both are strings. unsigned this_len = this->storage_.length_; unsigned other_len = other.storage_.length_; unsigned min_len = std::min(this_len, other_len); int comp = memcmp(this->cstr_, other.cstr_, min_len); if (comp < 0) return true; if (comp > 0) return false; return (this_len < other_len); } bool Value::CZString::operator==(const CZString& other) const { if (!cstr_) return index_ == other.index_; //return strcmp(cstr_, other.cstr_) == 0; // Assume both are strings. unsigned this_len = this->storage_.length_; unsigned other_len = other.storage_.length_; if (this_len != other_len) return false; int comp = memcmp(this->cstr_, other.cstr_, this_len); return comp == 0; } ArrayIndex Value::CZString::index() const { return index_; } //const char* Value::CZString::c_str() const { return cstr_; } const char* Value::CZString::data() const { return cstr_; } unsigned Value::CZString::length() const { return storage_.length_; } bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; } // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class Value::Value // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// /*! \internal Default constructor initialization must be equivalent to: * memset( this, 0, sizeof(Value) ) * This optimization is used in ValueInternalMap fast allocator. */ Value::Value(ValueType type) { initBasic(type); switch (type) { case nullValue: break; case intValue: case uintValue: value_.int_ = 0; break; case realValue: value_.real_ = 0.0; break; case stringValue: value_.string_ = 0; break; case arrayValue: case objectValue: value_.map_ = new ObjectValues(); break; case booleanValue: value_.bool_ = false; break; default: JSON_ASSERT_UNREACHABLE; } } Value::Value(Int value) { initBasic(intValue); value_.int_ = value; } Value::Value(UInt value) { initBasic(uintValue); value_.uint_ = value; } #if defined(JSON_HAS_INT64) Value::Value(Int64 value) { initBasic(intValue); value_.int_ = value; } Value::Value(UInt64 value) { initBasic(uintValue); value_.uint_ = value; } #endif // defined(JSON_HAS_INT64) Value::Value(double value) { initBasic(realValue); value_.real_ = value; } Value::Value(const char* value) { initBasic(stringValue, true); value_.string_ = duplicateAndPrefixStringValue(value, static_cast(strlen(value))); } Value::Value(const char* beginValue, const char* endValue) { initBasic(stringValue, true); value_.string_ = duplicateAndPrefixStringValue(beginValue, static_cast(endValue - beginValue)); } Value::Value(const std::string& value) { initBasic(stringValue, true); value_.string_ = duplicateAndPrefixStringValue(value.data(), static_cast(value.length())); } Value::Value(const StaticString& value) { initBasic(stringValue); value_.string_ = const_cast(value.c_str()); } #ifdef JSON_USE_CPPTL Value::Value(const CppTL::ConstString& value) { initBasic(stringValue, true); value_.string_ = duplicateAndPrefixStringValue(value, static_cast(value.length())); } #endif Value::Value(bool value) { initBasic(booleanValue); value_.bool_ = value; } Value::Value(Value const& other) : type_(other.type_), allocated_(false) , comments_(0), start_(other.start_), limit_(other.limit_) { switch (type_) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: value_ = other.value_; break; case stringValue: if (other.value_.string_ && other.allocated_) { unsigned len; char const* str; decodePrefixedString(other.allocated_, other.value_.string_, &len, &str); value_.string_ = duplicateAndPrefixStringValue(str, len); allocated_ = true; } else { value_.string_ = other.value_.string_; allocated_ = false; } break; case arrayValue: case objectValue: value_.map_ = new ObjectValues(*other.value_.map_); break; default: JSON_ASSERT_UNREACHABLE; } if (other.comments_) { comments_ = new CommentInfo[numberOfCommentPlacement]; for (int comment = 0; comment < numberOfCommentPlacement; ++comment) { const CommentInfo& otherComment = other.comments_[comment]; if (otherComment.comment_) comments_[comment].setComment( otherComment.comment_, strlen(otherComment.comment_)); } } } Value::~Value() { switch (type_) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: break; case stringValue: if (allocated_) releaseStringValue(value_.string_); break; case arrayValue: case objectValue: delete value_.map_; break; default: JSON_ASSERT_UNREACHABLE; } if (comments_) delete[] comments_; } Value& Value::operator=(Value other) { swap(other); return *this; } void Value::swapPayload(Value& other) { ValueType temp = type_; type_ = other.type_; other.type_ = temp; std::swap(value_, other.value_); int temp2 = allocated_; allocated_ = other.allocated_; other.allocated_ = temp2; } void Value::swap(Value& other) { swapPayload(other); std::swap(comments_, other.comments_); std::swap(start_, other.start_); std::swap(limit_, other.limit_); } ValueType Value::type() const { return type_; } int Value::compare(const Value& other) const { if (*this < other) return -1; if (*this > other) return 1; return 0; } bool Value::operator<(const Value& other) const { int typeDelta = type_ - other.type_; if (typeDelta) return typeDelta < 0 ? true : false; switch (type_) { case nullValue: return false; case intValue: return value_.int_ < other.value_.int_; case uintValue: return value_.uint_ < other.value_.uint_; case realValue: return value_.real_ < other.value_.real_; case booleanValue: return value_.bool_ < other.value_.bool_; case stringValue: { if ((value_.string_ == 0) || (other.value_.string_ == 0)) { if (other.value_.string_) return true; else return false; } unsigned this_len; unsigned other_len; char const* this_str; char const* other_str; decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str); unsigned min_len = std::min(this_len, other_len); int comp = memcmp(this_str, other_str, min_len); if (comp < 0) return true; if (comp > 0) return false; return (this_len < other_len); } case arrayValue: case objectValue: { int delta = int(value_.map_->size() - other.value_.map_->size()); if (delta) return delta < 0; return (*value_.map_) < (*other.value_.map_); } default: JSON_ASSERT_UNREACHABLE; } return false; // unreachable } bool Value::operator<=(const Value& other) const { return !(other < *this); } bool Value::operator>=(const Value& other) const { return !(*this < other); } bool Value::operator>(const Value& other) const { return other < *this; } bool Value::operator==(const Value& other) const { // if ( type_ != other.type_ ) // GCC 2.95.3 says: // attempt to take address of bit-field structure member `Json::Value::type_' // Beats me, but a temp solves the problem. int temp = other.type_; if (type_ != temp) return false; switch (type_) { case nullValue: return true; case intValue: return value_.int_ == other.value_.int_; case uintValue: return value_.uint_ == other.value_.uint_; case realValue: return value_.real_ == other.value_.real_; case booleanValue: return value_.bool_ == other.value_.bool_; case stringValue: { if ((value_.string_ == 0) || (other.value_.string_ == 0)) { return (value_.string_ == other.value_.string_); } unsigned this_len; unsigned other_len; char const* this_str; char const* other_str; decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str); if (this_len != other_len) return false; int comp = memcmp(this_str, other_str, this_len); return comp == 0; } case arrayValue: case objectValue: return value_.map_->size() == other.value_.map_->size() && (*value_.map_) == (*other.value_.map_); default: JSON_ASSERT_UNREACHABLE; } return false; // unreachable } bool Value::operator!=(const Value& other) const { return !(*this == other); } const char* Value::asCString() const { JSON_ASSERT_MESSAGE(type_ == stringValue, "in Json::Value::asCString(): requires stringValue"); if (value_.string_ == 0) return 0; unsigned this_len; char const* this_str; decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); return this_str; } bool Value::getString(char const** str, char const** end) const { if (type_ != stringValue) return false; if (value_.string_ == 0) return false; unsigned length; decodePrefixedString(this->allocated_, this->value_.string_, &length, str); *end = *str + length; return true; } std::string Value::asString() const { switch (type_) { case nullValue: return ""; case stringValue: { if (value_.string_ == 0) return ""; unsigned this_len; char const* this_str; decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); return std::string(this_str, this_len); } case booleanValue: return value_.bool_ ? "true" : "false"; case intValue: return valueToString(value_.int_); case uintValue: return valueToString(value_.uint_); case realValue: return valueToString(value_.real_); default: JSON_FAIL_MESSAGE("Type is not convertible to string"); } } #ifdef JSON_USE_CPPTL CppTL::ConstString Value::asConstString() const { unsigned len; char const* str; decodePrefixedString(allocated_, value_.string_, &len, &str); return CppTL::ConstString(str, len); } #endif Value::Int Value::asInt() const { switch (type_) { case intValue: JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range"); return Int(value_.int_); case uintValue: JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range"); return Int(value_.uint_); case realValue: JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt), "double out of Int range"); return Int(value_.real_); case nullValue: return 0; case booleanValue: return value_.bool_ ? 1 : 0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to Int."); } Value::UInt Value::asUInt() const { switch (type_) { case intValue: JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range"); return UInt(value_.int_); case uintValue: JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range"); return UInt(value_.uint_); case realValue: JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt), "double out of UInt range"); return UInt(value_.real_); case nullValue: return 0; case booleanValue: return value_.bool_ ? 1 : 0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to UInt."); } #if defined(JSON_HAS_INT64) Value::Int64 Value::asInt64() const { switch (type_) { case intValue: return Int64(value_.int_); case uintValue: JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range"); return Int64(value_.uint_); case realValue: JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64), "double out of Int64 range"); return Int64(value_.real_); case nullValue: return 0; case booleanValue: return value_.bool_ ? 1 : 0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to Int64."); } Value::UInt64 Value::asUInt64() const { switch (type_) { case intValue: JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range"); return UInt64(value_.int_); case uintValue: return UInt64(value_.uint_); case realValue: JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64), "double out of UInt64 range"); return UInt64(value_.real_); case nullValue: return 0; case booleanValue: return value_.bool_ ? 1 : 0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to UInt64."); } #endif // if defined(JSON_HAS_INT64) LargestInt Value::asLargestInt() const { #if defined(JSON_NO_INT64) return asInt(); #else return asInt64(); #endif } LargestUInt Value::asLargestUInt() const { #if defined(JSON_NO_INT64) return asUInt(); #else return asUInt64(); #endif } double Value::asDouble() const { switch (type_) { case intValue: return static_cast(value_.int_); case uintValue: #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) return static_cast(value_.uint_); #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) return integerToDouble(value_.uint_); #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) case realValue: return value_.real_; case nullValue: return 0.0; case booleanValue: return value_.bool_ ? 1.0 : 0.0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to double."); } float Value::asFloat() const { switch (type_) { case intValue: return static_cast(value_.int_); case uintValue: #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) return static_cast(value_.uint_); #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) return integerToDouble(value_.uint_); #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) case realValue: return static_cast(value_.real_); case nullValue: return 0.0; case booleanValue: return value_.bool_ ? 1.0f : 0.0f; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to float."); } bool Value::asBool() const { switch (type_) { case booleanValue: return value_.bool_; case nullValue: return false; case intValue: return value_.int_ ? true : false; case uintValue: return value_.uint_ ? true : false; case realValue: return value_.real_ ? true : false; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to bool."); } bool Value::isConvertibleTo(ValueType other) const { switch (other) { case nullValue: return (isNumeric() && asDouble() == 0.0) || (type_ == booleanValue && value_.bool_ == false) || (type_ == stringValue && asString() == "") || (type_ == arrayValue && value_.map_->size() == 0) || (type_ == objectValue && value_.map_->size() == 0) || type_ == nullValue; case intValue: return isInt() || (type_ == realValue && InRange(value_.real_, minInt, maxInt)) || type_ == booleanValue || type_ == nullValue; case uintValue: return isUInt() || (type_ == realValue && InRange(value_.real_, 0, maxUInt)) || type_ == booleanValue || type_ == nullValue; case realValue: return isNumeric() || type_ == booleanValue || type_ == nullValue; case booleanValue: return isNumeric() || type_ == booleanValue || type_ == nullValue; case stringValue: return isNumeric() || type_ == booleanValue || type_ == stringValue || type_ == nullValue; case arrayValue: return type_ == arrayValue || type_ == nullValue; case objectValue: return type_ == objectValue || type_ == nullValue; } JSON_ASSERT_UNREACHABLE; return false; } /// Number of values in array or object ArrayIndex Value::size() const { switch (type_) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: case stringValue: return 0; case arrayValue: // size of the array is highest index + 1 if (!value_.map_->empty()) { ObjectValues::const_iterator itLast = value_.map_->end(); --itLast; return (*itLast).first.index() + 1; } return 0; case objectValue: return ArrayIndex(value_.map_->size()); } JSON_ASSERT_UNREACHABLE; return 0; // unreachable; } bool Value::empty() const { if (isNull() || isArray() || isObject()) return size() == 0u; else return false; } bool Value::operator!() const { return isNull(); } void Value::clear() { JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue || type_ == objectValue, "in Json::Value::clear(): requires complex value"); start_ = 0; limit_ = 0; switch (type_) { case arrayValue: case objectValue: value_.map_->clear(); break; default: break; } } void Value::resize(ArrayIndex newSize) { JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue, "in Json::Value::resize(): requires arrayValue"); if (type_ == nullValue) *this = Value(arrayValue); ArrayIndex oldSize = size(); if (newSize == 0) clear(); else if (newSize > oldSize) (*this)[newSize - 1]; else { for (ArrayIndex index = newSize; index < oldSize; ++index) { value_.map_->erase(index); } assert(size() == newSize); } } Value& Value::operator[](ArrayIndex index) { JSON_ASSERT_MESSAGE( type_ == nullValue || type_ == arrayValue, "in Json::Value::operator[](ArrayIndex): requires arrayValue"); if (type_ == nullValue) *this = Value(arrayValue); CZString key(index); ObjectValues::iterator it = value_.map_->lower_bound(key); if (it != value_.map_->end() && (*it).first == key) return (*it).second; ObjectValues::value_type defaultValue(key, nullRef); it = value_.map_->insert(it, defaultValue); return (*it).second; } Value& Value::operator[](int index) { JSON_ASSERT_MESSAGE( index >= 0, "in Json::Value::operator[](int index): index cannot be negative"); return (*this)[ArrayIndex(index)]; } const Value& Value::operator[](ArrayIndex index) const { JSON_ASSERT_MESSAGE( type_ == nullValue || type_ == arrayValue, "in Json::Value::operator[](ArrayIndex)const: requires arrayValue"); if (type_ == nullValue) return nullRef; CZString key(index); ObjectValues::const_iterator it = value_.map_->find(key); if (it == value_.map_->end()) return nullRef; return (*it).second; } const Value& Value::operator[](int index) const { JSON_ASSERT_MESSAGE( index >= 0, "in Json::Value::operator[](int index) const: index cannot be negative"); return (*this)[ArrayIndex(index)]; } void Value::initBasic(ValueType type, bool allocated) { type_ = type; allocated_ = allocated; comments_ = 0; start_ = 0; limit_ = 0; } // Access an object value by name, create a null member if it does not exist. // @pre Type of '*this' is object or null. // @param key is null-terminated. Value& Value::resolveReference(const char* key) { JSON_ASSERT_MESSAGE( type_ == nullValue || type_ == objectValue, "in Json::Value::resolveReference(): requires objectValue"); if (type_ == nullValue) *this = Value(objectValue); CZString actualKey( key, static_cast(strlen(key)), CZString::noDuplication); // NOTE! ObjectValues::iterator it = value_.map_->lower_bound(actualKey); if (it != value_.map_->end() && (*it).first == actualKey) return (*it).second; ObjectValues::value_type defaultValue(actualKey, nullRef); it = value_.map_->insert(it, defaultValue); Value& value = (*it).second; return value; } // @param key is not null-terminated. Value& Value::resolveReference(char const* key, char const* end) { JSON_ASSERT_MESSAGE( type_ == nullValue || type_ == objectValue, "in Json::Value::resolveReference(key, end): requires objectValue"); if (type_ == nullValue) *this = Value(objectValue); CZString actualKey( key, static_cast(end-key), CZString::duplicateOnCopy); ObjectValues::iterator it = value_.map_->lower_bound(actualKey); if (it != value_.map_->end() && (*it).first == actualKey) return (*it).second; ObjectValues::value_type defaultValue(actualKey, nullRef); it = value_.map_->insert(it, defaultValue); Value& value = (*it).second; return value; } Value Value::get(ArrayIndex index, const Value& defaultValue) const { const Value* value = &((*this)[index]); return value == &nullRef ? defaultValue : *value; } bool Value::isValidIndex(ArrayIndex index) const { return index < size(); } Value const* Value::find(char const* key, char const* end) const { JSON_ASSERT_MESSAGE( type_ == nullValue || type_ == objectValue, "in Json::Value::find(key, end, found): requires objectValue or nullValue"); if (type_ == nullValue) return NULL; CZString actualKey(key, static_cast(end-key), CZString::noDuplication); ObjectValues::const_iterator it = value_.map_->find(actualKey); if (it == value_.map_->end()) return NULL; return &(*it).second; } const Value& Value::operator[](const char* key) const { Value const* found = find(key, key + strlen(key)); if (!found) return nullRef; return *found; } Value const& Value::operator[](std::string const& key) const { Value const* found = find(key.data(), key.data() + key.length()); if (!found) return nullRef; return *found; } Value& Value::operator[](const char* key) { return resolveReference(key, key + strlen(key)); } Value& Value::operator[](const std::string& key) { return resolveReference(key.data(), key.data() + key.length()); } Value& Value::operator[](const StaticString& key) { return resolveReference(key.c_str()); } #ifdef JSON_USE_CPPTL Value& Value::operator[](const CppTL::ConstString& key) { return resolveReference(key.c_str(), key.end_c_str()); } Value const& Value::operator[](CppTL::ConstString const& key) const { Value const* found = find(key.c_str(), key.end_c_str()); if (!found) return nullRef; return *found; } #endif Value& Value::append(const Value& value) { return (*this)[size()] = value; } Value Value::get(char const* key, char const* end, Value const& defaultValue) const { Value const* found = find(key, end); return !found ? defaultValue : *found; } Value Value::get(char const* key, Value const& defaultValue) const { return get(key, key + strlen(key), defaultValue); } Value Value::get(std::string const& key, Value const& defaultValue) const { return get(key.data(), key.data() + key.length(), defaultValue); } bool Value::removeMember(const char* key, const char* end, Value* removed) { if (type_ != objectValue) { return false; } CZString actualKey(key, static_cast(end-key), CZString::noDuplication); ObjectValues::iterator it = value_.map_->find(actualKey); if (it == value_.map_->end()) return false; *removed = it->second; value_.map_->erase(it); return true; } bool Value::removeMember(const char* key, Value* removed) { return removeMember(key, key + strlen(key), removed); } bool Value::removeMember(std::string const& key, Value* removed) { return removeMember(key.data(), key.data() + key.length(), removed); } Value Value::removeMember(const char* key) { JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue, "in Json::Value::removeMember(): requires objectValue"); if (type_ == nullValue) return nullRef; Value removed; // null removeMember(key, key + strlen(key), &removed); return removed; // still null if removeMember() did nothing } Value Value::removeMember(const std::string& key) { return removeMember(key.c_str()); } bool Value::removeIndex(ArrayIndex index, Value* removed) { if (type_ != arrayValue) { return false; } CZString key(index); ObjectValues::iterator it = value_.map_->find(key); if (it == value_.map_->end()) { return false; } *removed = it->second; ArrayIndex oldSize = size(); // shift left all items left, into the place of the "removed" for (ArrayIndex i = index; i < (oldSize - 1); ++i){ CZString key(i); (*value_.map_)[key] = (*this)[i + 1]; } // erase the last one ("leftover") CZString keyLast(oldSize - 1); ObjectValues::iterator itLast = value_.map_->find(keyLast); value_.map_->erase(itLast); return true; } #ifdef JSON_USE_CPPTL Value Value::get(const CppTL::ConstString& key, const Value& defaultValue) const { return get(key.c_str(), key.end_c_str(), defaultValue); } #endif bool Value::isMember(char const* key, char const* end) const { Value const* value = find(key, end); return NULL != value; } bool Value::isMember(char const* key) const { return isMember(key, key + strlen(key)); } bool Value::isMember(std::string const& key) const { return isMember(key.data(), key.data() + key.length()); } #ifdef JSON_USE_CPPTL bool Value::isMember(const CppTL::ConstString& key) const { return isMember(key.c_str(), key.end_c_str()); } #endif Value::Members Value::getMemberNames() const { JSON_ASSERT_MESSAGE( type_ == nullValue || type_ == objectValue, "in Json::Value::getMemberNames(), value must be objectValue"); if (type_ == nullValue) return Value::Members(); Members members; members.reserve(value_.map_->size()); ObjectValues::const_iterator it = value_.map_->begin(); ObjectValues::const_iterator itEnd = value_.map_->end(); for (; it != itEnd; ++it) { members.push_back(std::string((*it).first.data(), (*it).first.length())); } return members; } // //# ifdef JSON_USE_CPPTL // EnumMemberNames // Value::enumMemberNames() const //{ // if ( type_ == objectValue ) // { // return CppTL::Enum::any( CppTL::Enum::transform( // CppTL::Enum::keys( *(value_.map_), CppTL::Type() ), // MemberNamesTransform() ) ); // } // return EnumMemberNames(); //} // // // EnumValues // Value::enumValues() const //{ // if ( type_ == objectValue || type_ == arrayValue ) // return CppTL::Enum::anyValues( *(value_.map_), // CppTL::Type() ); // return EnumValues(); //} // //# endif static bool IsIntegral(double d) { double integral_part; return modf(d, &integral_part) == 0.0; } bool Value::isNull() const { return type_ == nullValue; } bool Value::isBool() const { return type_ == booleanValue; } bool Value::isInt() const { switch (type_) { case intValue: return value_.int_ >= minInt && value_.int_ <= maxInt; case uintValue: return value_.uint_ <= UInt(maxInt); case realValue: return value_.real_ >= minInt && value_.real_ <= maxInt && IsIntegral(value_.real_); default: break; } return false; } bool Value::isUInt() const { switch (type_) { case intValue: return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt); case uintValue: return value_.uint_ <= maxUInt; case realValue: return value_.real_ >= 0 && value_.real_ <= maxUInt && IsIntegral(value_.real_); default: break; } return false; } bool Value::isInt64() const { #if defined(JSON_HAS_INT64) switch (type_) { case intValue: return true; case uintValue: return value_.uint_ <= UInt64(maxInt64); case realValue: // Note that maxInt64 (= 2^63 - 1) is not exactly representable as a // double, so double(maxInt64) will be rounded up to 2^63. Therefore we // require the value to be strictly less than the limit. return value_.real_ >= double(minInt64) && value_.real_ < double(maxInt64) && IsIntegral(value_.real_); default: break; } #endif // JSON_HAS_INT64 return false; } bool Value::isUInt64() const { #if defined(JSON_HAS_INT64) switch (type_) { case intValue: return value_.int_ >= 0; case uintValue: return true; case realValue: // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we // require the value to be strictly less than the limit. return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble && IsIntegral(value_.real_); default: break; } #endif // JSON_HAS_INT64 return false; } bool Value::isIntegral() const { #if defined(JSON_HAS_INT64) return isInt64() || isUInt64(); #else return isInt() || isUInt(); #endif } bool Value::isDouble() const { return type_ == realValue || isIntegral(); } bool Value::isNumeric() const { return isIntegral() || isDouble(); } bool Value::isString() const { return type_ == stringValue; } bool Value::isArray() const { return type_ == arrayValue; } bool Value::isObject() const { return type_ == objectValue; } void Value::setComment(const char* comment, size_t len, CommentPlacement placement) { if (!comments_) comments_ = new CommentInfo[numberOfCommentPlacement]; if ((len > 0) && (comment[len-1] == '\n')) { // Always discard trailing newline, to aid indentation. len -= 1; } comments_[placement].setComment(comment, len); } void Value::setComment(const char* comment, CommentPlacement placement) { setComment(comment, strlen(comment), placement); } void Value::setComment(const std::string& comment, CommentPlacement placement) { setComment(comment.c_str(), comment.length(), placement); } bool Value::hasComment(CommentPlacement placement) const { return comments_ != 0 && comments_[placement].comment_ != 0; } std::string Value::getComment(CommentPlacement placement) const { if (hasComment(placement)) return comments_[placement].comment_; return ""; } void Value::setOffsetStart(size_t start) { start_ = start; } void Value::setOffsetLimit(size_t limit) { limit_ = limit; } size_t Value::getOffsetStart() const { return start_; } size_t Value::getOffsetLimit() const { return limit_; } std::string Value::toStyledString() const { StyledWriter writer; return writer.write(*this); } Value::const_iterator Value::begin() const { switch (type_) { case arrayValue: case objectValue: if (value_.map_) return const_iterator(value_.map_->begin()); break; default: break; } return const_iterator(); } Value::const_iterator Value::end() const { switch (type_) { case arrayValue: case objectValue: if (value_.map_) return const_iterator(value_.map_->end()); break; default: break; } return const_iterator(); } Value::iterator Value::begin() { switch (type_) { case arrayValue: case objectValue: if (value_.map_) return iterator(value_.map_->begin()); break; default: break; } return iterator(); } Value::iterator Value::end() { switch (type_) { case arrayValue: case objectValue: if (value_.map_) return iterator(value_.map_->end()); break; default: break; } return iterator(); } // class PathArgument // ////////////////////////////////////////////////////////////////// PathArgument::PathArgument() : key_(), index_(), kind_(kindNone) {} PathArgument::PathArgument(ArrayIndex index) : key_(), index_(index), kind_(kindIndex) {} PathArgument::PathArgument(const char* key) : key_(key), index_(), kind_(kindKey) {} PathArgument::PathArgument(const std::string& key) : key_(key.c_str()), index_(), kind_(kindKey) {} // class Path // ////////////////////////////////////////////////////////////////// Path::Path(const std::string& path, const PathArgument& a1, const PathArgument& a2, const PathArgument& a3, const PathArgument& a4, const PathArgument& a5) { InArgs in; in.push_back(&a1); in.push_back(&a2); in.push_back(&a3); in.push_back(&a4); in.push_back(&a5); makePath(path, in); } void Path::makePath(const std::string& path, const InArgs& in) { const char* current = path.c_str(); const char* end = current + path.length(); InArgs::const_iterator itInArg = in.begin(); while (current != end) { if (*current == '[') { ++current; if (*current == '%') addPathInArg(path, in, itInArg, PathArgument::kindIndex); else { ArrayIndex index = 0; for (; current != end && *current >= '0' && *current <= '9'; ++current) index = index * 10 + ArrayIndex(*current - '0'); args_.push_back(index); } if (current == end || *current++ != ']') invalidPath(path, int(current - path.c_str())); } else if (*current == '%') { addPathInArg(path, in, itInArg, PathArgument::kindKey); ++current; } else if (*current == '.') { ++current; } else { const char* beginName = current; while (current != end && !strchr("[.", *current)) ++current; args_.push_back(std::string(beginName, current)); } } } void Path::addPathInArg(const std::string& /*path*/, const InArgs& in, InArgs::const_iterator& itInArg, PathArgument::Kind kind) { if (itInArg == in.end()) { // Error: missing argument %d } else if ((*itInArg)->kind_ != kind) { // Error: bad argument type } else { args_.push_back(**itInArg); } } void Path::invalidPath(const std::string& /*path*/, int /*location*/) { // Error: invalid path. } const Value& Path::resolve(const Value& root) const { const Value* node = &root; for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) { const PathArgument& arg = *it; if (arg.kind_ == PathArgument::kindIndex) { if (!node->isArray() || !node->isValidIndex(arg.index_)) { // Error: unable to resolve path (array value expected at position... } node = &((*node)[arg.index_]); } else if (arg.kind_ == PathArgument::kindKey) { if (!node->isObject()) { // Error: unable to resolve path (object value expected at position...) } node = &((*node)[arg.key_]); if (node == &Value::nullRef) { // Error: unable to resolve path (object has no member named '' at // position...) } } } return *node; } Value Path::resolve(const Value& root, const Value& defaultValue) const { const Value* node = &root; for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) { const PathArgument& arg = *it; if (arg.kind_ == PathArgument::kindIndex) { if (!node->isArray() || !node->isValidIndex(arg.index_)) return defaultValue; node = &((*node)[arg.index_]); } else if (arg.kind_ == PathArgument::kindKey) { if (!node->isObject()) return defaultValue; node = &((*node)[arg.key_]); if (node == &Value::nullRef) return defaultValue; } } return *node; } Value& Path::make(Value& root) const { Value* node = &root; for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) { const PathArgument& arg = *it; if (arg.kind_ == PathArgument::kindIndex) { if (!node->isArray()) { // Error: node is not an array at position ... } node = &((*node)[arg.index_]); } else if (arg.kind_ == PathArgument::kindKey) { if (!node->isObject()) { // Error: node is not an object at position... } node = &((*node)[arg.key_]); } } return *node; } } // namespace Json // ////////////////////////////////////////////////////////////////////// // End of content of file: src/lib_json/json_value.cpp // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: src/lib_json/json_writer.cpp // ////////////////////////////////////////////////////////////////////// // Copyright 2011 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #if !defined(JSON_IS_AMALGAMATION) #include #include "json_tool.h" #endif // if !defined(JSON_IS_AMALGAMATION) #include #include #include #include #include #include #include #include #if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0 #include #define isfinite _finite #elif defined(__sun) && defined(__SVR4) //Solaris #include #define isfinite finite #else #include #define isfinite std::isfinite #endif #if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below #define snprintf _snprintf #else #define snprintf std::snprintf #endif #if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0 // Disable warning about strdup being deprecated. #pragma warning(disable : 4996) #endif namespace Json { #if __cplusplus >= 201103L typedef std::unique_ptr StreamWriterPtr; #else typedef std::auto_ptr StreamWriterPtr; #endif static bool containsControlCharacter(const char* str) { while (*str) { if (isControlCharacter(*(str++))) return true; } return false; } static bool containsControlCharacter0(const char* str, unsigned len) { char const* end = str + len; while (end != str) { if (isControlCharacter(*str) || 0==*str) return true; ++str; } return false; } std::string valueToString(LargestInt value) { UIntToStringBuffer buffer; char* current = buffer + sizeof(buffer); bool isNegative = value < 0; if (isNegative) value = -value; uintToString(LargestUInt(value), current); if (isNegative) *--current = '-'; assert(current >= buffer); return current; } std::string valueToString(LargestUInt value) { UIntToStringBuffer buffer; char* current = buffer + sizeof(buffer); uintToString(value, current); assert(current >= buffer); return current; } #if defined(JSON_HAS_INT64) std::string valueToString(Int value) { return valueToString(LargestInt(value)); } std::string valueToString(UInt value) { return valueToString(LargestUInt(value)); } #endif // # if defined(JSON_HAS_INT64) std::string valueToString(double value) { // Allocate a buffer that is more than large enough to store the 16 digits of // precision requested below. char buffer[32]; int len = -1; // Print into the buffer. We need not request the alternative representation // that always has a decimal point because JSON doesn't distingish the // concepts of reals and integers. #if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with // visual studio 2005 to // avoid warning. #if defined(WINCE) len = _snprintf(buffer, sizeof(buffer), "%.17g", value); #else len = sprintf_s(buffer, sizeof(buffer), "%.17g", value); #endif #else if (isfinite(value)) { len = snprintf(buffer, sizeof(buffer), "%.17g", value); } else { // IEEE standard states that NaN values will not compare to themselves if (value != value) { len = snprintf(buffer, sizeof(buffer), "null"); } else if (value < 0) { len = snprintf(buffer, sizeof(buffer), "-1e+9999"); } else { len = snprintf(buffer, sizeof(buffer), "1e+9999"); } // For those, we do not need to call fixNumLoc, but it is fast. } #endif assert(len >= 0); fixNumericLocale(buffer, buffer + len); return buffer; } std::string valueToString(bool value) { return value ? "true" : "false"; } std::string valueToQuotedString(const char* value) { if (value == NULL) return ""; // Not sure how to handle unicode... if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && !containsControlCharacter(value)) return std::string("\"") + value + "\""; // We have to walk value and escape any special characters. // Appending to std::string is not efficient, but this should be rare. // (Note: forward slashes are *not* rare, but I am not escaping them.) std::string::size_type maxsize = strlen(value) * 2 + 3; // allescaped+quotes+NULL std::string result; result.reserve(maxsize); // to avoid lots of mallocs result += "\""; for (const char* c = value; *c != 0; ++c) { switch (*c) { case '\"': result += "\\\""; break; case '\\': result += "\\\\"; break; case '\b': result += "\\b"; break; case '\f': result += "\\f"; break; case '\n': result += "\\n"; break; case '\r': result += "\\r"; break; case '\t': result += "\\t"; break; // case '/': // Even though \/ is considered a legal escape in JSON, a bare // slash is also legal, so I see no reason to escape it. // (I hope I am not misunderstanding something. // blep notes: actually escaping \/ may be useful in javascript to avoid (*c); result += oss.str(); } else { result += *c; } break; } } result += "\""; return result; } // https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp static char const* strnpbrk(char const* s, char const* accept, size_t n) { assert((s || !n) && accept); char const* const end = s + n; for (char const* cur = s; cur < end; ++cur) { int const c = *cur; for (char const* a = accept; *a; ++a) { if (*a == c) { return cur; } } } return NULL; } static std::string valueToQuotedStringN(const char* value, unsigned length) { if (value == NULL) return ""; // Not sure how to handle unicode... if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL && !containsControlCharacter0(value, length)) return std::string("\"") + value + "\""; // We have to walk value and escape any special characters. // Appending to std::string is not efficient, but this should be rare. // (Note: forward slashes are *not* rare, but I am not escaping them.) std::string::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL std::string result; result.reserve(maxsize); // to avoid lots of mallocs result += "\""; char const* end = value + length; for (const char* c = value; c != end; ++c) { switch (*c) { case '\"': result += "\\\""; break; case '\\': result += "\\\\"; break; case '\b': result += "\\b"; break; case '\f': result += "\\f"; break; case '\n': result += "\\n"; break; case '\r': result += "\\r"; break; case '\t': result += "\\t"; break; // case '/': // Even though \/ is considered a legal escape in JSON, a bare // slash is also legal, so I see no reason to escape it. // (I hope I am not misunderstanding something.) // blep notes: actually escaping \/ may be useful in javascript to avoid (*c); result += oss.str(); } else { result += *c; } break; } } result += "\""; return result; } // Class Writer // ////////////////////////////////////////////////////////////////// Writer::~Writer() {} // Class FastWriter // ////////////////////////////////////////////////////////////////// FastWriter::FastWriter() : yamlCompatiblityEnabled_(false), dropNullPlaceholders_(false), omitEndingLineFeed_(false) {} void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; } void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; } void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; } std::string FastWriter::write(const Value& root) { document_ = ""; writeValue(root); if (!omitEndingLineFeed_) document_ += "\n"; return document_; } void FastWriter::writeValue(const Value& value) { switch (value.type()) { case nullValue: if (!dropNullPlaceholders_) document_ += "null"; break; case intValue: document_ += valueToString(value.asLargestInt()); break; case uintValue: document_ += valueToString(value.asLargestUInt()); break; case realValue: document_ += valueToString(value.asDouble()); break; case stringValue: document_ += valueToQuotedString(value.asCString()); break; case booleanValue: document_ += valueToString(value.asBool()); break; case arrayValue: { document_ += '['; int size = value.size(); for (int index = 0; index < size; ++index) { if (index > 0) document_ += ','; writeValue(value[index]); } document_ += ']'; } break; case objectValue: { Value::Members members(value.getMemberNames()); document_ += '{'; for (Value::Members::iterator it = members.begin(); it != members.end(); ++it) { const std::string& name = *it; if (it != members.begin()) document_ += ','; document_ += valueToQuotedStringN(name.data(), name.length()); document_ += yamlCompatiblityEnabled_ ? ": " : ":"; writeValue(value[name]); } document_ += '}'; } break; } } // Class StyledWriter // ////////////////////////////////////////////////////////////////// StyledWriter::StyledWriter() : rightMargin_(74), indentSize_(3), addChildValues_() {} std::string StyledWriter::write(const Value& root) { document_ = ""; addChildValues_ = false; indentString_ = ""; writeCommentBeforeValue(root); writeValue(root); writeCommentAfterValueOnSameLine(root); document_ += "\n"; return document_; } void StyledWriter::writeValue(const Value& value) { switch (value.type()) { case nullValue: pushValue("null"); break; case intValue: pushValue(valueToString(value.asLargestInt())); break; case uintValue: pushValue(valueToString(value.asLargestUInt())); break; case realValue: pushValue(valueToString(value.asDouble())); break; case stringValue: { // Is NULL is possible for value.string_? char const* str; char const* end; bool ok = value.getString(&str, &end); if (ok) pushValue(valueToQuotedStringN(str, static_cast(end-str))); else pushValue(""); break; } case booleanValue: pushValue(valueToString(value.asBool())); break; case arrayValue: writeArrayValue(value); break; case objectValue: { Value::Members members(value.getMemberNames()); if (members.empty()) pushValue("{}"); else { writeWithIndent("{"); indent(); Value::Members::iterator it = members.begin(); for (;;) { const std::string& name = *it; const Value& childValue = value[name]; writeCommentBeforeValue(childValue); writeWithIndent(valueToQuotedString(name.c_str())); document_ += " : "; writeValue(childValue); if (++it == members.end()) { writeCommentAfterValueOnSameLine(childValue); break; } document_ += ','; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("}"); } } break; } } void StyledWriter::writeArrayValue(const Value& value) { unsigned size = value.size(); if (size == 0) pushValue("[]"); else { bool isArrayMultiLine = isMultineArray(value); if (isArrayMultiLine) { writeWithIndent("["); indent(); bool hasChildValue = !childValues_.empty(); unsigned index = 0; for (;;) { const Value& childValue = value[index]; writeCommentBeforeValue(childValue); if (hasChildValue) writeWithIndent(childValues_[index]); else { writeIndent(); writeValue(childValue); } if (++index == size) { writeCommentAfterValueOnSameLine(childValue); break; } document_ += ','; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("]"); } else // output on a single line { assert(childValues_.size() == size); document_ += "[ "; for (unsigned index = 0; index < size; ++index) { if (index > 0) document_ += ", "; document_ += childValues_[index]; } document_ += " ]"; } } } bool StyledWriter::isMultineArray(const Value& value) { int size = value.size(); bool isMultiLine = size * 3 >= rightMargin_; childValues_.clear(); for (int index = 0; index < size && !isMultiLine; ++index) { const Value& childValue = value[index]; isMultiLine = isMultiLine || ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); } if (!isMultiLine) // check if line length > max line length { childValues_.reserve(size); addChildValues_ = true; int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' for (int index = 0; index < size; ++index) { if (hasCommentForValue(value[index])) { isMultiLine = true; } writeValue(value[index]); lineLength += int(childValues_[index].length()); } addChildValues_ = false; isMultiLine = isMultiLine || lineLength >= rightMargin_; } return isMultiLine; } void StyledWriter::pushValue(const std::string& value) { if (addChildValues_) childValues_.push_back(value); else document_ += value; } void StyledWriter::writeIndent() { if (!document_.empty()) { char last = document_[document_.length() - 1]; if (last == ' ') // already indented return; if (last != '\n') // Comments may add new-line document_ += '\n'; } document_ += indentString_; } void StyledWriter::writeWithIndent(const std::string& value) { writeIndent(); document_ += value; } void StyledWriter::indent() { indentString_ += std::string(indentSize_, ' '); } void StyledWriter::unindent() { assert(int(indentString_.size()) >= indentSize_); indentString_.resize(indentString_.size() - indentSize_); } void StyledWriter::writeCommentBeforeValue(const Value& root) { if (!root.hasComment(commentBefore)) return; document_ += "\n"; writeIndent(); const std::string& comment = root.getComment(commentBefore); std::string::const_iterator iter = comment.begin(); while (iter != comment.end()) { document_ += *iter; if (*iter == '\n' && (iter != comment.end() && *(iter + 1) == '/')) writeIndent(); ++iter; } // Comments are stripped of trailing newlines, so add one here document_ += "\n"; } void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) { if (root.hasComment(commentAfterOnSameLine)) document_ += " " + root.getComment(commentAfterOnSameLine); if (root.hasComment(commentAfter)) { document_ += "\n"; document_ += root.getComment(commentAfter); document_ += "\n"; } } bool StyledWriter::hasCommentForValue(const Value& value) { return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter); } // Class StyledStreamWriter // ////////////////////////////////////////////////////////////////// StyledStreamWriter::StyledStreamWriter(std::string indentation) : document_(NULL), rightMargin_(74), indentation_(indentation), addChildValues_() {} void StyledStreamWriter::write(std::ostream& out, const Value& root) { document_ = &out; addChildValues_ = false; indentString_ = ""; indented_ = true; writeCommentBeforeValue(root); if (!indented_) writeIndent(); indented_ = true; writeValue(root); writeCommentAfterValueOnSameLine(root); *document_ << "\n"; document_ = NULL; // Forget the stream, for safety. } void StyledStreamWriter::writeValue(const Value& value) { switch (value.type()) { case nullValue: pushValue("null"); break; case intValue: pushValue(valueToString(value.asLargestInt())); break; case uintValue: pushValue(valueToString(value.asLargestUInt())); break; case realValue: pushValue(valueToString(value.asDouble())); break; case stringValue: pushValue(valueToQuotedString(value.asCString())); break; case booleanValue: pushValue(valueToString(value.asBool())); break; case arrayValue: writeArrayValue(value); break; case objectValue: { Value::Members members(value.getMemberNames()); if (members.empty()) pushValue("{}"); else { writeWithIndent("{"); indent(); Value::Members::iterator it = members.begin(); for (;;) { const std::string& name = *it; const Value& childValue = value[name]; writeCommentBeforeValue(childValue); writeWithIndent(valueToQuotedString(name.c_str())); *document_ << " : "; writeValue(childValue); if (++it == members.end()) { writeCommentAfterValueOnSameLine(childValue); break; } *document_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("}"); } } break; } } void StyledStreamWriter::writeArrayValue(const Value& value) { unsigned size = value.size(); if (size == 0) pushValue("[]"); else { bool isArrayMultiLine = isMultineArray(value); if (isArrayMultiLine) { writeWithIndent("["); indent(); bool hasChildValue = !childValues_.empty(); unsigned index = 0; for (;;) { const Value& childValue = value[index]; writeCommentBeforeValue(childValue); if (hasChildValue) writeWithIndent(childValues_[index]); else { if (!indented_) writeIndent(); indented_ = true; writeValue(childValue); indented_ = false; } if (++index == size) { writeCommentAfterValueOnSameLine(childValue); break; } *document_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("]"); } else // output on a single line { assert(childValues_.size() == size); *document_ << "[ "; for (unsigned index = 0; index < size; ++index) { if (index > 0) *document_ << ", "; *document_ << childValues_[index]; } *document_ << " ]"; } } } bool StyledStreamWriter::isMultineArray(const Value& value) { int size = value.size(); bool isMultiLine = size * 3 >= rightMargin_; childValues_.clear(); for (int index = 0; index < size && !isMultiLine; ++index) { const Value& childValue = value[index]; isMultiLine = isMultiLine || ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); } if (!isMultiLine) // check if line length > max line length { childValues_.reserve(size); addChildValues_ = true; int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' for (int index = 0; index < size; ++index) { if (hasCommentForValue(value[index])) { isMultiLine = true; } writeValue(value[index]); lineLength += int(childValues_[index].length()); } addChildValues_ = false; isMultiLine = isMultiLine || lineLength >= rightMargin_; } return isMultiLine; } void StyledStreamWriter::pushValue(const std::string& value) { if (addChildValues_) childValues_.push_back(value); else *document_ << value; } void StyledStreamWriter::writeIndent() { // blep intended this to look at the so-far-written string // to determine whether we are already indented, but // with a stream we cannot do that. So we rely on some saved state. // The caller checks indented_. *document_ << '\n' << indentString_; } void StyledStreamWriter::writeWithIndent(const std::string& value) { if (!indented_) writeIndent(); *document_ << value; indented_ = false; } void StyledStreamWriter::indent() { indentString_ += indentation_; } void StyledStreamWriter::unindent() { assert(indentString_.size() >= indentation_.size()); indentString_.resize(indentString_.size() - indentation_.size()); } void StyledStreamWriter::writeCommentBeforeValue(const Value& root) { if (!root.hasComment(commentBefore)) return; if (!indented_) writeIndent(); const std::string& comment = root.getComment(commentBefore); std::string::const_iterator iter = comment.begin(); while (iter != comment.end()) { *document_ << *iter; if (*iter == '\n' && (iter != comment.end() && *(iter + 1) == '/')) // writeIndent(); // would include newline *document_ << indentString_; ++iter; } indented_ = false; } void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) { if (root.hasComment(commentAfterOnSameLine)) *document_ << ' ' << root.getComment(commentAfterOnSameLine); if (root.hasComment(commentAfter)) { writeIndent(); *document_ << root.getComment(commentAfter); } indented_ = false; } bool StyledStreamWriter::hasCommentForValue(const Value& value) { return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter); } ////////////////////////// // BuiltStyledStreamWriter /// Scoped enums are not available until C++11. struct CommentStyle { /// Decide whether to write comments. enum Enum { None, ///< Drop all comments. Most, ///< Recover odd behavior of previous versions (not implemented yet). All ///< Keep all comments. }; }; struct BuiltStyledStreamWriter : public StreamWriter { BuiltStyledStreamWriter( std::string const& indentation, CommentStyle::Enum cs, std::string const& colonSymbol, std::string const& nullSymbol, std::string const& endingLineFeedSymbol); virtual int write(Value const& root, std::ostream* sout); private: void writeValue(Value const& value); void writeArrayValue(Value const& value); bool isMultineArray(Value const& value); void pushValue(std::string const& value); void writeIndent(); void writeWithIndent(std::string const& value); void indent(); void unindent(); void writeCommentBeforeValue(Value const& root); void writeCommentAfterValueOnSameLine(Value const& root); static bool hasCommentForValue(const Value& value); typedef std::vector ChildValues; ChildValues childValues_; std::string indentString_; int rightMargin_; std::string indentation_; CommentStyle::Enum cs_; std::string colonSymbol_; std::string nullSymbol_; std::string endingLineFeedSymbol_; bool addChildValues_ : 1; bool indented_ : 1; }; BuiltStyledStreamWriter::BuiltStyledStreamWriter( std::string const& indentation, CommentStyle::Enum cs, std::string const& colonSymbol, std::string const& nullSymbol, std::string const& endingLineFeedSymbol) : rightMargin_(74) , indentation_(indentation) , cs_(cs) , colonSymbol_(colonSymbol) , nullSymbol_(nullSymbol) , endingLineFeedSymbol_(endingLineFeedSymbol) , addChildValues_(false) , indented_(false) { } int BuiltStyledStreamWriter::write(Value const& root, std::ostream* sout) { sout_ = sout; addChildValues_ = false; indented_ = true; indentString_ = ""; writeCommentBeforeValue(root); if (!indented_) writeIndent(); indented_ = true; writeValue(root); writeCommentAfterValueOnSameLine(root); *sout_ << endingLineFeedSymbol_; sout_ = NULL; return 0; } void BuiltStyledStreamWriter::writeValue(Value const& value) { switch (value.type()) { case nullValue: pushValue(nullSymbol_); break; case intValue: pushValue(valueToString(value.asLargestInt())); break; case uintValue: pushValue(valueToString(value.asLargestUInt())); break; case realValue: pushValue(valueToString(value.asDouble())); break; case stringValue: { // Is NULL is possible for value.string_? char const* str; char const* end; bool ok = value.getString(&str, &end); if (ok) pushValue(valueToQuotedStringN(str, static_cast(end-str))); else pushValue(""); break; } case booleanValue: pushValue(valueToString(value.asBool())); break; case arrayValue: writeArrayValue(value); break; case objectValue: { Value::Members members(value.getMemberNames()); if (members.empty()) pushValue("{}"); else { writeWithIndent("{"); indent(); Value::Members::iterator it = members.begin(); for (;;) { std::string const& name = *it; Value const& childValue = value[name]; writeCommentBeforeValue(childValue); writeWithIndent(valueToQuotedStringN(name.data(), name.length())); *sout_ << colonSymbol_; writeValue(childValue); if (++it == members.end()) { writeCommentAfterValueOnSameLine(childValue); break; } *sout_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("}"); } } break; } } void BuiltStyledStreamWriter::writeArrayValue(Value const& value) { unsigned size = value.size(); if (size == 0) pushValue("[]"); else { bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value); if (isMultiLine) { writeWithIndent("["); indent(); bool hasChildValue = !childValues_.empty(); unsigned index = 0; for (;;) { Value const& childValue = value[index]; writeCommentBeforeValue(childValue); if (hasChildValue) writeWithIndent(childValues_[index]); else { if (!indented_) writeIndent(); indented_ = true; writeValue(childValue); indented_ = false; } if (++index == size) { writeCommentAfterValueOnSameLine(childValue); break; } *sout_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("]"); } else // output on a single line { assert(childValues_.size() == size); *sout_ << "["; if (!indentation_.empty()) *sout_ << " "; for (unsigned index = 0; index < size; ++index) { if (index > 0) *sout_ << ", "; *sout_ << childValues_[index]; } if (!indentation_.empty()) *sout_ << " "; *sout_ << "]"; } } } bool BuiltStyledStreamWriter::isMultineArray(Value const& value) { int size = value.size(); bool isMultiLine = size * 3 >= rightMargin_; childValues_.clear(); for (int index = 0; index < size && !isMultiLine; ++index) { Value const& childValue = value[index]; isMultiLine = isMultiLine || ((childValue.isArray() || childValue.isObject()) && childValue.size() > 0); } if (!isMultiLine) // check if line length > max line length { childValues_.reserve(size); addChildValues_ = true; int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' for (int index = 0; index < size; ++index) { if (hasCommentForValue(value[index])) { isMultiLine = true; } writeValue(value[index]); lineLength += int(childValues_[index].length()); } addChildValues_ = false; isMultiLine = isMultiLine || lineLength >= rightMargin_; } return isMultiLine; } void BuiltStyledStreamWriter::pushValue(std::string const& value) { if (addChildValues_) childValues_.push_back(value); else *sout_ << value; } void BuiltStyledStreamWriter::writeIndent() { // blep intended this to look at the so-far-written string // to determine whether we are already indented, but // with a stream we cannot do that. So we rely on some saved state. // The caller checks indented_. if (!indentation_.empty()) { // In this case, drop newlines too. *sout_ << '\n' << indentString_; } } void BuiltStyledStreamWriter::writeWithIndent(std::string const& value) { if (!indented_) writeIndent(); *sout_ << value; indented_ = false; } void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; } void BuiltStyledStreamWriter::unindent() { assert(indentString_.size() >= indentation_.size()); indentString_.resize(indentString_.size() - indentation_.size()); } void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) { if (cs_ == CommentStyle::None) return; if (!root.hasComment(commentBefore)) return; if (!indented_) writeIndent(); const std::string& comment = root.getComment(commentBefore); std::string::const_iterator iter = comment.begin(); while (iter != comment.end()) { *sout_ << *iter; if (*iter == '\n' && (iter != comment.end() && *(iter + 1) == '/')) // writeIndent(); // would write extra newline *sout_ << indentString_; ++iter; } indented_ = false; } void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) { if (cs_ == CommentStyle::None) return; if (root.hasComment(commentAfterOnSameLine)) *sout_ << " " + root.getComment(commentAfterOnSameLine); if (root.hasComment(commentAfter)) { writeIndent(); *sout_ << root.getComment(commentAfter); } } // static bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) { return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter); } /////////////// // StreamWriter StreamWriter::StreamWriter() : sout_(NULL) { } StreamWriter::~StreamWriter() { } StreamWriter::Factory::~Factory() {} StreamWriterBuilder::StreamWriterBuilder() { setDefaults(&settings_); } StreamWriterBuilder::~StreamWriterBuilder() {} StreamWriter* StreamWriterBuilder::newStreamWriter() const { std::string indentation = settings_["indentation"].asString(); std::string cs_str = settings_["commentStyle"].asString(); bool eyc = settings_["enableYAMLCompatibility"].asBool(); bool dnp = settings_["dropNullPlaceholders"].asBool(); CommentStyle::Enum cs = CommentStyle::All; if (cs_str == "All") { cs = CommentStyle::All; } else if (cs_str == "None") { cs = CommentStyle::None; } else { throwRuntimeError("commentStyle must be 'All' or 'None'"); } std::string colonSymbol = " : "; if (eyc) { colonSymbol = ": "; } else if (indentation.empty()) { colonSymbol = ":"; } std::string nullSymbol = "null"; if (dnp) { nullSymbol = ""; } std::string endingLineFeedSymbol = ""; return new BuiltStyledStreamWriter( indentation, cs, colonSymbol, nullSymbol, endingLineFeedSymbol); } static void getValidWriterKeys(std::set* valid_keys) { valid_keys->clear(); valid_keys->insert("indentation"); valid_keys->insert("commentStyle"); valid_keys->insert("enableYAMLCompatibility"); valid_keys->insert("dropNullPlaceholders"); } bool StreamWriterBuilder::validate(Json::Value* invalid) const { Json::Value my_invalid; if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL Json::Value& inv = *invalid; std::set valid_keys; getValidWriterKeys(&valid_keys); Value::Members keys = settings_.getMemberNames(); size_t n = keys.size(); for (size_t i = 0; i < n; ++i) { std::string const& key = keys[i]; if (valid_keys.find(key) == valid_keys.end()) { inv[key] = settings_[key]; } } return 0u == inv.size(); } Value& StreamWriterBuilder::operator[](std::string key) { return settings_[key]; } // static void StreamWriterBuilder::setDefaults(Json::Value* settings) { //! [StreamWriterBuilderDefaults] (*settings)["commentStyle"] = "All"; (*settings)["indentation"] = "\t"; (*settings)["enableYAMLCompatibility"] = false; (*settings)["dropNullPlaceholders"] = false; //! [StreamWriterBuilderDefaults] } std::string writeString(StreamWriter::Factory const& builder, Value const& root) { std::ostringstream sout; StreamWriterPtr const writer(builder.newStreamWriter()); writer->write(root, &sout); return sout.str(); } std::ostream& operator<<(std::ostream& sout, Value const& root) { StreamWriterBuilder builder; StreamWriterPtr const writer(builder.newStreamWriter()); writer->write(root, &sout); return sout; } } // namespace Json // ////////////////////////////////////////////////////////////////////// // End of content of file: src/lib_json/json_writer.cpp // ////////////////////////////////////////////////////////////////////// ================================================ FILE: src/common/json.h ================================================ /// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/). /// It is intended to be used with #include "json.h" // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: LICENSE // ////////////////////////////////////////////////////////////////////// /* The JsonCpp library's source code, including accompanying documentation, tests and demonstration applications, are licensed under the following conditions... The author (Baptiste Lepilleur) explicitly disclaims copyright in all jurisdictions which recognize such a disclaimer. In such jurisdictions, this software is released into the Public Domain. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is released under the terms of the MIT License (see below). In jurisdictions which recognize Public Domain property, the user of this software may choose to accept it either as 1) Public Domain, 2) under the conditions of the MIT License (see below), or 3) under the terms of dual Public Domain/MIT License conditions described here, as they choose. The MIT License is about as close to Public Domain as a license can get, and is described in clear, concise terms at: http://en.wikipedia.org/wiki/MIT_License The full text of the MIT License follows: ======================================================================== Copyright (c) 2007-2010 Baptiste Lepilleur 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. ======================================================================== (END LICENSE TEXT) The MIT license is compatible with both the GPL and commercial software, affording one all of the rights of Public Domain with the minor nuisance of being required to keep the above copyright notice and license text in the source code. Note also that by accepting the Public Domain "license" you can re-license your copy using whatever license you like. */ // ////////////////////////////////////////////////////////////////////// // End of content of file: LICENSE // ////////////////////////////////////////////////////////////////////// #ifndef JSON_AMALGATED_H_INCLUDED # define JSON_AMALGATED_H_INCLUDED /// If defined, indicates that the source file is amalgated /// to prevent private header inclusion. #define JSON_IS_AMALGAMATION // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: include/json/version.h // ////////////////////////////////////////////////////////////////////// // DO NOT EDIT. This file is generated by CMake from "version" // and "version.h.in" files. // Run CMake configure step to update it. #ifndef JSON_VERSION_H_INCLUDED # define JSON_VERSION_H_INCLUDED # define JSONCPP_VERSION_STRING "1.6.0" # define JSONCPP_VERSION_MAJOR 1 # define JSONCPP_VERSION_MINOR 6 # define JSONCPP_VERSION_PATCH 0 # define JSONCPP_VERSION_QUALIFIER # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8)) #endif // JSON_VERSION_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: include/json/version.h // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: include/json/config.h // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_CONFIG_H_INCLUDED #define JSON_CONFIG_H_INCLUDED /// If defined, indicates that json library is embedded in CppTL library. //# define JSON_IN_CPPTL 1 /// If defined, indicates that json may leverage CppTL library //# define JSON_USE_CPPTL 1 /// If defined, indicates that cpptl vector based map should be used instead of /// std::map /// as Value container. //# define JSON_USE_CPPTL_SMALLMAP 1 // If non-zero, the library uses exceptions to report bad input instead of C // assertion macros. The default is to use exceptions. #ifndef JSON_USE_EXCEPTION #define JSON_USE_EXCEPTION 1 #endif /// If defined, indicates that the target file is amalgated /// to prevent private header inclusion. /// Remarks: it is automatically defined in the generated amalgated header. // #define JSON_IS_AMALGAMATION #ifdef JSON_IN_CPPTL #include #ifndef JSON_USE_CPPTL #define JSON_USE_CPPTL 1 #endif #endif #ifdef JSON_IN_CPPTL #define JSON_API CPPTL_API #elif defined(JSON_DLL_BUILD) #if defined(_MSC_VER) #define JSON_API __declspec(dllexport) #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING #endif // if defined(_MSC_VER) #elif defined(JSON_DLL) #if defined(_MSC_VER) #define JSON_API __declspec(dllimport) #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING #endif // if defined(_MSC_VER) #endif // ifdef JSON_IN_CPPTL #if !defined(JSON_API) #define JSON_API #endif // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for // integer // Storages, and 64 bits integer support is disabled. // #define JSON_NO_INT64 1 #if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6 // Microsoft Visual Studio 6 only support conversion from __int64 to double // (no conversion from unsigned __int64). #define JSON_USE_INT64_DOUBLE_CONVERSION 1 // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255' // characters in the debug information) // All projects I've ever seen with VS6 were using this globally (not bothering // with pragma push/pop). #pragma warning(disable : 4786) #endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6 #if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008 /// Indicates that the following function is deprecated. #define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) #elif defined(__clang__) && defined(__has_feature) #if __has_feature(attribute_deprecated_with_message) #define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) #endif #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) #define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) #elif defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) #define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__)) #endif #if !defined(JSONCPP_DEPRECATED) #define JSONCPP_DEPRECATED(message) #endif // if !defined(JSONCPP_DEPRECATED) namespace Json { typedef int Int; typedef unsigned int UInt; #if defined(JSON_NO_INT64) typedef int LargestInt; typedef unsigned int LargestUInt; #undef JSON_HAS_INT64 #else // if defined(JSON_NO_INT64) // For Microsoft Visual use specific types as long long is not supported #if defined(_MSC_VER) // Microsoft Visual Studio typedef __int64 Int64; typedef unsigned __int64 UInt64; #else // if defined(_MSC_VER) // Other platforms, use long long typedef long long int Int64; typedef unsigned long long int UInt64; #endif // if defined(_MSC_VER) typedef Int64 LargestInt; typedef UInt64 LargestUInt; #define JSON_HAS_INT64 #endif // if defined(JSON_NO_INT64) } // end namespace Json #endif // JSON_CONFIG_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: include/json/config.h // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: include/json/forwards.h // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_FORWARDS_H_INCLUDED #define JSON_FORWARDS_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "config.h" #endif // if !defined(JSON_IS_AMALGAMATION) namespace Json { // writer.h class FastWriter; class StyledWriter; // reader.h class Reader; // features.h class Features; // value.h typedef unsigned int ArrayIndex; class StaticString; class Path; class PathArgument; class Value; class ValueIteratorBase; class ValueIterator; class ValueConstIterator; } // namespace Json #endif // JSON_FORWARDS_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: include/json/forwards.h // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: include/json/features.h // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef CPPTL_JSON_FEATURES_H_INCLUDED #define CPPTL_JSON_FEATURES_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "forwards.h" #endif // if !defined(JSON_IS_AMALGAMATION) namespace Json { /** \brief Configuration passed to reader and writer. * This configuration object can be used to force the Reader or Writer * to behave in a standard conforming way. */ class JSON_API Features { public: /** \brief A configuration that allows all features and assumes all strings * are UTF-8. * - C & C++ comments are allowed * - Root object can be any JSON value * - Assumes Value strings are encoded in UTF-8 */ static Features all(); /** \brief A configuration that is strictly compatible with the JSON * specification. * - Comments are forbidden. * - Root object must be either an array or an object value. * - Assumes Value strings are encoded in UTF-8 */ static Features strictMode(); /** \brief Initialize the configuration like JsonConfig::allFeatures; */ Features(); /// \c true if comments are allowed. Default: \c true. bool allowComments_; /// \c true if root must be either an array or an object value. Default: \c /// false. bool strictRoot_; /// \c true if dropped null placeholders are allowed. Default: \c false. bool allowDroppedNullPlaceholders_; /// \c true if numeric object key are allowed. Default: \c false. bool allowNumericKeys_; }; } // namespace Json #endif // CPPTL_JSON_FEATURES_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: include/json/features.h // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: include/json/value.h // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef CPPTL_JSON_H_INCLUDED #define CPPTL_JSON_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "forwards.h" #endif // if !defined(JSON_IS_AMALGAMATION) #include #include #include #ifndef JSON_USE_CPPTL_SMALLMAP #include #else #include #endif #ifdef JSON_USE_CPPTL #include #endif // Disable warning C4251: : needs to have dll-interface to // be used by... #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(push) #pragma warning(disable : 4251) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) /** \brief JSON (JavaScript Object Notation). */ namespace Json { /** Base class for all exceptions we throw. * * We use nothing but these internally. Of course, STL can throw others. */ class JSON_API Exception; /** Exceptions which the user cannot easily avoid. * * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input * * \remark derived from Json::Exception */ class JSON_API RuntimeError; /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros. * * These are precondition-violations (user bugs) and internal errors (our bugs). * * \remark derived from Json::Exception */ class JSON_API LogicError; /// used internally void throwRuntimeError(std::string const& msg); /// used internally void throwLogicError(std::string const& msg); /** \brief Type of the value held by a Value object. */ enum ValueType { nullValue = 0, ///< 'null' value intValue, ///< signed integer value uintValue, ///< unsigned integer value realValue, ///< double value stringValue, ///< UTF-8 string value booleanValue, ///< bool value arrayValue, ///< array value (ordered list) objectValue ///< object value (collection of name/value pairs). }; enum CommentPlacement { commentBefore = 0, ///< a comment placed on the line before a value commentAfterOnSameLine, ///< a comment just after a value on the same line commentAfter, ///< a comment on the line after a value (only make sense for /// root value) numberOfCommentPlacement }; //# ifdef JSON_USE_CPPTL // typedef CppTL::AnyEnumerator EnumMemberNames; // typedef CppTL::AnyEnumerator EnumValues; //# endif /** \brief Lightweight wrapper to tag static string. * * Value constructor and objectValue member assignement takes advantage of the * StaticString and avoid the cost of string duplication when storing the * string or the member name. * * Example of usage: * \code * Json::Value aValue( StaticString("some text") ); * Json::Value object; * static const StaticString code("code"); * object[code] = 1234; * \endcode */ class JSON_API StaticString { public: explicit StaticString(const char* czstring) : c_str_(czstring) {} operator const char*() const { return c_str_; } const char* c_str() const { return c_str_; } private: const char* c_str_; }; /** \brief Represents a JSON value. * * This class is a discriminated union wrapper that can represents a: * - signed integer [range: Value::minInt - Value::maxInt] * - unsigned integer (range: 0 - Value::maxUInt) * - double * - UTF-8 string * - boolean * - 'null' * - an ordered list of Value * - collection of name/value pairs (javascript object) * * The type of the held value is represented by a #ValueType and * can be obtained using type(). * * Values of an #objectValue or #arrayValue can be accessed using operator[]() * methods. * Non-const methods will automatically create the a #nullValue element * if it does not exist. * The sequence of an #arrayValue will be automatically resized and initialized * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. * * The get() methods can be used to obtain default value in the case the * required element does not exist. * * It is possible to iterate over the list of a #objectValue values using * the getMemberNames() method. * * \note #Value string-length fit in size_t, but keys must be < 2^30. * (The reason is an implementation detail.) A #CharReader will raise an * exception if a bound is exceeded to avoid security holes in your app, * but the Value API does *not* check bounds. That is the responsibility * of the caller. */ class JSON_API Value { friend class ValueIteratorBase; public: typedef std::vector Members; typedef ValueIterator iterator; typedef ValueConstIterator const_iterator; typedef Json::UInt UInt; typedef Json::Int Int; #if defined(JSON_HAS_INT64) typedef Json::UInt64 UInt64; typedef Json::Int64 Int64; #endif // defined(JSON_HAS_INT64) typedef Json::LargestInt LargestInt; typedef Json::LargestUInt LargestUInt; typedef Json::ArrayIndex ArrayIndex; static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value(). static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null /// Minimum signed integer value that can be stored in a Json::Value. static const LargestInt minLargestInt; /// Maximum signed integer value that can be stored in a Json::Value. static const LargestInt maxLargestInt; /// Maximum unsigned integer value that can be stored in a Json::Value. static const LargestUInt maxLargestUInt; /// Minimum signed int value that can be stored in a Json::Value. static const Int minInt; /// Maximum signed int value that can be stored in a Json::Value. static const Int maxInt; /// Maximum unsigned int value that can be stored in a Json::Value. static const UInt maxUInt; #if defined(JSON_HAS_INT64) /// Minimum signed 64 bits int value that can be stored in a Json::Value. static const Int64 minInt64; /// Maximum signed 64 bits int value that can be stored in a Json::Value. static const Int64 maxInt64; /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. static const UInt64 maxUInt64; #endif // defined(JSON_HAS_INT64) private: #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION class CZString { public: enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy }; CZString(ArrayIndex index); CZString(char const* str, unsigned length, DuplicationPolicy allocate); CZString(CZString const& other); ~CZString(); CZString& operator=(CZString other); bool operator<(CZString const& other) const; bool operator==(CZString const& other) const; ArrayIndex index() const; //const char* c_str() const; ///< \deprecated char const* data() const; unsigned length() const; bool isStaticString() const; private: void swap(CZString& other); struct StringStorage { DuplicationPolicy policy_: 2; unsigned length_: 30; // 1GB max }; char const* cstr_; // actually, a prefixed string, unless policy is noDup union { ArrayIndex index_; StringStorage storage_; }; }; public: #ifndef JSON_USE_CPPTL_SMALLMAP typedef std::map ObjectValues; #else typedef CppTL::SmallMap ObjectValues; #endif // ifndef JSON_USE_CPPTL_SMALLMAP #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION public: /** \brief Create a default Value of the given type. This is a very useful constructor. To create an empty array, pass arrayValue. To create an empty object, pass objectValue. Another Value can then be set to this one by assignment. This is useful since clear() and resize() will not alter types. Examples: \code Json::Value null_value; // null Json::Value arr_value(Json::arrayValue); // [] Json::Value obj_value(Json::objectValue); // {} \endcode */ Value(ValueType type = nullValue); Value(Int value); Value(UInt value); #if defined(JSON_HAS_INT64) Value(Int64 value); Value(UInt64 value); #endif // if defined(JSON_HAS_INT64) Value(double value); Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.) Value(const char* beginValue, const char* endValue); ///< Copy all, incl zeroes. /** \brief Constructs a value from a static string. * Like other value string constructor but do not duplicate the string for * internal storage. The given string must remain alive after the call to this * constructor. * \note This works only for null-terminated strings. (We cannot change the * size of this class, so we have nowhere to store the length, * which might be computed later for various operations.) * * Example of usage: * \code * static StaticString foo("some text"); * Json::Value aValue(foo); * \endcode */ Value(const StaticString& value); Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too. #ifdef JSON_USE_CPPTL Value(const CppTL::ConstString& value); #endif Value(bool value); /// Deep copy. Value(const Value& other); ~Value(); /// Deep copy, then swap(other). /// \note Over-write existing comments. To preserve comments, use #swapPayload(). Value& operator=(Value other); /// Swap everything. void swap(Value& other); /// Swap values but leave comments and target offsets in place. void swapPayload(Value& other); ValueType type() const; /// Compare payload only, not comments etc. bool operator<(const Value& other) const; bool operator<=(const Value& other) const; bool operator>=(const Value& other) const; bool operator>(const Value& other) const; bool operator==(const Value& other) const; bool operator!=(const Value& other) const; int compare(const Value& other) const; const char* asCString() const; ///< Embedded zeroes could cause you trouble! std::string asString() const; ///< Embedded zeroes are possible. /** Get raw char* of string-value. * \return false if !string. (Seg-fault if str or end are NULL.) */ bool getString( char const** str, char const** end) const; #ifdef JSON_USE_CPPTL CppTL::ConstString asConstString() const; #endif Int asInt() const; UInt asUInt() const; #if defined(JSON_HAS_INT64) Int64 asInt64() const; UInt64 asUInt64() const; #endif // if defined(JSON_HAS_INT64) LargestInt asLargestInt() const; LargestUInt asLargestUInt() const; float asFloat() const; double asDouble() const; bool asBool() const; bool isNull() const; bool isBool() const; bool isInt() const; bool isInt64() const; bool isUInt() const; bool isUInt64() const; bool isIntegral() const; bool isDouble() const; bool isNumeric() const; bool isString() const; bool isArray() const; bool isObject() const; bool isConvertibleTo(ValueType other) const; /// Number of values in array or object ArrayIndex size() const; /// \brief Return true if empty array, empty object, or null; /// otherwise, false. bool empty() const; /// Return isNull() bool operator!() const; /// Remove all object members and array elements. /// \pre type() is arrayValue, objectValue, or nullValue /// \post type() is unchanged void clear(); /// Resize the array to size elements. /// New elements are initialized to null. /// May only be called on nullValue or arrayValue. /// \pre type() is arrayValue or nullValue /// \post type() is arrayValue void resize(ArrayIndex size); /// Access an array element (zero based index ). /// If the array contains less than index element, then null value are /// inserted /// in the array so that its size is index+1. /// (You may need to say 'value[0u]' to get your compiler to distinguish /// this from the operator[] which takes a string.) Value& operator[](ArrayIndex index); /// Access an array element (zero based index ). /// If the array contains less than index element, then null value are /// inserted /// in the array so that its size is index+1. /// (You may need to say 'value[0u]' to get your compiler to distinguish /// this from the operator[] which takes a string.) Value& operator[](int index); /// Access an array element (zero based index ) /// (You may need to say 'value[0u]' to get your compiler to distinguish /// this from the operator[] which takes a string.) const Value& operator[](ArrayIndex index) const; /// Access an array element (zero based index ) /// (You may need to say 'value[0u]' to get your compiler to distinguish /// this from the operator[] which takes a string.) const Value& operator[](int index) const; /// If the array contains at least index+1 elements, returns the element /// value, /// otherwise returns defaultValue. Value get(ArrayIndex index, const Value& defaultValue) const; /// Return true if index < size(). bool isValidIndex(ArrayIndex index) const; /// \brief Append value to array at the end. /// /// Equivalent to jsonvalue[jsonvalue.size()] = value; Value& append(const Value& value); /// Access an object value by name, create a null member if it does not exist. /// \note Because of our implementation, keys are limited to 2^30 -1 chars. /// Exceeding that will cause an exception. Value& operator[](const char* key); /// Access an object value by name, returns null if there is no member with /// that name. const Value& operator[](const char* key) const; /// Access an object value by name, create a null member if it does not exist. /// \param key may contain embedded nulls. Value& operator[](const std::string& key); /// Access an object value by name, returns null if there is no member with /// that name. /// \param key may contain embedded nulls. const Value& operator[](const std::string& key) const; /** \brief Access an object value by name, create a null member if it does not exist. * If the object has no entry for that name, then the member name used to store * the new entry is not duplicated. * Example of use: * \code * Json::Value object; * static const StaticString code("code"); * object[code] = 1234; * \endcode */ Value& operator[](const StaticString& key); #ifdef JSON_USE_CPPTL /// Access an object value by name, create a null member if it does not exist. Value& operator[](const CppTL::ConstString& key); /// Access an object value by name, returns null if there is no member with /// that name. const Value& operator[](const CppTL::ConstString& key) const; #endif /// Return the member named key if it exist, defaultValue otherwise. /// \note deep copy Value get(const char* key, const Value& defaultValue) const; /// Return the member named key if it exist, defaultValue otherwise. /// \note deep copy /// \param key may contain embedded nulls. Value get(const char* key, const char* end, const Value& defaultValue) const; /// Return the member named key if it exist, defaultValue otherwise. /// \note deep copy /// \param key may contain embedded nulls. Value get(const std::string& key, const Value& defaultValue) const; #ifdef JSON_USE_CPPTL /// Return the member named key if it exist, defaultValue otherwise. /// \note deep copy Value get(const CppTL::ConstString& key, const Value& defaultValue) const; #endif /// Most general and efficient version of isMember()const, get()const, /// and operator[]const /// \note As stated elsewhere, behavior is undefined if (end-key) >= 2^30 Value const* find(char const* key, char const* end) const; /// Most general and efficient version of object-mutators. /// \note As stated elsewhere, behavior is undefined if (end-key) >= 2^30 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue. Value const* demand(char const* key, char const* end); /// \brief Remove and return the named member. /// /// Do nothing if it did not exist. /// \return the removed Value, or null. /// \pre type() is objectValue or nullValue /// \post type() is unchanged /// \deprecated Value removeMember(const char* key); /// Same as removeMember(const char*) /// \param key may contain embedded nulls. /// \deprecated Value removeMember(const std::string& key); /// Same as removeMember(const char* key, const char* end, Value* removed), /// but 'key' is null-terminated. bool removeMember(const char* key, Value* removed); /** \brief Remove the named map member. Update 'removed' iff removed. \param key may contain embedded nulls. \return true iff removed (no exceptions) */ bool removeMember(std::string const& key, Value* removed); /// Same as removeMember(std::string const& key, Value* removed) bool removeMember(const char* key, const char* end, Value* removed); /** \brief Remove the indexed array element. O(n) expensive operations. Update 'removed' iff removed. \return true iff removed (no exceptions) */ bool removeIndex(ArrayIndex i, Value* removed); /// Return true if the object has a member named key. /// \note 'key' must be null-terminated. bool isMember(const char* key) const; /// Return true if the object has a member named key. /// \param key may contain embedded nulls. bool isMember(const std::string& key) const; /// Same as isMember(std::string const& key)const bool isMember(const char* key, const char* end) const; #ifdef JSON_USE_CPPTL /// Return true if the object has a member named key. bool isMember(const CppTL::ConstString& key) const; #endif /// \brief Return a list of the member names. /// /// If null, return an empty list. /// \pre type() is objectValue or nullValue /// \post if type() was nullValue, it remains nullValue Members getMemberNames() const; //# ifdef JSON_USE_CPPTL // EnumMemberNames enumMemberNames() const; // EnumValues enumValues() const; //# endif /// \deprecated Always pass len. void setComment(const char* comment, CommentPlacement placement); /// Comments must be //... or /* ... */ void setComment(const char* comment, size_t len, CommentPlacement placement); /// Comments must be //... or /* ... */ void setComment(const std::string& comment, CommentPlacement placement); bool hasComment(CommentPlacement placement) const; /// Include delimiters and embedded newlines. std::string getComment(CommentPlacement placement) const; std::string toStyledString() const; const_iterator begin() const; const_iterator end() const; iterator begin(); iterator end(); // Accessors for the [start, limit) range of bytes within the JSON text from // which this value was parsed, if any. void setOffsetStart(size_t start); void setOffsetLimit(size_t limit); size_t getOffsetStart() const; size_t getOffsetLimit() const; private: void initBasic(ValueType type, bool allocated = false); Value& resolveReference(const char* key); Value& resolveReference(const char* key, const char* end); struct CommentInfo { CommentInfo(); ~CommentInfo(); void setComment(const char* text, size_t len); char* comment_; }; // struct MemberNamesTransform //{ // typedef const char *result_type; // const char *operator()( const CZString &name ) const // { // return name.c_str(); // } //}; union ValueHolder { LargestInt int_; LargestUInt uint_; double real_; bool bool_; char* string_; // actually ptr to unsigned, followed by str, unless !allocated_ ObjectValues* map_; } value_; ValueType type_ : 8; unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. // If not allocated_, string_ must be null-terminated. CommentInfo* comments_; // [start, limit) byte offsets in the target JSON text from which this Value // was extracted. size_t start_; size_t limit_; }; /** \brief Experimental and untested: represents an element of the "path" to * access a node. */ class JSON_API PathArgument { public: friend class Path; PathArgument(); PathArgument(ArrayIndex index); PathArgument(const char* key); PathArgument(const std::string& key); private: enum Kind { kindNone = 0, kindIndex, kindKey }; std::string key_; ArrayIndex index_; Kind kind_; }; /** \brief Experimental and untested: represents a "path" to access a node. * * Syntax: * - "." => root node * - ".[n]" => elements at index 'n' of root node (an array value) * - ".name" => member named 'name' of root node (an object value) * - ".name1.name2.name3" * - ".[0][1][2].name1[3]" * - ".%" => member name is provided as parameter * - ".[%]" => index is provied as parameter */ class JSON_API Path { public: Path(const std::string& path, const PathArgument& a1 = PathArgument(), const PathArgument& a2 = PathArgument(), const PathArgument& a3 = PathArgument(), const PathArgument& a4 = PathArgument(), const PathArgument& a5 = PathArgument()); const Value& resolve(const Value& root) const; Value resolve(const Value& root, const Value& defaultValue) const; /// Creates the "path" to access the specified node and returns a reference on /// the node. Value& make(Value& root) const; private: typedef std::vector InArgs; typedef std::vector Args; void makePath(const std::string& path, const InArgs& in); void addPathInArg(const std::string& path, const InArgs& in, InArgs::const_iterator& itInArg, PathArgument::Kind kind); void invalidPath(const std::string& path, int location); Args args_; }; /** \brief base class for Value iterators. * */ class JSON_API ValueIteratorBase { public: typedef std::bidirectional_iterator_tag iterator_category; typedef unsigned int size_t; typedef int difference_type; typedef ValueIteratorBase SelfType; ValueIteratorBase(); explicit ValueIteratorBase(const Value::ObjectValues::iterator& current); bool operator==(const SelfType& other) const { return isEqual(other); } bool operator!=(const SelfType& other) const { return !isEqual(other); } difference_type operator-(const SelfType& other) const { return other.computeDistance(*this); } /// Return either the index or the member name of the referenced value as a /// Value. Value key() const; /// Return the index of the referenced Value, or -1 if it is not an arrayValue. UInt index() const; /// Return the member name of the referenced Value, or "" if it is not an /// objectValue. /// \note Avoid `c_str()` on result, as embedded zeroes are possible. std::string name() const; /// Return the member name of the referenced Value. "" if it is not an /// objectValue. /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls. JSONCPP_DEPRECATED("Use `key = name();` instead.") char const* memberName() const; /// Return the member name of the referenced Value, or NULL if it is not an /// objectValue. /// \note Better version than memberName(). Allows embedded nulls. char const* memberName(char const** end) const; protected: Value& deref() const; void increment(); void decrement(); difference_type computeDistance(const SelfType& other) const; bool isEqual(const SelfType& other) const; void copy(const SelfType& other); private: Value::ObjectValues::iterator current_; // Indicates that iterator is for a null value. bool isNull_; }; /** \brief const iterator for object and array value. * */ class JSON_API ValueConstIterator : public ValueIteratorBase { friend class Value; public: typedef const Value value_type; //typedef unsigned int size_t; //typedef int difference_type; typedef const Value& reference; typedef const Value* pointer; typedef ValueConstIterator SelfType; ValueConstIterator(); private: /*! \internal Use by Value to create an iterator. */ explicit ValueConstIterator(const Value::ObjectValues::iterator& current); public: SelfType& operator=(const ValueIteratorBase& other); SelfType operator++(int) { SelfType temp(*this); ++*this; return temp; } SelfType operator--(int) { SelfType temp(*this); --*this; return temp; } SelfType& operator--() { decrement(); return *this; } SelfType& operator++() { increment(); return *this; } reference operator*() const { return deref(); } pointer operator->() const { return &deref(); } }; /** \brief Iterator for object and array value. */ class JSON_API ValueIterator : public ValueIteratorBase { friend class Value; public: typedef Value value_type; typedef unsigned int size_t; typedef int difference_type; typedef Value& reference; typedef Value* pointer; typedef ValueIterator SelfType; ValueIterator(); ValueIterator(const ValueConstIterator& other); ValueIterator(const ValueIterator& other); private: /*! \internal Use by Value to create an iterator. */ explicit ValueIterator(const Value::ObjectValues::iterator& current); public: SelfType& operator=(const SelfType& other); SelfType operator++(int) { SelfType temp(*this); ++*this; return temp; } SelfType operator--(int) { SelfType temp(*this); --*this; return temp; } SelfType& operator--() { decrement(); return *this; } SelfType& operator++() { increment(); return *this; } reference operator*() const { return deref(); } pointer operator->() const { return &deref(); } }; } // namespace Json namespace std { /// Specialize std::swap() for Json::Value. template<> inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); } } #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(pop) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // CPPTL_JSON_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: include/json/value.h // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: include/json/reader.h // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef CPPTL_JSON_READER_H_INCLUDED #define CPPTL_JSON_READER_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "features.h" #include "value.h" #endif // if !defined(JSON_IS_AMALGAMATION) #include #include #include #include #include // Disable warning C4251: : needs to have dll-interface to // be used by... #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(push) #pragma warning(disable : 4251) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) namespace Json { /** \brief Unserialize a JSON document into a *Value. * * \deprecated Use CharReader and CharReaderBuilder. */ class JSON_API Reader { public: typedef char Char; typedef const Char* Location; /** \brief An error tagged with where in the JSON text it was encountered. * * The offsets give the [start, limit) range of bytes within the text. Note * that this is bytes, not codepoints. * */ struct StructuredError { size_t offset_start; size_t offset_limit; std::string message; }; /** \brief Constructs a Reader allowing all features * for parsing. */ Reader(); /** \brief Constructs a Reader allowing the specified feature set * for parsing. */ Reader(const Features& features); /** \brief Read a Value from a JSON * document. * \param document UTF-8 encoded string containing the document to read. * \param root [out] Contains the root value of the document if it was * successfully parsed. * \param collectComments \c true to collect comment and allow writing them * back during * serialization, \c false to discard comments. * This parameter is ignored if * Features::allowComments_ * is \c false. * \return \c true if the document was successfully parsed, \c false if an * error occurred. */ bool parse(const std::string& document, Value& root, bool collectComments = true); /** \brief Read a Value from a JSON document. * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the document to read. * \param endDoc Pointer on the end of the UTF-8 encoded string of the document to read. * Must be >= beginDoc. * \param root [out] Contains the root value of the document if it was * successfully parsed. * \param collectComments \c true to collect comment and allow writing them back during * serialization, \c false to discard comments. * This parameter is ignored if Features::allowComments_ * is \c false. * \return \c true if the document was successfully parsed, \c false if an error occurred. */ bool parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments = true); /// \brief Parse from input stream. /// \see Json::operator>>(std::istream&, Json::Value&). bool parse(std::istream& is, Value& root, bool collectComments = true); /** \brief Returns a user friendly string that list errors in the parsed * document. * \return Formatted error message with the list of errors with their location * in * the parsed document. An empty string is returned if no error * occurred * during parsing. * \deprecated Use getFormattedErrorMessages() instead (typo fix). */ JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.") std::string getFormatedErrorMessages() const; /** \brief Returns a user friendly string that list errors in the parsed * document. * \return Formatted error message with the list of errors with their location * in * the parsed document. An empty string is returned if no error * occurred * during parsing. */ std::string getFormattedErrorMessages() const; /** \brief Returns a vector of structured erros encounted while parsing. * \return A (possibly empty) vector of StructuredError objects. Currently * only one error can be returned, but the caller should tolerate * multiple * errors. This can occur if the parser recovers from a non-fatal * parse error and then encounters additional errors. */ std::vector getStructuredErrors() const; /** \brief Add a semantic error message. * \param value JSON Value location associated with the error * \param message The error message. * \return \c true if the error was successfully added, \c false if the * Value offset exceeds the document size. */ bool pushError(const Value& value, const std::string& message); /** \brief Add a semantic error message with extra context. * \param value JSON Value location associated with the error * \param message The error message. * \param extra Additional JSON Value location to contextualize the error * \return \c true if the error was successfully added, \c false if either * Value offset exceeds the document size. */ bool pushError(const Value& value, const std::string& message, const Value& extra); /** \brief Return whether there are any errors. * \return \c true if there are no errors to report \c false if * errors have occurred. */ bool good() const; private: enum TokenType { tokenEndOfStream = 0, tokenObjectBegin, tokenObjectEnd, tokenArrayBegin, tokenArrayEnd, tokenString, tokenNumber, tokenTrue, tokenFalse, tokenNull, tokenArraySeparator, tokenMemberSeparator, tokenComment, tokenError }; class Token { public: TokenType type_; Location start_; Location end_; }; class ErrorInfo { public: Token token_; std::string message_; Location extra_; }; typedef std::deque Errors; bool readToken(Token& token); void skipSpaces(); bool match(Location pattern, int patternLength); bool readComment(); bool readCStyleComment(); bool readCppStyleComment(); bool readString(); void readNumber(); bool readValue(); bool readObject(Token& token); bool readArray(Token& token); bool decodeNumber(Token& token); bool decodeNumber(Token& token, Value& decoded); bool decodeString(Token& token); bool decodeString(Token& token, std::string& decoded); bool decodeDouble(Token& token); bool decodeDouble(Token& token, Value& decoded); bool decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode); bool decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode); bool addError(const std::string& message, Token& token, Location extra = 0); bool recoverFromError(TokenType skipUntilToken); bool addErrorAndRecover(const std::string& message, Token& token, TokenType skipUntilToken); void skipUntilSpace(); Value& currentValue(); Char getNextChar(); void getLocationLineAndColumn(Location location, int& line, int& column) const; std::string getLocationLineAndColumn(Location location) const; void addComment(Location begin, Location end, CommentPlacement placement); void skipCommentTokens(Token& token); typedef std::stack Nodes; Nodes nodes_; Errors errors_; std::string document_; Location begin_; Location end_; Location current_; Location lastValueEnd_; Value* lastValue_; std::string commentsBefore_; Features features_; bool collectComments_; }; // Reader /** Interface for reading JSON from a char array. */ class JSON_API CharReader { public: virtual ~CharReader() {} /** \brief Read a Value from a JSON document. * The document must be a UTF-8 encoded string containing the document to read. * * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the document to read. * \param endDoc Pointer on the end of the UTF-8 encoded string of the document to read. * Must be >= beginDoc. * \param root [out] Contains the root value of the document if it was * successfully parsed. * \param errs [out] Formatted error messages (if not NULL) * a user friendly string that lists errors in the parsed * document. * \return \c true if the document was successfully parsed, \c false if an error occurred. */ virtual bool parse( char const* beginDoc, char const* endDoc, Value* root, std::string* errs) = 0; class Factory { public: virtual ~Factory() {} /** \brief Allocate a CharReader via operator new(). * \throw std::exception if something goes wrong (e.g. invalid settings) */ virtual CharReader* newCharReader() const = 0; }; // Factory }; // CharReader /** \brief Build a CharReader implementation. Usage: \code using namespace Json; CharReaderBuilder builder; builder["collectComments"] = false; Value value; std::string errs; bool ok = parseFromStream(builder, std::cin, &value, &errs); \endcode */ class JSON_API CharReaderBuilder : public CharReader::Factory { public: // Note: We use a Json::Value so that we can add data-members to this class // without a major version bump. /** Configuration of this builder. These are case-sensitive. Available settings (case-sensitive): - `"collectComments": false or true` - true to collect comment and allow writing them back during serialization, false to discard comments. This parameter is ignored if allowComments is false. - `"allowComments": false or true` - true if comments are allowed. - `"strictRoot": false or true` - true if root must be either an array or an object value - `"allowDroppedNullPlaceholders": false or true` - true if dropped null placeholders are allowed. (See StreamWriterBuilder.) - `"allowNumericKeys": false or true` - true if numeric object keys are allowed. - `"allowSingleQuotes": false or true` - true if '' are allowed for strings (both keys and values) - `"stackLimit": integer` - Exceeding stackLimit (recursive depth of `readValue()`) will cause an exception. - This is a security issue (seg-faults caused by deeply nested JSON), so the default is low. - `"failIfExtra": false or true` - If true, `parse()` returns false when extra non-whitespace trails the JSON value in the input string. - `"rejectDupKeys": false or true` - If true, `parse()` returns false when a key is duplicated within an object. You can examine 'settings_` yourself to see the defaults. You can also write and read them just like any JSON Value. \sa setDefaults() */ Json::Value settings_; CharReaderBuilder(); virtual ~CharReaderBuilder(); virtual CharReader* newCharReader() const; /** \return true if 'settings' are legal and consistent; * otherwise, indicate bad settings via 'invalid'. */ bool validate(Json::Value* invalid) const; /** A simple way to update a specific setting. */ Value& operator[](std::string key); /** Called by ctor, but you can use this to reset settings_. * \pre 'settings' != NULL (but Json::null is fine) * \remark Defaults: * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode */ static void setDefaults(Json::Value* settings); /** Same as old Features::strictMode(). * \pre 'settings' != NULL (but Json::null is fine) * \remark Defaults: * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults */ static void strictMode(Json::Value* settings); }; /** Consume entire stream and use its begin/end. * Someday we might have a real StreamReader, but for now this * is convenient. */ bool JSON_API parseFromStream( CharReader::Factory const&, std::istream&, Value* root, std::string* errs); /** \brief Read from 'sin' into 'root'. Always keep comments from the input JSON. This can be used to read a file into a particular sub-object. For example: \code Json::Value root; cin >> root["dir"]["file"]; cout << root; \endcode Result: \verbatim { "dir": { "file": { // The input stream JSON would be nested here. } } } \endverbatim \throw std::exception on parse error. \see Json::operator<<() */ JSON_API std::istream& operator>>(std::istream&, Value&); } // namespace Json #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(pop) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // CPPTL_JSON_READER_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: include/json/reader.h // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: include/json/writer.h // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_WRITER_H_INCLUDED #define JSON_WRITER_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "value.h" #endif // if !defined(JSON_IS_AMALGAMATION) #include #include #include // Disable warning C4251: : needs to have dll-interface to // be used by... #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(push) #pragma warning(disable : 4251) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) namespace Json { class Value; /** Usage: \code using namespace Json; void writeToStdout(StreamWriter::Factory const& factory, Value const& value) { std::unique_ptr const writer( factory.newStreamWriter()); writer->write(value, &std::cout); std::cout << std::endl; // add lf and flush } \endcode */ class JSON_API StreamWriter { protected: std::ostream* sout_; // not owned; will not delete public: StreamWriter(); virtual ~StreamWriter(); /** Write Value into document as configured in sub-class. Do not take ownership of sout, but maintain a reference during function. \pre sout != NULL \return zero on success (For now, we always return zero, so check the stream instead.) \throw std::exception possibly, depending on configuration */ virtual int write(Value const& root, std::ostream* sout) = 0; /** \brief A simple abstract factory. */ class JSON_API Factory { public: virtual ~Factory(); /** \brief Allocate a CharReader via operator new(). * \throw std::exception if something goes wrong (e.g. invalid settings) */ virtual StreamWriter* newStreamWriter() const = 0; }; // Factory }; // StreamWriter /** \brief Write into stringstream, then return string, for convenience. * A StreamWriter will be created from the factory, used, and then deleted. */ std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root); /** \brief Build a StreamWriter implementation. Usage: \code using namespace Json; Value value = ...; StreamWriterBuilder builder; builder["commentStyle"] = "None"; builder["indentation"] = " "; // or whatever you like std::unique_ptr writer( builder.newStreamWriter()); writer->write(value, &std::cout); std::cout << std::endl; // add lf and flush \endcode */ class JSON_API StreamWriterBuilder : public StreamWriter::Factory { public: // Note: We use a Json::Value so that we can add data-members to this class // without a major version bump. /** Configuration of this builder. Available settings (case-sensitive): - "commentStyle": "None" or "All" - "indentation": "" - "enableYAMLCompatibility": false or true - slightly change the whitespace around colons - "dropNullPlaceholders": false or true - Drop the "null" string from the writer's output for nullValues. Strictly speaking, this is not valid JSON. But when the output is being fed to a browser's Javascript, it makes for smaller output and the browser can handle the output just fine. You can examine 'settings_` yourself to see the defaults. You can also write and read them just like any JSON Value. \sa setDefaults() */ Json::Value settings_; StreamWriterBuilder(); virtual ~StreamWriterBuilder(); /** * \throw std::exception if something goes wrong (e.g. invalid settings) */ virtual StreamWriter* newStreamWriter() const; /** \return true if 'settings' are legal and consistent; * otherwise, indicate bad settings via 'invalid'. */ bool validate(Json::Value* invalid) const; /** A simple way to update a specific setting. */ Value& operator[](std::string key); /** Called by ctor, but you can use this to reset settings_. * \pre 'settings' != NULL (but Json::null is fine) * \remark Defaults: * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults */ static void setDefaults(Json::Value* settings); }; /** \brief Abstract class for writers. * \deprecated Use StreamWriter. (And really, this is an implementation detail.) */ class JSON_API Writer { public: virtual ~Writer(); virtual std::string write(const Value& root) = 0; }; /** \brief Outputs a Value in JSON format *without formatting (not human friendly). * * The JSON document is written in a single line. It is not intended for 'human' *consumption, * but may be usefull to support feature such as RPC where bandwith is limited. * \sa Reader, Value * \deprecated Use StreamWriterBuilder. */ class JSON_API FastWriter : public Writer { public: FastWriter(); virtual ~FastWriter() {} void enableYAMLCompatibility(); /** \brief Drop the "null" string from the writer's output for nullValues. * Strictly speaking, this is not valid JSON. But when the output is being * fed to a browser's Javascript, it makes for smaller output and the * browser can handle the output just fine. */ void dropNullPlaceholders(); void omitEndingLineFeed(); public: // overridden from Writer virtual std::string write(const Value& root); private: void writeValue(const Value& value); std::string document_; bool yamlCompatiblityEnabled_; bool dropNullPlaceholders_; bool omitEndingLineFeed_; }; /** \brief Writes a Value in JSON format in a *human friendly way. * * The rules for line break and indent are as follow: * - Object value: * - if empty then print {} without indent and line break * - if not empty the print '{', line break & indent, print one value per *line * and then unindent and line break and print '}'. * - Array value: * - if empty then print [] without indent and line break * - if the array contains no object value, empty array or some other value *types, * and all the values fit on one lines, then print the array on a single *line. * - otherwise, it the values do not fit on one line, or the array contains * object or non empty array, then print one value per line. * * If the Value have comments then they are outputed according to their *#CommentPlacement. * * \sa Reader, Value, Value::setComment() * \deprecated Use StreamWriterBuilder. */ class JSON_API StyledWriter : public Writer { public: StyledWriter(); virtual ~StyledWriter() {} public: // overridden from Writer /** \brief Serialize a Value in JSON format. * \param root Value to serialize. * \return String containing the JSON document that represents the root value. */ virtual std::string write(const Value& root); private: void writeValue(const Value& value); void writeArrayValue(const Value& value); bool isMultineArray(const Value& value); void pushValue(const std::string& value); void writeIndent(); void writeWithIndent(const std::string& value); void indent(); void unindent(); void writeCommentBeforeValue(const Value& root); void writeCommentAfterValueOnSameLine(const Value& root); bool hasCommentForValue(const Value& value); static std::string normalizeEOL(const std::string& text); typedef std::vector ChildValues; ChildValues childValues_; std::string document_; std::string indentString_; int rightMargin_; int indentSize_; bool addChildValues_; }; /** \brief Writes a Value in JSON format in a human friendly way, to a stream rather than to a string. * * The rules for line break and indent are as follow: * - Object value: * - if empty then print {} without indent and line break * - if not empty the print '{', line break & indent, print one value per line * and then unindent and line break and print '}'. * - Array value: * - if empty then print [] without indent and line break * - if the array contains no object value, empty array or some other value types, * and all the values fit on one lines, then print the array on a single line. * - otherwise, it the values do not fit on one line, or the array contains * object or non empty array, then print one value per line. * * If the Value have comments then they are outputed according to their #CommentPlacement. * * \param indentation Each level will be indented by this amount extra. * \sa Reader, Value, Value::setComment() * \deprecated Use StreamWriterBuilder. */ class JSON_API StyledStreamWriter { public: StyledStreamWriter(std::string indentation = "\t"); ~StyledStreamWriter() {} public: /** \brief Serialize a Value in JSON format. * \param out Stream to write to. (Can be ostringstream, e.g.) * \param root Value to serialize. * \note There is no point in deriving from Writer, since write() should not * return a value. */ void write(std::ostream& out, const Value& root); private: void writeValue(const Value& value); void writeArrayValue(const Value& value); bool isMultineArray(const Value& value); void pushValue(const std::string& value); void writeIndent(); void writeWithIndent(const std::string& value); void indent(); void unindent(); void writeCommentBeforeValue(const Value& root); void writeCommentAfterValueOnSameLine(const Value& root); bool hasCommentForValue(const Value& value); static std::string normalizeEOL(const std::string& text); typedef std::vector ChildValues; ChildValues childValues_; std::ostream* document_; std::string indentString_; int rightMargin_; std::string indentation_; bool addChildValues_ : 1; bool indented_ : 1; }; #if defined(JSON_HAS_INT64) std::string JSON_API valueToString(Int value); std::string JSON_API valueToString(UInt value); #endif // if defined(JSON_HAS_INT64) std::string JSON_API valueToString(LargestInt value); std::string JSON_API valueToString(LargestUInt value); std::string JSON_API valueToString(double value); std::string JSON_API valueToString(bool value); std::string JSON_API valueToQuotedString(const char* value); /// \brief Output using the StyledStreamWriter. /// \see Json::operator>>() JSON_API std::ostream& operator<<(std::ostream&, const Value& root); } // namespace Json #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(pop) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // JSON_WRITER_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: include/json/writer.h // ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// // Beginning of content of file: include/json/assertions.h // ////////////////////////////////////////////////////////////////////// // Copyright 2007-2010 Baptiste Lepilleur // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED #define CPPTL_JSON_ASSERTIONS_H_INCLUDED #include #include #if !defined(JSON_IS_AMALGAMATION) #include "config.h" #endif // if !defined(JSON_IS_AMALGAMATION) /** It should not be possible for a maliciously designed file to * cause an abort() or seg-fault, so these macros are used only * for pre-condition violations and internal logic errors. */ #if JSON_USE_EXCEPTION // @todo <= add detail about condition in exception # define JSON_ASSERT(condition) \ {if (!(condition)) {Json::throwLogicError( "assert json failed" );}} # define JSON_FAIL_MESSAGE(message) \ { \ std::ostringstream oss; oss << message; \ Json::throwLogicError(oss.str()); \ abort(); \ } #else // JSON_USE_EXCEPTION # define JSON_ASSERT(condition) assert(condition) // The call to assert() will show the failure message in debug builds. In // release builds we abort, for a core-dump or debugger. # define JSON_FAIL_MESSAGE(message) \ { \ std::ostringstream oss; oss << message; \ assert(false && oss.str().c_str()); \ abort(); \ } #endif #define JSON_ASSERT_MESSAGE(condition, message) \ if (!(condition)) { \ JSON_FAIL_MESSAGE(message); \ } #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED // ////////////////////////////////////////////////////////////////////// // End of content of file: include/json/assertions.h // ////////////////////////////////////////////////////////////////////// #endif //ifndef JSON_AMALGATED_H_INCLUDED ================================================ FILE: src/common/logger.cpp ================================================ #include "logger.h" #include #include #include #include #include #include #include #include "common/types.h" namespace Airwave { static int fd = -1; static std::string id; static std::vector buffer; static LogLevel defaultLevel = LogLevel::kDebug; bool loggerInit(const std::string& socketPath, const std::string& senderId) { fd = socket(AF_UNIX, SOCK_DGRAM, 0); if(fd < 0) return false; sockaddr_un address; memset(&address, 0, sizeof(sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, socketPath.c_str()); if(connect(fd, reinterpret_cast(&address), sizeof(sockaddr_un)) != 0) { close(fd); fd = -1; return false; } id = senderId; // NOTE The buffer size is hardcoded, increase it if necessary. buffer.resize(1024); return true; } void loggerFree() { if(fd >= 0) { close(fd); id.clear(); } } LogLevel loggerLogLevel() { return defaultLevel; } void loggerSetLogLevel(LogLevel level) { defaultLevel = level; } std::string loggerSenderId() { return id; } void loggerSetSenderId(const std::string& senderId) { id = senderId; } void loggerMessage(LogLevel level, const char* format, ...) { if(level > defaultLevel) return; if(fd == -1) return; timespec tm; clock_gettime(CLOCK_REALTIME, &tm); u64* timestamp = reinterpret_cast(buffer.data()); *timestamp = (static_cast(tm.tv_sec) << 32) + tm.tv_nsec; char* output = buffer.data() + sizeof(u64); output = std::copy(id.begin(), id.end(), output); *output = '\x01'; ++output; uint count = output - buffer.data(); va_list args; va_start(args, format); count += std::vsnprintf(output, buffer.size() - count, format, args) + 1; va_end(args); send(fd, buffer.data(), count, 0); } } // namespace Airwave ================================================ FILE: src/common/logger.h ================================================ #ifndef COMMON_LOGGER_H #define COMMON_LOGGER_H #include #define FLOOD(format, ...) \ Airwave::loggerMessage(Airwave::LogLevel::kFlood, format, ##__VA_ARGS__) #define DEBUG(format, ...) \ Airwave::loggerMessage(Airwave::LogLevel::kDebug, format, ##__VA_ARGS__) #define TRACE(format, ...) \ Airwave::loggerMessage(Airwave::LogLevel::kTrace, format, ##__VA_ARGS__) // Workaround for wingdi.h #ifdef ERROR #undef ERROR #endif #define ERROR(format, ...) \ Airwave::loggerMessage(Airwave::LogLevel::kError, format, ##__VA_ARGS__) namespace Airwave { enum class LogLevel { kDefault = -1, kQuiet, kError, kTrace, kDebug, kFlood }; bool loggerInit(const std::string& socketPath, const std::string& senderId); void loggerFree(); LogLevel loggerLogLevel(); void loggerSetLogLevel(LogLevel level); std::string loggerSenderId(); void loggerSetSenderId(const std::string& senderId); void loggerMessage(LogLevel level, const char* format, ...); } // namespace Airwave #endif // COMMON_LOGGER_H ================================================ FILE: src/common/moduleinfo.cpp ================================================ #include "moduleinfo.h" ModuleInfo::ModuleInfo() : isInitialized_(false) { magic_ = magic_open(MAGIC_NONE); if(!magic_) { return; } if(magic_load(magic_, nullptr) != 0) { magic_close(magic_); return; } isInitialized_ = true; } ModuleInfo::~ModuleInfo() { magic_close(magic_); } ModuleInfo* ModuleInfo::instance() { static ModuleInfo info; return &info; } ModuleInfo::Arch ModuleInfo::getArch(const std::string& fileName) const { if(isInitialized_) { const char* buffer = magic_file(magic_, fileName.c_str()); if(buffer) { std::string string = buffer; if(string.find("80386") != std::string::npos) { return kArch32; } else if(string.find("x86-64") != std::string::npos) { return kArch64; } } } return kArchUnknown; } ================================================ FILE: src/common/moduleinfo.h ================================================ #ifndef COMMON_MODULEINFO_H #define COMMON_MODULEINFO_H #include #include class ModuleInfo { public: enum Arch { kArchUnknown = 0, kArch32 = 32, kArch64 = 64 }; static ModuleInfo* instance(); ModuleInfo(const ModuleInfo&) = delete; ModuleInfo& operator=(const ModuleInfo&) = delete; ~ModuleInfo(); Arch getArch(const std::string& fileName) const; private: bool isInitialized_; magic_t magic_; ModuleInfo(); }; #endif // COMMON_MODULEINFO_H ================================================ FILE: src/common/protocol.h ================================================ #ifndef COMMON_PROTOCOL_H #define COMMON_PROTOCOL_H #include "common/types.h" namespace Airwave { enum class Command { Response, Dispatch, GetParameter, SetParameter, ProcessSingle, ProcessDouble, HostInfo, PluginInfo, ShowWindow, GetDataBlock, SetDataBlock, AudioMaster }; struct DataFrame { Command command; i32 opcode; i32 index; i64 value; // The 64-bit value is used here to avoid 64->32 bridging issues float opt; u8 data[]; } __attribute__((packed)); struct PluginInfo { i32 flags; i32 programCount; i32 paramCount; i32 inputCount; i32 outputCount; i32 initialDelay; i32 uniqueId; i32 version; } __attribute__((packed)); } // namespace Airwave #endif // COMMON_PROTOCOL_H ================================================ FILE: src/common/storage.cpp ================================================ #include "storage.h" #include #include "common/config.h" #include "common/filesystem.h" #include "common/json.h" namespace Airwave { Storage::Storage() : isChanged_(false) { reload(); } Storage::~Storage() { save(); } bool Storage::reload() { storageFilePath_.clear(); logSocketPath_.clear(); binariesPath_.clear(); prefixByName_.clear(); loaderByName_.clear(); linkByPath_.clear(); // Add default WINE prefix std::string name = "default"; std::string path = FileSystem::realPath("~") + "/.wine"; prefixByName_.emplace(makePair(name, path)); // Add default WINE loader name = "default"; path = FileSystem::fullNameFromPath("wine"); loaderByName_.emplace(makePair(name, path)); // Initialize default values binariesPath_ = INSTALL_PREFIX "/bin"; const char* string = getenv("TMPDIR"); std::string tempPath = string ? string : "/tmp"; logSocketPath_ = tempPath + "/" PROJECT_NAME ".sock"; defaultLogLevel_ = LogLevel::kTrace; // Find and read a configuration file string = getenv("XDG_CONFIG_PATH"); std::string configPath = string ? string : std::string(); if(configPath.empty()) configPath = "~/.config"; configPath = FileSystem::realPath(configPath); if(configPath.back() != '/') configPath += '/'; if(!FileSystem::isDirExists(configPath)) return false; storageFilePath_ = configPath + PROJECT_NAME "/" PROJECT_NAME ".conf"; std::ifstream file(storageFilePath_); if(!file.is_open()) return false; Json::Value root; Json::Reader reader; if(!reader.parse(file, root, false)) return false; // Load general variables auto value = root["binaries_path"]; if(!value.isNull()) binariesPath_ = value.asString(); value = root["log_socket_path"]; if(!value.isNull()) logSocketPath_ = value.asString(); value = root["default_log_level"]; if(!value.isNull()) { defaultLogLevel_ = static_cast(value.asInt()); if(defaultLogLevel_ < LogLevel::kQuiet || defaultLogLevel_ > LogLevel::kFlood) defaultLogLevel_ = LogLevel::kTrace; } // Load prefixes Json::Value prefixes = root["prefixes"]; for(uint i = 0; i < prefixes.size(); ++i) { Json::Value prefix = prefixes[i]; name = prefix["name"].asString(); path = prefix["path"].asString(); if(name.empty() || path.empty()) continue; prefixByName_.emplace(makePair(name, path)); } // Load loaders Json::Value loaders = root["loaders"]; for(uint i = 0; i < loaders.size(); ++i) { Json::Value loader = loaders[i]; name = loader["name"].asString(); path = loader["path"].asString(); if(name.empty() || path.empty()) continue; loaderByName_.emplace(makePair(name, path)); } // Load links Json::Value links = root["links"]; for(uint i = 0; i < links.size(); ++i) { Json::Value link = links[i]; LinkInfo info; info.target = link["target"].asString(); info.loader = link["loader"].asString(); if(info.loader.empty()) info.loader = "default;"; info.prefix = link["prefix"].asString(); if(info.prefix.empty()) info.prefix = "default;"; auto value = link["log_level"]; if(value.isNull()) { info.level = LogLevel::kDefault; } else { info.level = static_cast(value.asInt()); if(info.level < LogLevel::kDefault || info.level > LogLevel::kFlood) info.level = LogLevel::kDefault; } path = link["path"].asString(); linkByPath_.emplace(makePair(path, info)); } return true; } bool Storage::save() { if(!isChanged_) return true; std::size_t pos = storageFilePath_.rfind('/'); if(pos != std::string::npos) { std::string dir = storageFilePath_.substr(0, pos); if(!FileSystem::makePath(dir)) return false; } std::ofstream file(storageFilePath_, std::ios::out | std::ios::trunc); if(!file.is_open()) return false; Json::Value root; root["binaries_path"] = binariesPath_; root["log_socket_path"] = logSocketPath_; root["default_log_level"] = static_cast(defaultLogLevel_); Json::Value prefixes(Json::arrayValue); for(auto it : prefixByName_) { if(it.first == "default") continue; Json::Value prefix; prefix["name"] = it.first; prefix["path"] = it.second; prefixes.append(prefix); } root["prefixes"] = prefixes; Json::Value loaders(Json::arrayValue); for(auto it : loaderByName_) { if(it.first == "default") continue; Json::Value loader; loader["name"] = it.first; loader["path"] = it.second; loaders.append(loader); } root["loaders"] = loaders; Json::Value links(Json::arrayValue); for(auto& it : linkByPath_) { Json::Value link; link["path"] = it.first; link["loader"] = it.second.loader; link["prefix"] = it.second.prefix; link["target"] = it.second.target; link["log_level"] = static_cast(it.second.level); links.append(link); } root["links"] = links; Json::StyledWriter writer; file << writer.write(root); isChanged_ = false; return true; } std::string Storage::logSocketPath() const { return logSocketPath_; } void Storage::setLogSocketPath(const std::string& path) { logSocketPath_ = path; isChanged_ = true; } std::string Storage::binariesPath() const { return binariesPath_; } void Storage::setBinariesPath(const std::string& path) { binariesPath_ = path; isChanged_ = true; } LogLevel Storage::defaultLogLevel() const { return defaultLogLevel_; } void Storage::setDefaultLogLevel(LogLevel level) { defaultLogLevel_ = level; isChanged_ = true; } Storage::Prefix Storage::prefix(const std::string& name) { if(name.empty()) return Prefix(this, prefixByName_.begin()); return Prefix(this, prefixByName_.find(name)); } Storage::Prefix Storage::createPrefix(const std::string& name, const std::string& path) { auto it = prefixByName_.find(name); if(it != prefixByName_.end()) return Prefix(); auto result = prefixByName_.emplace(name, path); isChanged_ = true; return Prefix(this, result.first); } bool Storage::removePrefix(Storage::Prefix prefix) { if(!prefix || prefix.name() == "default") return false; prefixByName_.erase(prefix.it_); isChanged_ = true; return true; } Storage::Loader Storage::loader(std::string const& name) { if(name.empty()) return Loader(this, loaderByName_.begin()); return Loader(this, loaderByName_.find(name)); } Storage::Loader Storage::createLoader(const std::string& name, const std::string& path) { auto it = loaderByName_.find(name); if(it != loaderByName_.end()) return Loader(); auto result = loaderByName_.emplace(name, path); isChanged_ = true; return Loader(this, result.first); } bool Storage::removeLoader(Storage::Loader loader) { if(!loader || loader.name() == "default") return false; loaderByName_.erase(loader.it_); isChanged_ = true; return true; } Storage::Link Storage::link(std::string const& path) { if(path.empty()) return Link(this, linkByPath_.begin()); return Link(this, linkByPath_.find(path)); } Storage::Link Storage::createLink(const std::string& path, const std::string& target, const std::string& prefix, const std::string& loader) { auto it = linkByPath_.find(path); if(it != linkByPath_.end()) return Link(); auto prefixIt = prefixByName_.find(prefix); if(prefixIt == prefixByName_.end()) return Link(); auto loaderIt = loaderByName_.find(loader); if(loaderIt == loaderByName_.end()) return Link(); LinkInfo info; info.target = target; info.prefix = prefix; info.loader = loader; info.level = LogLevel::kDefault; auto result = linkByPath_.emplace(makePair(path, info)); if(!result.second) return Link(); isChanged_ = true; return Link(this, result.first); } bool Storage::removeLink(Storage::Link link) { if(!link) return false; linkByPath_.erase(link.it_); isChanged_ = true; return true; } Storage::Prefix::Prefix() : storage_(nullptr) { } Storage::Prefix::Prefix(Storage* storage, PrefixMap::iterator it) : storage_(storage), it_(it) { } bool Storage::Prefix::isNull() const { return !storage_ || it_ == storage_->prefixByName_.end(); } std::string Storage::Prefix::name() const { if(isNull()) return std::string(); return it_->first; } bool Storage::Prefix::setName(const std::string& name) { if(isNull()) return false; std::string oldName = it_->first; std::string path = it_->second; auto result = storage_->prefixByName_.emplace(makePair(name, path)); if(!result.second) return false; for(auto& it : storage_->linkByPath_) { if(it.second.prefix == oldName) it.second.prefix = name; } storage_->prefixByName_.erase(it_); storage_->isChanged_ = true; it_ = result.first; return true; } std::string Storage::Prefix::path() const { if(isNull()) return std::string(); return it_->second; } bool Storage::Prefix::setPath(const std::string& path) { if(isNull()) return false; if(path == it_->second) return true; it_->second = path; storage_->isChanged_ = true; return true; } Storage::Prefix Storage::Prefix::next() const { if(storage_ && it_ != storage_->prefixByName_.end()) { auto nextIt = it_; return Prefix(storage_, ++nextIt); } return Prefix(); } bool Storage::Prefix::operator!() const { return isNull(); } Storage::Loader::Loader() : storage_(nullptr) { } Storage::Loader::Loader(Storage* storage, LoaderMap::iterator it) : storage_(storage), it_(it) { } bool Storage::Loader::isNull() const { return !storage_ || it_ == storage_->loaderByName_.end(); } std::string Storage::Loader::name() const { if(isNull()) return std::string(); return it_->first; } bool Storage::Loader::setName(const std::string& name) { if(isNull()) return false; std::string oldName = it_->first; std::string path = it_->second; auto result = storage_->loaderByName_.emplace(makePair(name, path)); if(!result.second) return false; for(auto& it : storage_->linkByPath_) { if(it.second.loader == oldName) it.second.loader = name; } storage_->loaderByName_.erase(it_); storage_->isChanged_ = true; it_ = result.first; return true; } std::string Storage::Loader::path() const { if(isNull()) return std::string(); return it_->second; } bool Storage::Loader::setPath(const std::string& path) { if(isNull()) return false; if(path == it_->second) return true; it_->second = path; storage_->isChanged_ = true; return true; } Storage::Loader Storage::Loader::next() const { if(storage_ && it_ != storage_->loaderByName_.end()) { auto nextIt = it_; return Loader(storage_, ++nextIt); } return Loader(); } bool Storage::Loader::operator!() const { return isNull(); } Storage::Link::Link() : storage_(nullptr) { } Storage::Link::Link(Storage* storage, LinkMap::iterator it) : storage_(storage), it_(it) { } bool Storage::Link::isNull() const { return !storage_ || it_ == storage_->linkByPath_.end(); } std::string Storage::Link::path() const { if(isNull()) return std::string(); return it_->first; } bool Storage::Link::setPath(const std::string& path) { if(isNull()) return false; if(path == it_->first) return true; auto it = storage_->linkByPath_.find(path); if(it != storage_->linkByPath_.end()) return false; LinkInfo info = it_->second; storage_->linkByPath_.erase(it_); it_ = storage_->linkByPath_.emplace_hint(it, makePair(path, info)); storage_->isChanged_ = true; return true; } std::string Storage::Link::target() const { if(isNull()) return std::string(); return it_->second.target; } bool Storage::Link::setTarget(const std::string& path) { if(isNull()) return false; if(path == it_->second.target) return true; it_->second.target = path; storage_->isChanged_ = true; return true; } std::string Storage::Link::prefix() const { if(isNull()) return std::string(); return it_->second.prefix; } bool Storage::Link::setPrefix(const std::string& prefix) { if(isNull()) return false; if(prefix == it_->second.prefix) return true; it_->second.prefix = prefix; storage_->isChanged_ = true; return true; } std::string Storage::Link::loader() const { if(isNull()) return std::string(); return it_->second.loader; } bool Storage::Link::setLoader(const std::string& loader) { if(isNull()) return false; if(loader == it_->second.loader) return true; it_->second.loader = loader; storage_->isChanged_ = true; return true; } LogLevel Storage::Link::logLevel() const { if(isNull()) return LogLevel::kDefault; return it_->second.level; } void Storage::Link::setLogLevel(LogLevel level) { if(!isNull() && level != it_->second.level) { it_->second.level = level; storage_->isChanged_ = true; } } Storage::Link Storage::Link::next() const { if(storage_ && it_ != storage_->linkByPath_.end()) { auto nextIt = it_; return Link(storage_, ++nextIt); } return Link(); } bool Storage::Link::operator!() const { return isNull(); } } // namespace Airwave ================================================ FILE: src/common/storage.h ================================================ #ifndef COMMON_STORAGE_H #define COMMON_STORAGE_H #include #include #include "common/logger.h" #include "common/types.h" namespace Airwave { class Storage { public: class Prefix { public: Prefix(); bool isNull() const; std::string name() const; bool setName(const std::string& name); std::string path() const; bool setPath(const std::string& path); Prefix next() const; bool operator!() const; private: friend class Storage; using PrefixMap = std::map; Storage* storage_; PrefixMap::iterator it_; Prefix(Storage* storage, PrefixMap::iterator it); }; class Loader { public: Loader(); bool isNull() const; std::string name() const; bool setName(const std::string& name); std::string path() const; bool setPath(const std::string& path); Loader next() const; bool operator!() const; private: friend class Storage; using LoaderMap = std::map; Storage* storage_; LoaderMap::iterator it_; Loader(Storage* storage, LoaderMap::iterator it); }; struct LinkInfo { std::string target; std::string prefix; std::string loader; LogLevel level; }; class Link { public: Link(); bool isNull() const; std::string path() const; bool setPath(const std::string& path); std::string target() const; bool setTarget(const std::string& path); std::string prefix() const; bool setPrefix(const std::string& prefix); std::string loader() const; bool setLoader(const std::string& loader); LogLevel logLevel() const; void setLogLevel(LogLevel level); Link next() const; bool operator!() const; private: friend class Storage; using LinkMap = std::map; Storage* storage_; LinkMap::iterator it_; Link(Storage* storage, LinkMap::iterator it); }; Storage(); ~Storage(); bool reload(); bool save(); std::string logSocketPath() const; void setLogSocketPath(const std::string& path); std::string binariesPath() const; void setBinariesPath(const std::string& path); LogLevel defaultLogLevel() const; void setDefaultLogLevel(LogLevel level); Prefix prefix(const std::string& name = std::string()); Prefix createPrefix(const std::string& name, const std::string& path); bool removePrefix(Prefix prefix); Loader loader(const std::string& name = std::string()); Loader createLoader(const std::string& name, const std::string& path); bool removeLoader(Loader loader); Link link(const std::string& path = std::string()); Link createLink(const std::string& path, const std::string& target, const std::string& prefix, const std::string& loader); bool removeLink(Link link); private: friend class Prefix; friend class Loader; friend class Link; bool isChanged_; std::string storageFilePath_; std::string logSocketPath_; std::string binariesPath_; LogLevel defaultLogLevel_; std::map prefixByName_; std::map loaderByName_; std::map linkByPath_; }; } // namespace Airwave #endif // COMMON_STORAGE_H ================================================ FILE: src/common/types.h ================================================ #ifndef COMMON_TYPES_H #define COMMON_TYPES_H #include #include #include #include #include // Remove stupid definitions from stdbool.h #undef bool #undef true #undef false #define UNUSED(x) ((void) x) // Basic data types using schar = signed char; using uchar = unsigned char; using ushort = unsigned short; using uint = unsigned int; using ulong = unsigned long; using longlong = long long; using ulonglong = unsigned long long; using ch16 = char16_t; using ch32 = char32_t; using i8 = int8_t; using u8 = uint8_t; using i16 = int16_t; using u16 = uint16_t; using i32 = int32_t; using u32 = uint32_t; using i64 = int64_t; using u64 = uint64_t; using f32 = float; using f64 = double; template using Box = std::unique_ptr; template using Rc = std::shared_ptr; template using Ref = std::weak_ptr; template using Pair = std::pair; template using Tuple = std::tuple; template constexpr Box makeBox(Args&&... args) { return Box(new T(std::forward(args)...)); } template constexpr Rc makeRc(Args&&... args) { return Rc(new T(std::forward(args)...)); } template constexpr Pair::type, typename std::decay::type> makePair(First&& first, Second&& second) { using PairType = Pair; return PairType(std::forward(first), std::forward(second)); } template constexpr Tuple::type...> makeTuple(Args&&... args) { return std::make_tuple(std::forward(args)...); } #endif // COMMON_TYPES_H ================================================ FILE: src/common/vst24.h ================================================ #ifndef COMMON_VST24_H #define COMMON_VST24_H #include #include #include "common/types.h" namespace Airwave { //using AudioMasterProc = intptr_t (VSTCALLBACK*)(AEffect*, i32, i32, intptr_t, void*, float); //using VstPluginMainProc = AEffect* (VSTCALLBACK*)(AudioMasterProc); typedef intptr_t (VSTCALLBACK *AudioMasterProc)(AEffect*, i32, i32, intptr_t, void*, float); typedef AEffect* (VSTCALLBACK *VstPluginMainProc)(AudioMasterProc); static const char* const kDispatchEvents[] = { "effOpen", "effClose", "effSetProgram", "effGetProgram", "effSetProgramName", "effGetProgramName", "effGetParamLabel", "effGetParamDisplay", "effGetParamName", "effGetVu", "effSetSampleRate", "effSetBlockSize", "effMainsChanged", "effEditGetRect", "effEditOpen", "effEditClose", "effEditDraw", "effEditMouse", "effEditKey", "effEditIdle", "effEditTop", "effEditSleep", "effIdentify", "effGetChunk", "effSetChunk", "effProcessEvents", "effCanBeAutomated", "effString2Parameter", "effGetNumProgramCategories", "effGetProgramNameIndexed", "effCopyProgram", "effConnectInput", "effConnectOutput", "effGetInputProperties", "effGetOutputProperties", "effGetPlugCategory", "effGetCurrentPosition", "effGetDestinationBuffer", "effOfflineNotify", "effOfflinePrepare", "effOfflineRun", "effProcessVarIo", "effSetSpeakerArrangement", "effSetBlockSizeAndSampleRate", "effSetBypass", "effGetEffectName", "effGetErrorText", "effGetVendorString", "effGetProductString", "effGetVendorVersion", "effVendorSpecific", "effCanDo", "effGetTailSize", "effIdle", "effGetIcon", "effSetViewPosition", "effGetParameterProperties", "effKeysRequired", "effGetVstVersion", "effEditKeyDown", "effEditKeyUp", "effSetEditKnobMode", "effGetMidiProgramName", "effGetCurrentMidiProgram", "effGetMidiProgramCategory", "effHasMidiProgramsChanged", "effGetMidiKeyName", "effBeginSetProgram", "effEndSetProgram", "effGetSpeakerArrangement", "effShellGetNextPlugin", "effStartProcess", "effStopProcess", "effSetTotalSampleToProcess", "effSetPanLaw", "effBeginLoadBank", "effBeginLoadProgram", "effSetProcessPrecision", "effGetNumMidiInputChannels", "effGetNumMidiOutputChannels" }; static const char* const kAudioMasterEvents[] = { "audioMasterAutomate", "audioMasterVersion", "audioMasterCurrentId", "audioMasterIdle", "audioMasterPinConnected", "", "audioMasterWantMidi", "audioMasterGetTime", "audioMasterProcessEvents", "audioMasterSetTime", "audioMasterTempoAt", "audioMasterGetNumAutomatableParameters", "audioMasterGetParameterQuantization", "audioMasterIOChanged", "audioMasterNeedIdle", "audioMasterSizeWindow", "audioMasterGetSampleRate", "audioMasterGetBlockSize", "audioMasterGetInputLatency", "audioMasterGetOutputLatency", "audioMasterGetPreviousPlug", "audioMasterGetNextPlug", "audioMasterWillReplaceOrAccumulate", "audioMasterGetCurrentProcessLevel", "audioMasterGetAutomationState", "audioMasterOfflineStart", "audioMasterOfflineRead", "audioMasterOfflineWrite", "audioMasterOfflineGetCurrentPass", "audioMasterOfflineGetCurrentMetaPass", "audioMasterSetOutputSampleRate", "audioMasterGetOutputSpeakerArrangement", "audioMasterGetVendorString", "audioMasterGetProductString", "audioMasterGetVendorVersion", "audioMasterVendorSpecific", "audioMasterSetIcon", "audioMasterCanDo", "audioMasterGetLanguage", "audioMasterOpenWindow", "audioMasterCloseWindow", "audioMasterGetDirectory", "audioMasterUpdateDisplay", "audioMasterBeginEdit", "audioMasterEndEdit", "audioMasterOpenFileSelector", "audioMasterCloseFileSelector", "audioMasterEditFile", "audioMasterGetChunkFile", "audioMasterGetInputSpeakerArrangement" }; } // namespace Airwave #endif // COMMON_VST24_H ================================================ FILE: src/common/vsteventkeeper.cpp ================================================ #include "vsteventkeeper.h" #include #include namespace Airwave { VstEventKeeper::VstEventKeeper() : events_(nullptr), data_(nullptr) { } VstEventKeeper::~VstEventKeeper() { delete [] events_; } void VstEventKeeper::reload(int count, const VstEvent events[]) { if(!events_ || events_->numEvents < count) { delete [] events_; int extraCount = std::max(count - 2, 0); size_t size = sizeof(VstEvents) + extraCount * sizeof(VstEvent*) + count * sizeof(VstEvent); uint8_t* buffer = new uint8_t[size]; events_ = reinterpret_cast(buffer); size_t offset = sizeof(VstEvents) + extraCount * sizeof(VstEvent*); data_ = reinterpret_cast(buffer + offset); } events_->numEvents = count; events_->reserved = 0; for(int i = 0; i < count; ++i) { data_[i] = events[i]; events_->events[i] = &data_[i]; } } VstEvents* VstEventKeeper::events() { return events_; } } // namespace Airwave ================================================ FILE: src/common/vsteventkeeper.h ================================================ #ifndef COMMON_VSTEVENTSKEEPER_H #define COMMON_VSTEVENTSKEEPER_H #include namespace Airwave { class VstEventKeeper { public: VstEventKeeper(); ~VstEventKeeper(); void reload(int count, const VstEvent events[]); VstEvents* events(); private: VstEvents* events_; VstEvent* data_; }; } // namespace Airwave #endif // COMMON_VSTEVENTSKEEPER_H ================================================ FILE: src/host/CMakeLists.txt ================================================ # Configure base name set(TARGET_NAME ${HOST_BASENAME}) project(${TARGET_NAME}) option(DISABLE_64BIT "Disable building of the 64-bit host endpoint" OFF) find_package(Threads REQUIRED) include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ${VSTSDK_INCLUDE_DIR} ) # Set target operating system set(CMAKE_SYSTEM_NAME Windows) # Set compilers to use set(CMAKE_C_COMPILER winegcc) set(CMAKE_CXX_COMPILER wineg++) add_definitions(-DNOMINMAX) if(DEBUG_BINARY_DIR) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${DEBUG_BINARY_DIR}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${DEBUG_BINARY_DIR}) endif() # Sources set(SOURCES ../common/dataport.cpp ../common/event.cpp ../common/filesystem.cpp ../common/logger.cpp ../common/vsteventkeeper.cpp host.cpp main.cpp ) if(NOT DISABLE_64BIT AND PLATFORM_64BIT) # Set target add_executable(${TARGET_NAME}-64 WIN32 ${SOURCES}) set_target_properties(${TARGET_NAME}-64 PROPERTIES COMPILE_FLAGS "-m64" LINK_FLAGS "-m64" ) # Link with libraries target_link_libraries(${TARGET_NAME}-64 ${CMAKE_THREAD_LIBS_INIT} ) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}-64.exe ${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}-64.exe.so DESTINATION bin ) endif() # Set target add_executable(${TARGET_NAME}-32 WIN32 ${SOURCES}) set_target_properties(${TARGET_NAME}-32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32" ) # Link with libraries target_link_libraries(${TARGET_NAME}-32 ${CMAKE_THREAD_LIBS_INIT} ) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}-32.exe ${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}-32.exe.so DESTINATION bin ) ================================================ FILE: src/host/host.cpp ================================================ #include "host.h" #include #include "common/logger.h" #include "common/protocol.h" namespace Airwave { Host* Host::self_ = nullptr; Host::Host() : isInitialized_(false), hwnd_(0), data_(nullptr), dataLength_(0), runAudio_(ATOMIC_FLAG_INIT), isEditorOpen_(false), oldWndProc_(nullptr), childHwnd_(0) { DEBUG("Main thread id: %p", GetCurrentThreadId()); } Host::~Host() { if(isInitialized_) { TRACE("Waiting for audio thread termination..."); runAudio_.clear(); WaitForSingleObject(audioThread_, INFINITE); destroyEditorWindow(); DeleteCriticalSection(&cs_); FreeLibrary(module_); } } bool Host::initialize(const char* fileName, int portId) { if(isInitialized_) { TRACE("Host endpoint is already initialized"); return false; } module_ = LoadLibrary(fileName); if(!module_) { ERROR("Unable to load '%s' shared library: %s", fileName, errorString().c_str()); return false; } if(!InitializeCriticalSectionAndSpinCount(&cs_, 0x00010000)) { FreeLibrary(module_); return false; } VstPluginMainProc vstMainProc = reinterpret_cast( GetProcAddress(module_, "VSTPluginMain")); if(!vstMainProc) { vstMainProc = reinterpret_cast( GetProcAddress(module_, "main")); if(!vstMainProc) { ERROR("The %s is not a VST plugin"); DeleteCriticalSection(&cs_); FreeLibrary(module_); return false; } } if(!controlPort_.connect(portId)) { ERROR("Unable to connect control port (id = %d)", portId); DeleteCriticalSection(&cs_); FreeLibrary(module_); return false; } TRACE("Waiting for plugin endpoint request..."); if(!controlPort_.waitRequest()) { ERROR("Unable to get initial request from plugin endpoint"); controlPort_.disconnect(); DeleteCriticalSection(&cs_); FreeLibrary(module_); return false; } TRACE("Request from plugin endpoint received, sending response"); DataFrame* frame = controlPort_.frame(); if(!callbackPort_.connect(frame->opcode)) { ERROR("Unable to connect callback port (id = %d)", frame->opcode); controlPort_.disconnect(); DeleteCriticalSection(&cs_); FreeLibrary(module_); return false; } // When we call vstMainProc(), the audioMasterProc() can be called from there with // effect argument set to the nullptr. This is because VST plugin object is not yet // initialized at this point. Since we need the pointer to our object inside of // audioMasterProc(), we must store it in some accessible place. Static member // pointer is very ugly, but very effective solution, since we don't need more than // one instance of host endpoint anyway. self_ = this; TRACE("Initializing VST plugin..."); effect_ = vstMainProc(audioMasterProc); if(!effect_ || effect_->magic != kEffectMagic) { ERROR("Unable to initialize VST plugin"); controlPort_.disconnect(); callbackPort_.disconnect(); DeleteCriticalSection(&cs_); FreeLibrary(module_); return false; } TRACE("VST plugin is initialized"); std::memset(&timeInfo_, 0, sizeof(VstTimeInfo)); frame->command = Command::PluginInfo; PluginInfo* info = reinterpret_cast(frame->data); info->flags = effect_->flags; info->programCount = effect_->numPrograms; info->paramCount = effect_->numParams; info->inputCount = effect_->numInputs; info->outputCount = effect_->numOutputs; info->initialDelay = effect_->initialDelay; info->uniqueId = effect_->uniqueID; info->version = effect_->version; // Workaround for plugins from Waves char vendorName[kVstMaxVendorStrLen]; if(effect_->dispatcher(effect_, effGetVendorString, 0, 0, &vendorName, 0.0f)) { if(strncmp(vendorName, "Waves", kVstMaxVendorStrLen) == 0) info->flags |= effFlagsHasEditor; } controlPort_.sendResponse(); isInitialized_ = true; return true; } bool Host::processRequest() { if(!controlPort_.isConnected()) { TRACE("Control port isn't connected anymore, exiting"); return false; } if(!controlPort_.waitRequest(10)) return true; bool result = true; DataFrame* frame = controlPort_.frame(); switch(frame->command) { case Command::Dispatch: result = handleDispatch(frame); break; case Command::GetDataBlock: handleGetDataBlock(frame); break; case Command::SetDataBlock: handleSetDataBlock(frame); break; case Command::ShowWindow: { if(hwnd_) { ShowWindow(hwnd_, SW_SHOW); UpdateWindow(hwnd_); } break; } default: ERROR("processRequest() unacceptable command: %d", frame->command); break; } frame->command = Command::Response; controlPort_.sendResponse(); return result; } std::string Host::errorString() const { DWORD error = GetLastError(); if(error) { LPVOID buffer; DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; DWORD length = FormatMessage(flags, nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast(&buffer), 0, nullptr); if(length) { LPCSTR message = static_cast(buffer); std::string result(message, message + length); LocalFree(buffer); return result; } } return std::string(); } void Host::destroyEditorWindow() { if(hwnd_) { KillTimer(hwnd_, timerId_); DestroyWindow(hwnd_); UnregisterClass(kWindowClass, GetModuleHandle(nullptr)); hwnd_ = 0; } } void Host::audioThread() { condition_.post(); while(runAudio_.test_and_set()) { if(audioPort_.waitRequest(100)) { DataFrame* frame = audioPort_.frame(); if(frame->command == Command::ProcessSingle) { handleProcessSingle(); } else if(frame->command == Command::GetParameter) { handleGetParameter(); } else if(frame->command == Command::SetParameter) { handleSetParameter(); } else if(frame->command == Command::ProcessDouble) { handleProcessDouble(); } else if(frame->command == Command::Dispatch) { handleDispatch(frame); } else { ERROR("audioThread() unacceptable command: %d", frame->command); } frame->command = Command::Response; audioPort_.sendResponse(); } } } void Host::handleGetDataBlock(DataFrame* frame) { size_t blockSize = frame->index; DEBUG("handleGetDataBlock: %d bytes", blockSize); frame->index = dataLength_ < blockSize ? dataLength_ : blockSize; std::copy(data_, data_ + frame->index, frame->data); data_ += frame->index; dataLength_ -= frame->index; } void Host::handleSetDataBlock(DataFrame* frame) { chunk_.insert(chunk_.end(), frame->data, frame->data + frame->index); } bool Host::handleDispatch(DataFrame* frame) { FLOOD("handleDispatch: %s", kDispatchEvents[frame->opcode]); if(isEditorOpen_ && frame->opcode != effEditIdle) { // Postpone the effEditIdle event by 100 milliseconds SetTimer(hwnd_, timerId_, 100, nullptr); } switch(frame->opcode) { case effClose: // Some stupid hosts doesn't send the effEditClose event before sending // the effClose event. This leads to crashes of some stupid plugins. So // we just emulate correct behavior here to avoid these crashes. if(isEditorOpen_) { effect_->dispatcher(effect_, effEditClose, 0, 0, nullptr, 0.0f); destroyEditorWindow(); isEditorOpen_ = false; } frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, frame->value, nullptr, frame->opt); break; case effGetVstVersion: case effOpen: case effGetPlugCategory: case effSetSampleRate: case effGetVendorVersion: case effEditIdle: case effMainsChanged: case effCanBeAutomated: case effGetProgram: case effStartProcess: case effSetProgram: case effBeginSetProgram: case effEndSetProgram: case effStopProcess: case effGetTailSize: case effSetEditKnobMode: case __effConnectInputDeprecated: case __effConnectOutputDeprecated: case __effKeysRequiredDeprecated: case __effIdentifyDeprecated: frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, frame->value, nullptr, frame->opt); break; case effEditClose: frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, frame->value, nullptr, frame->opt); destroyEditorWindow(); isEditorOpen_ = false; break; case effSetBlockSize: if(runAudio_.test_and_set()) { runAudio_.clear(); WaitForSingleObject(audioThread_, INFINITE); } audioPort_.disconnect(); if(!audioPort_.connect(frame->index)) { ERROR("Unable to connect audio port"); return false; } runAudio_.test_and_set(); audioThread_ = CreateThread(nullptr, 0, audioThreadProc, this, 0, nullptr); condition_.wait(); frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, frame->value, nullptr, frame->opt); break; case effEditOpen: { WNDCLASSEX wclass; std::memset(&wclass, 0, sizeof(WNDCLASSEX)); wclass.cbSize = sizeof(WNDCLASSEX); wclass.style = CS_HREDRAW | CS_VREDRAW; wclass.lpfnWndProc = windowProc; wclass.cbClsExtra = 0; wclass.cbWndExtra = 0; wclass.hInstance = GetModuleHandle(nullptr); wclass.hIcon = LoadIcon(nullptr, kWindowClass); wclass.hCursor = LoadCursor(nullptr, IDC_ARROW); wclass.lpszClassName = kWindowClass; if(!RegisterClassEx(&wclass)) { ERROR("Unable to register window class: %s", errorString().c_str()); return false; } hwnd_ = CreateWindowEx(WS_EX_TOOLWINDOW, kWindowClass, "Plugin", WS_POPUP, 0, 0, 200, 200, 0, 0, GetModuleHandle(nullptr), 0); if(!hwnd_) { ERROR("Unable to create window: %s", errorString().c_str()); UnregisterClass(kWindowClass, module_); return false; } frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, frame->value, hwnd_, frame->opt); // Obtain the size of the VST window in advance. ERect* rect = nullptr; effect_->dispatcher(effect_, effEditGetRect, 0, 0, &rect, 0.0f); RECT wndRect = { rect->left, rect->top, rect->right, rect->bottom }; AdjustWindowRectEx(&wndRect, GetWindowLong(hwnd_, GWL_STYLE), GetMenu(hwnd_) != nullptr, GetWindowLong(hwnd_, GWL_EXSTYLE)); SetWindowPos(hwnd_, 0, 0, 0, rect->right - rect->left, rect->bottom - rect->top, SWP_NOACTIVATE | SWP_NOMOVE); std::memcpy(&frame->data, rect, sizeof(ERect)); timerId_ = SetTimer(hwnd_, 0, 100, nullptr); HANDLE handle = GetPropA(hwnd_, "__wine_x11_whole_window"); frame->value = reinterpret_cast(handle); isEditorOpen_ = true; break; } case effEditGetRect: { ERect* rect = nullptr; frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, frame->value, &rect, frame->opt); std::memcpy(&frame->data, rect, sizeof(ERect)); break; } case effCanDo: case effGetVendorString: case effGetProductString: case effGetParamName: case effGetParamLabel: case effGetProgramNameIndexed: case effGetParamDisplay: case effGetProgramName: case effSetProgramName: case effGetParameterProperties: case effGetOutputProperties: case effGetInputProperties: case effGetMidiKeyName: case effBeginLoadBank: case effBeginLoadProgram: case effGetEffectName: case effShellGetNextPlugin: frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, frame->value, frame->data, frame->opt); break; case effProcessEvents: { VstEvent* events = reinterpret_cast(frame->data); events_.reload(frame->index, events); VstEvents* e = events_.events(); frame->value = effect_->dispatcher(effect_, frame->opcode, 0, frame->value, e, frame->opt); break; } case effGetChunk: { size_t blockSize = frame->value; frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, 0, &data_, frame->opt); dataLength_ = frame->value; DEBUG("effGetChunk: %d", dataLength_); if(dataLength_ == 0) break; frame->index = dataLength_ < blockSize ? dataLength_ : blockSize; std::copy(data_, data_ + frame->index, frame->data); data_ += frame->index; dataLength_ -= frame->index; break; } case effSetChunk: { DEBUG("effSetChunk: %d bytes", chunk_.size()); frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, chunk_.size(), chunk_.data(), frame->opt); chunk_.clear(); break; } case effSetSpeakerArrangement: { u8* data = frame->data; intptr_t value = reinterpret_cast(data); void* ptr = data + sizeof(VstSpeakerArrangement); frame->value = effect_->dispatcher(effect_, frame->opcode, frame->index, value, ptr, frame->opt); break; } default: ERROR("Unhandled dispatch event: %s", kDispatchEvents[frame->opcode]); } return true; } void Host::handleGetParameter() { // DataFrame* frame = controlPort_.frame(); DataFrame* frame = audioPort_.frame(); frame->opt = effect_->getParameter(effect_, frame->index); } void Host::handleSetParameter() { // DataFrame* frame = controlPort_.frame(); DataFrame* frame = audioPort_.frame(); effect_->setParameter(effect_, frame->index, frame->opt); } void Host::handleProcessSingle() { DataFrame* frame = audioPort_.frame(); float* inputs[effect_->numInputs]; float* outputs[effect_->numOutputs]; i32 sampleCount = frame->value; float* data = reinterpret_cast(frame->data); for(int i = 0; i < effect_->numInputs; ++i) inputs[i] = data + i * sampleCount; for(int i = 0; i < effect_->numOutputs; ++i) outputs[i] = data + i * sampleCount; effect_->processReplacing(effect_, inputs, outputs, sampleCount); } void Host::handleProcessDouble() { DataFrame* frame = audioPort_.frame(); double* inputs[effect_->numInputs]; double* outputs[effect_->numOutputs]; i32 sampleCount = frame->value; double* data = reinterpret_cast(frame->data); for(int i = 0; i < effect_->numInputs; ++i) inputs[i] = data + i * sampleCount; for(int i = 0; i < effect_->numOutputs; ++i) outputs[i] = data + i * sampleCount; effect_->processDoubleReplacing(effect_, inputs, outputs, sampleCount); } intptr_t Host::audioMaster(i32 opcode, i32 index, intptr_t value, void* ptr, float opt) { if(opcode != audioMasterGetTime && opcode != audioMasterIdle) FLOOD("handleAudioMaster(%s)", kAudioMasterEvents[opcode]); DataFrame* frame = callbackPort_.frame(); frame->command = Command::AudioMaster; frame->opcode = opcode; frame->index = index; frame->value = value; frame->opt = opt; switch(opcode) { case audioMasterVersion: case __audioMasterWantMidiDeprecated: case audioMasterAutomate: case audioMasterBeginEdit: case audioMasterEndEdit: case audioMasterGetVendorVersion: case audioMasterSizeWindow: case audioMasterGetInputLatency: case audioMasterGetOutputLatency: case audioMasterGetCurrentProcessLevel: case audioMasterGetAutomationState: case audioMasterCurrentId: case audioMasterGetSampleRate: callbackPort_.sendRequest(); callbackPort_.waitResponse(); return frame->value; case audioMasterIOChanged: { if(!isInitialized_) return 0; PluginInfo* info = reinterpret_cast(frame->data); info->flags = effect_->flags; info->programCount = effect_->numPrograms; info->paramCount = effect_->numParams; info->inputCount = effect_->numInputs; info->outputCount = effect_->numOutputs; info->initialDelay = effect_->initialDelay; info->uniqueId = effect_->uniqueID; info->version = effect_->version; callbackPort_.sendRequest(); callbackPort_.waitResponse(); return frame->value; } // FIXME Passing the audioMasterUpdateDisplay request to the plugin endpoint leads to // crash (or lock in Renoise) with some plugins (u-he TripleCheese). case audioMasterUpdateDisplay: // callbackPort_.sendRequest(); // callbackPort_.waitResponse(); return 1; case audioMasterIdle: case __audioMasterNeedIdleDeprecated: // There is no need to translate this request to the VST host, because we can // simply call the dispatcher. // if(isEditorOpen_) // effect_->dispatcher(effect_, effEditIdle, 0, 0, nullptr, 0.0f); // NOTE Currently we run effEditIdle periodically on timer event return 1; case audioMasterGetVendorString: { callbackPort_.sendRequest(); callbackPort_.waitResponse(); if(!frame->value) return 0; const char* source = reinterpret_cast(frame->data); char* dest = static_cast(ptr); std::strncpy(dest, source, kVstMaxVendorStrLen); dest[kVstMaxVendorStrLen-1] = '\0'; return frame->value; } case audioMasterGetProductString: { callbackPort_.sendRequest(); callbackPort_.waitResponse(); if(!frame->value) return 0; const char* source = reinterpret_cast(frame->data); char* dest = static_cast(ptr); std::strncpy(dest, source, kVstMaxProductStrLen); dest[kVstMaxProductStrLen-1] = '\0'; return frame->value; } case audioMasterCanDo: { const char* source = static_cast(ptr); char* dest = reinterpret_cast(frame->data); size_t maxLength = callbackPort_.frameSize() - sizeof(DataFrame); std::strncpy(dest, source, maxLength); dest[maxLength-1] = '\0'; callbackPort_.sendRequest(); callbackPort_.waitResponse(); return frame->value; } case audioMasterGetTime: callbackPort_.sendRequest(); callbackPort_.waitResponse(); if(!frame->value) return 0; std::memcpy(&timeInfo_, frame->data, sizeof(VstTimeInfo)); return reinterpret_cast(&timeInfo_); case audioMasterProcessEvents: { VstEvents* events = static_cast(ptr); VstEvent* event = reinterpret_cast(frame->data); frame->index = events->numEvents; for(int i = 0; i < events->numEvents; ++i) event[i] = *events->events[i]; callbackPort_.sendRequest(); callbackPort_.waitResponse(); return frame->value; } } ERROR("Unhandled audio master request: %s", kAudioMasterEvents[opcode]); return 0; } intptr_t VSTCALLBACK Host::audioMasterProc(AEffect* effect, i32 opcode, i32 index, intptr_t value, void* ptr, float opt) { UNUSED(effect); EnterCriticalSection(&self_->cs_); intptr_t result = self_->audioMaster(opcode, index, value, ptr, opt); LeaveCriticalSection(&self_->cs_); return result; } DWORD CALLBACK Host::audioThreadProc(void* param) { TRACE("Audio thread started"); Host* host = static_cast(param); host->audioThread(); TRACE("Audio thread terminated"); return 0; } LRESULT CALLBACK Host::windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { if(hwnd == self_->hwnd_) { switch(message) { case WM_CLOSE: DEBUG("Received WM_CLOSE event"); ShowWindow(hwnd, SW_HIDE); return 0; case WM_PARENTNOTIFY: if(wParam == WM_CREATE) { self_->childHwnd_ = reinterpret_cast(lParam); LONG_PTR value = SetWindowLongPtr(self_->childHwnd_, GWLP_WNDPROC, reinterpret_cast(windowProc)); self_->oldWndProc_ = reinterpret_cast(value); } break; case WM_TIMER: self_->effect_->dispatcher(self_->effect_, effEditIdle, 0, 0, nullptr, 0.0f); break; } } else if(self_->childHwnd_ && hwnd == self_->childHwnd_) { return CallWindowProc(self_->oldWndProc_, hwnd, message, wParam, lParam); } return DefWindowProc(hwnd, message, wParam, lParam); } } //namespace Airwave ================================================ FILE: src/host/host.h ================================================ #ifndef HOST_HOST_H #define HOST_HOST_H #include #include #include #include #include "common/config.h" #include "common/dataport.h" #include "common/event.h" #include "common/vst24.h" #include "common/vsteventkeeper.h" namespace Airwave { struct DataFrame; class Host { public: Host(); ~Host(); bool initialize(const char* fileName, int portId); bool processRequest(); private: bool isInitialized_; HMODULE module_; HWND hwnd_; CRITICAL_SECTION cs_; UINT_PTR timerId_; AEffect* effect_; VstTimeInfo timeInfo_; VstEventKeeper events_; u8* data_; size_t dataLength_; std::vector chunk_; DataPort controlPort_; DataPort callbackPort_; DataPort audioPort_; Event condition_; HANDLE audioThread_; std::atomic_flag runAudio_; bool isEditorOpen_; WNDPROC oldWndProc_; HWND childHwnd_; static Host* self_; static constexpr const char* kWindowClass = PROJECT_NAME; std::string errorString() const; void destroyEditorWindow(); void audioThread(); void handleGetDataBlock(DataFrame* frame); void handleSetDataBlock(DataFrame* frame); bool handleDispatch(DataFrame* frame); void handleGetParameter(); void handleSetParameter(); void handleProcessSingle(); void handleProcessDouble(); intptr_t audioMaster(i32 opcode, i32 index, intptr_t value, void* ptr, float opt); static intptr_t VSTCALLBACK audioMasterProc(AEffect* effect, i32 opcode, i32 index, intptr_t value, void* ptr, float opt); static DWORD CALLBACK audioThreadProc(void* param); static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); }; } // namespace Airwave #endif // HOST_HOST_H ================================================ FILE: src/host/main.cpp ================================================ #include #include "host.h" #include "common/config.h" #include "common/filesystem.h" #include "common/logger.h" using namespace Airwave; int __cdecl main(int argc, const char* argv[]) { if(argc != 5) { fprintf(stderr, "Airwave host endpoint, version " VERSION_STRING); fprintf(stderr, "error: wrong number of arguments: %d", argc); fprintf(stderr, "usage: %s ", argv[0]); loggerFree(); return -1; } loggerInit(argv[4], HOST_BASENAME); loggerSetSenderId(FileSystem::baseName(argv[1])); LogLevel level = static_cast(atoi(argv[3])); if(level < LogLevel::kQuiet || level > LogLevel::kFlood) { loggerSetLogLevel(LogLevel::kTrace); ERROR("Invalid log level '%d', using log level 'trace' instead", argc); } else { loggerSetLogLevel(level); } TRACE("Initializing host endpoint %s", VERSION_STRING); Host* host = new Host; if(!host->initialize(argv[1], atoi(argv[2]))) { ERROR("Unable to initialize host endpoint"); loggerFree(); return -2; } TRACE("Host endpoint is initialized"); while(host->processRequest()) { MSG message; while(PeekMessage(&message, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&message); DispatchMessage(&message); } } TRACE("Terminating the host endpoint..."); delete host; TRACE("Host endpoint terminated"); loggerFree(); return 0; } ================================================ FILE: src/manager/CMakeLists.txt ================================================ set(TARGET_NAME ${PROJECT_NAME}-manager) project(${TARGET_NAME}) find_package(Qt5Widgets REQUIRED) find_package(Qt5Network REQUIRED) find_package(LibMagic REQUIRED) include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ${LIBMAGIC_INCLUDE_DIR} ) # Instruct CMake to run moc automatically when needed set(CMAKE_AUTOMOC ON) set(SOURCES main.cpp ../common/filesystem.cpp ../common/json.cpp ../common/moduleinfo.cpp ../common/storage.cpp core/application.cpp core/logsocket.cpp core/singleapplication.cpp forms/filedialog.cpp forms/folderdialog.cpp forms/linkdialog.cpp forms/loaderdialog.cpp forms/mainform.cpp forms/prefixdialog.cpp forms/settingsdialog.cpp models/directorymodel.cpp models/linksmodel.cpp models/loadersmodel.cpp models/prefixesmodel.cpp widgets/lineedit.cpp widgets/linksview.cpp widgets/logview.cpp widgets/directoryview.cpp widgets/loadersview.cpp widgets/nofocusdelegate.cpp widgets/prefixesview.cpp widgets/separatorlabel.cpp ) # Help the stupid IDE to consider following headers as a part of the project set(HEADERS ../common/config.h ../common/types.h models/generictreemodel.h widgets/generictreeview.h ) set(RESOURCES resources/resources.qrc ) set(LIBRARIES Qt5::Widgets Qt5::Network ${LIBMAGIC_LIBRARY} ) qt5_add_resources(RCC_SOURCES ${RESOURCES}) # Set target add_executable(${TARGET_NAME} ${SOURCES} ${HEADERS} ${RCC_SOURCES}) # Use the Widgets module from Qt 5 target_link_libraries(${TARGET_NAME} ${LIBRARIES}) # Generate desktop file configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/${TARGET_NAME}.desktop.in ${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}.desktop ) install(TARGETS ${TARGET_NAME} RUNTIME DESTINATION bin) install(FILES resources/${TARGET_NAME}.png DESTINATION share/icons/hicolor/48x48/apps) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}.desktop DESTINATION share/applications) ================================================ FILE: src/manager/airwave-manager.desktop.in ================================================ [Desktop Entry] Type=Application Version=1.0 Name=Airwave manager Comment=A tool for managing the Airwave VST bridge Exec=@TARGET_NAME@ Icon=@TARGET_NAME@ Terminal=false Categories=Multimedia;AudioVideo;Player;Recorder; ================================================ FILE: src/manager/core/application.cpp ================================================ #include #include "application.h" #include "common/config.h" #include "common/storage.h" #include "models/linksmodel.h" #include "models/loadersmodel.h" #include "models/prefixesmodel.h" Application::Application(int& argc, char** argv) : SingleApplication(argc, argv), storage_(new Airwave::Storage), links_(new LinksModel(this)), loaders_(new LoadersModel(this)), prefixes_(new PrefixesModel(this)) { } Application::~Application() { delete prefixes_; delete loaders_; delete links_; delete storage_; } LogSocket* Application::logSocket() { return &logSocket_; } Storage* Application::storage() const { return storage_; } LinksModel* Application::links() const { return links_; } LoadersModel* Application::loaders() const { return loaders_; } PrefixesModel* Application::prefixes() const { return prefixes_; } QStringList Application::checkMissingBinaries(const QString& path) const { QString binPath = path; if(binPath.isEmpty()) binPath = QString::fromStdString(storage_->binariesPath()); QDir binDir(binPath); QStringList fileList; fileList += HOST_BASENAME "-32.exe"; fileList += PLUGIN_BASENAME ".so"; #ifdef PLATFORM_64BIT fileList += HOST_BASENAME "-64.exe"; #endif QStringList result; foreach(const QString& fileName, fileList) { if(!binDir.exists(fileName)) result += fileName; } return result; } ================================================ FILE: src/manager/core/application.h ================================================ #ifndef CORE_APPLICATION_H #define CORE_APPLICATION_H #include "core/logsocket.h" #include "core/singleapplication.h" #ifdef qApp #undef qApp #define qApp (static_cast(QApplication::instance())) #endif class LinksModel; class LoadersModel; class PrefixesModel; namespace Airwave { class Storage; } class Application : public SingleApplication { public: Application(int& argc, char** argv); ~Application(); LogSocket* logSocket(); Airwave::Storage* storage() const; LinksModel* links() const; LoadersModel* loaders() const; PrefixesModel* prefixes() const; QStringList checkMissingBinaries(const QString& path = QString()) const; private: LogSocket logSocket_; Airwave::Storage* storage_; LinksModel* links_; LoadersModel* loaders_; PrefixesModel* prefixes_; }; #endif // CORE_APPLICATION_H ================================================ FILE: src/manager/core/logsocket.cpp ================================================ #include "logsocket.h" #include #include #include #include #include #include #include LogSocket::LogSocket(QObject* parent) : QObject(parent), fd_(-1), notifier_(nullptr) { } LogSocket::~LogSocket() { close(); } QString LogSocket::id() const { return id_; } bool LogSocket::listen(const QString& id) { fd_ = socket(AF_UNIX, SOCK_DGRAM, 0); if(fd_ < 0) { qDebug("Unable to create socket: %s", strerror(errno)); return false; } unlink(id.toUtf8().constData()); struct sockaddr_un address; std::memset(&address, 0, sizeof(address)); address.sun_family = AF_UNIX; std::snprintf(address.sun_path, UNIX_PATH_MAX, id.toUtf8().constData()); if(bind(fd_, reinterpret_cast(&address), sizeof(address)) < 0) { qDebug("Unable to bind socket: %s", strerror(errno)); ::close(fd_); fd_ = -1; return false; } id_ = id; notifier_ = new QSocketNotifier(fd_, QSocketNotifier::Read); connect(notifier_, SIGNAL(activated(int)), SLOT(handleDatagram())); return true; } void LogSocket::close() { if(fd_ != -1) { delete notifier_; ::close(fd_); unlink(id_.toUtf8().constData()); } } void LogSocket::handleDatagram() { size_t length = 0; if(ioctl(fd_, FIONREAD, &length) < 0) { qDebug("ioctl() call failed: %s", strerror(errno)); return; } char* buffer = new char[length]; if(recvfrom(fd_, buffer, length, 0, nullptr, nullptr) < 0) { qDebug("recvfrom() call failed: %s", strerror(errno)); delete [] buffer; return; } quint64* timeStamp = reinterpret_cast(buffer); const char* sender = buffer + sizeof(quint64); const char* message; message = static_cast(std::memchr(sender, 0x01, length)); if(!message) { qDebug("Discarding invalid datagram."); delete [] buffer; return; } QString senderId; senderId = QString::fromUtf8(sender, message - sender); emit newMessage(*timeStamp, senderId, message + 1); delete [] buffer; } ================================================ FILE: src/manager/core/logsocket.h ================================================ #ifndef CORE_LOGSOCKET_H #define CORE_LOGSOCKET_H #include #include class LogSocket : public QObject { Q_OBJECT public: LogSocket(QObject* parent = nullptr); ~LogSocket(); QString id() const; bool listen(const QString& id); void close(); signals: void newMessage(quint64 time, const QString& sender, const QString& text); private: int fd_; QSocketNotifier* notifier_; QString id_; private slots: void handleDatagram(); }; #endif // CORE_LOGSOCKET_H ================================================ FILE: src/manager/core/singleapplication.cpp ================================================ #include "singleapplication.h" #include #include #include SingleApplication::SingleApplication(int& argc, char** argv) : QApplication(argc, argv), server_(nullptr), window_(nullptr), isActivateOnMessage_(false) { QString id = QApplication::applicationFilePath().replace('/', '.'); initialize(id); } SingleApplication::SingleApplication(const QString& id, int& argc, char** argv) : QApplication(argc, argv), server_(nullptr), window_(nullptr), isActivateOnMessage_(false) { initialize(id); } SingleApplication::~SingleApplication() { finalize(); } bool SingleApplication::isRunning() const { return !server_; } QWidget* SingleApplication::activationWindow() const { return window_; } void SingleApplication::setActivationWindow(QWidget* window) { window_ = window; } bool SingleApplication::isActivateOnMessage() const { return isActivateOnMessage_; } void SingleApplication::setActivateOnMessage(bool enable) { isActivateOnMessage_ = enable; } void SingleApplication::activateWindow() { if(window_) { window_->show(); window_->activateWindow(); } } bool SingleApplication::sendMessage(const QString& message) { QLocalSocket socket; socket.connectToServer(id_); if(socket.waitForConnected(kConnectTimeout_)) { socket.write(message.toUtf8()); return true; } return false; } void SingleApplication::initialize(const QString& id) { id_ = id; QLocalSocket socket; socket.connectToServer(id); if(socket.waitForConnected(kConnectTimeout_)) return; server_ = new QLocalServer(this); connect(server_, SIGNAL(newConnection()), SLOT(processClientConnection())); if(!server_->listen(id)) { if(server_->serverError() == QAbstractSocket::AddressInUseError) { QLocalServer::removeServer(id); if(!server_->listen(id)) finalize(); } } } void SingleApplication::finalize() { if(server_) { delete server_; server_ = nullptr; id_.clear(); } } void SingleApplication::processClientConnection() { QLocalSocket* socket = server_->nextPendingConnection(); if(socket) { QString message; if(socket->waitForReadyRead(kReadTimeout_)) message = socket->readAll(); delete socket; if(!message.isEmpty()) { if(isActivateOnMessage_) activateWindow(); emit messageReceived(message); } else if(!isActivateOnMessage_) { activateWindow(); } } } ================================================ FILE: src/manager/core/singleapplication.h ================================================ #ifndef CORE_SINGLEAPPLICATION_H #define CORE_SINGLEAPPLICATION_H #include #ifdef qApp #undef qApp #define qApp (static_cast(QApplication::instance())) #endif class QLocalServer; class SingleApplication : public QApplication { Q_OBJECT public: SingleApplication(int& argc, char** argv); SingleApplication(const QString& id, int& argc, char** argv); ~SingleApplication(); bool isRunning() const; QWidget* activationWindow() const; void setActivationWindow(QWidget* window); bool isActivateOnMessage() const; void setActivateOnMessage(bool enable); public slots: void activateWindow(); bool sendMessage(const QString& message); signals: void messageReceived(const QString& message); private: static const int kConnectTimeout_ = 500; static const int kReadTimeout_ = 1000; QString id_; QLocalServer* server_; QWidget* window_; bool isActivateOnMessage_; void initialize(const QString& id); void finalize(); private slots: void processClientConnection(); }; #endif // CORE_SINGLEAPPLICATION_H ================================================ FILE: src/manager/forms/filedialog.cpp ================================================ #include "filedialog.h" #include #include #include #include #include #include #include #include "forms/folderdialog.h" #include "models/directorymodel.h" #include "widgets/directoryview.h" #include "widgets/lineedit.h" FileDialog::FileDialog(DialogMode mode, QWidget* parent) : QDialog(parent), dialogMode_(mode), acceptMode_(kAcceptFile) { setupUi(); setRootDirectory(QDir::rootPath()); setDirectory(QDir::homePath()); } void FileDialog::setupUi() { resize(600, 450); QLabel* label = new QLabel("Directory: "); currentDirEdit_ = new LineEdit; currentDirEdit_->setReadOnly(true); currentDirEdit_->setStyleSheet("QLineEdit { border: 1px solid #AAAAAA; }"); goUpButton_ = new QToolButton; goUpButton_->setIconSize(QSize(20, 20)); goUpButton_->setIcon(QIcon(":/go_up.png")); goUpButton_->setToolTip("Go to the upper folder"); goUpButton_->setAutoRaise(true); connect(goUpButton_, SIGNAL(clicked()), SLOT(goUp())); createDirButton_ = new QToolButton; createDirButton_->setIconSize(QSize(20, 20)); createDirButton_->setIcon(QIcon(":/create_folder.png")); createDirButton_->setToolTip("Create new folder"); createDirButton_->setAutoRaise(true); connect(createDirButton_, SIGNAL(clicked()), SLOT(onCreateDirButtonClicked())); toggleHiddenButton_ = new QToolButton; toggleHiddenButton_->setIconSize(QSize(20, 20)); toggleHiddenButton_->setIcon(QIcon(":/show.png")); toggleHiddenButton_->setToolTip("Show hidden files"); toggleHiddenButton_->setAutoRaise(true); toggleHiddenButton_->setCheckable(true); connect(toggleHiddenButton_, SIGNAL(toggled(bool)), SLOT(setShowHidden(bool))); QHBoxLayout* currentDirLayout = new QHBoxLayout; currentDirLayout->setContentsMargins(2, 0, 2, 0); currentDirLayout->setSpacing(2); currentDirLayout->addWidget(label); currentDirLayout->addWidget(currentDirEdit_); currentDirLayout->addWidget(goUpButton_); currentDirLayout->addWidget(createDirButton_); currentDirLayout->addWidget(toggleHiddenButton_); model_ = new DirectoryModel; view_ = new DirectoryView; view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); view_->setModel(model_); connect(view_, SIGNAL(currentItemChanged(DirectoryItem*,DirectoryItem*)), SLOT(onItemChanged(DirectoryItem*))); connect(view_, SIGNAL(itemDoubleClicked(DirectoryItem*)), SLOT(onItemDoubleClicked(DirectoryItem*))); QHeaderView* header = view_->header(); header->setStretchLastSection(false); header->setSectionResizeMode(0, QHeaderView::Stretch); nameEdit_ = new LineEdit; connect(nameEdit_, SIGNAL(textChanged(QString)), SLOT(onNameEditChanged(QString))); if(dialogMode_ == kOpenDialog) { actionButton_ = new QPushButton(QIcon(":/open.png"), "Open"); } else { actionButton_ = new QPushButton(QIcon(":/save.png"), "Save"); } actionButton_->setIconSize(QSize(16, 16)); connect(actionButton_, SIGNAL(clicked()), SLOT(accept())); cancelButton_ = new QPushButton(QIcon(":/remove.png"), "Cancel"); cancelButton_->setIconSize(QSize(16, 16)); connect(cancelButton_, SIGNAL(clicked()), SLOT(reject())); QGridLayout* bottomLayout = new QGridLayout; bottomLayout->setContentsMargins(1, 4, 1, 4); bottomLayout->setSpacing(5); bottomLayout->addWidget(new QLabel("File name: "), 0, 0); bottomLayout->addWidget(nameEdit_, 0, 1); bottomLayout->addWidget(actionButton_, 0, 2); bottomLayout->addWidget(cancelButton_, 1, 2); QVBoxLayout* mainLayout = new QVBoxLayout; mainLayout->setMargin(1); mainLayout->setSpacing(1); mainLayout->addLayout(currentDirLayout); mainLayout->addWidget(view_); mainLayout->addLayout(bottomLayout); setLayout(mainLayout); onNameEditChanged(QString()); } FileDialog::AcceptMode FileDialog::acceptMode() const { return acceptMode_; } void FileDialog::setAcceptMode(FileDialog::AcceptMode mode) { acceptMode_ = mode; model_->setFilesEnabled(mode == kAcceptFile || mode == kAcceptExistingFile); } QDir::Filters FileDialog::filters() const { return model_->filters(); } void FileDialog::setFilter(QDir::Filters filters) { model_->setFilters(filters); } QStringList FileDialog::nameFilters() const { return model_->nameFilters(); } void FileDialog::setNameFilter(const QString& filter) { model_->setNameFilters(QStringList() << filter); } void FileDialog::setNameFilters(const QStringList& filters) { model_->setNameFilters(filters); } QString FileDialog::rootDirectory() const { return rootPath_; } void FileDialog::setRootDirectory(const QString& path) { QDir dir(path); if(!dir.exists()) return; rootPath_ = path; if(!model_->directory().startsWith(path)) model_->setDirectory(path); } QString FileDialog::directory() const { return model_->directory(); } void FileDialog::setDirectory(const QString& path) { if(!path.startsWith(rootPath_)) return; if(QFileInfo::exists(path)) { model_->setDirectory(path); goUpButton_->setEnabled(path != rootPath_); currentDirEdit_->setText(path); } } void FileDialog::goUp() { // if(rootPath_ == model_->directory()) // return; QDir dir(model_->directory() + "/.."); setDirectory(dir.absolutePath()); } bool FileDialog::showHidden() const { return model_->filters() & QDir::Hidden; } void FileDialog::setShowHidden(bool enable) { QDir::Filters filters = model_->filters(); if(enable) { filters |= QDir::Hidden; } else { filters &= ~QDir::Hidden; } model_->setFilters(filters); } void FileDialog::accept() { if(!nameEdit_->text().contains('.')) nameEdit_->setText(nameEdit_->text() + suffix_); selectedPath_ = model_->directory() + '/' + nameEdit_->text(); QDialog::accept(); } int FileDialog::exec() { selectedPath_.clear(); return QDialog::exec(); } QString FileDialog::selectedPath() const { return selectedPath_; } QString FileDialog::selectedName() const { DirectoryItem* item = view_->currentItem(); if(!item) return QString(); return item->name(); } QString FileDialog::defaultSuffix() const { return suffix_; } void FileDialog::setDefaultSuffix(const QString& suffix) { if(suffix_.startsWith('.')) { suffix_ = suffix.mid(1); } else { suffix_ = suffix; } } void FileDialog::onItemChanged(DirectoryItem* item) { if(!item || item->isDirectory()) { nameEdit_->clear(); if(acceptMode_ == kAcceptFile || acceptMode_ == kAcceptExistingFile) { actionButton_->setEnabled(false); } } else { nameEdit_->setText(item->name()); actionButton_->setEnabled(true); } } void FileDialog::onItemDoubleClicked(DirectoryItem* item) { if(item->isDirectory()) { setDirectory(item->fullPath()); } else if(acceptMode_ == kAcceptFile || acceptMode_ == kAcceptExistingFile) { accept(); } } void FileDialog::onNameEditChanged(const QString& text) { if(dialogMode_ == kSaveDialog) { actionButton_->setEnabled(!text.isEmpty()); } } void FileDialog::onCreateDirButtonClicked() { FolderDialog dialog(model_); dialog.exec(); } ================================================ FILE: src/manager/forms/filedialog.h ================================================ #ifndef FORMS_FILEDIALOG_H #define FORMS_FILEDIALOG_H #include #include class QFileSystemModel; class QItemSelection; class QPushButton; class QToolButton; class DirectoryItem; class DirectoryModel; class DirectoryView; class LineEdit; class FileDialog : public QDialog { Q_OBJECT public: enum DialogMode { kOpenDialog, kSaveDialog }; enum AcceptMode { kAcceptFile, kAcceptExistingFile, kAcceptDirectory, kAcceptExistingDirectory }; FileDialog(DialogMode mode, QWidget* parent = nullptr); AcceptMode acceptMode() const; void setAcceptMode(AcceptMode mode); QDir::Filters filters() const; void setFilter(QDir::Filters filters); QStringList nameFilters() const; void setNameFilter(const QString& filter); void setNameFilters(const QStringList& filters); bool showHidden() const; QString directory() const; QString rootDirectory() const; QString selectedPath() const; QString selectedName() const; QString defaultSuffix() const; public slots: void setShowHidden(bool enable); void setDirectory(const QString& path); void setRootDirectory(const QString& path); void setDefaultSuffix(const QString& suffix); void accept(); int exec(); private: LineEdit* currentDirEdit_; QToolButton* goUpButton_; QToolButton* createDirButton_; QToolButton* toggleHiddenButton_; DirectoryModel* model_; DirectoryView* view_; LineEdit* nameEdit_; QPushButton* actionButton_; QPushButton* cancelButton_; DialogMode dialogMode_; AcceptMode acceptMode_; QString rootPath_; QString selectedPath_; QString suffix_; void setupUi(); private slots: void goUp(); void onItemChanged(DirectoryItem* item); void onItemDoubleClicked(DirectoryItem* item); void onNameEditChanged(const QString& text); void onCreateDirButtonClicked(); }; #endif //FORMS_FILEDIALOG_H ================================================ FILE: src/manager/forms/folderdialog.cpp ================================================ #include "folderdialog.h" #include #include #include #include #include "models/directorymodel.h" #include "widgets/lineedit.h" FolderDialog::FolderDialog(DirectoryModel* model, QWidget* parent) : QDialog(parent), model_(model) { setupUi(); } void FolderDialog::accept() { QString name = nameEdit_->text(); QDir dir(model_->directory() + '/' + name); if(dir.exists()) { QString message = QString("Directory '%1' is already exists").arg(name); QMessageBox::critical(this, "Error", message); } else { dir.mkpath("."); QDialog::accept(); } } void FolderDialog::setupUi() { setWindowTitle("New folder"); nameEdit_ = new LineEdit; nameEdit_->setText("New folder"); nameEdit_->selectAll(); buttons_ = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons_, SIGNAL(accepted()), SLOT(accept())); connect(buttons_, SIGNAL(rejected()), SLOT(reject())); QGridLayout* layout = new QGridLayout; layout->addWidget(new QLabel("Folder name:"), 0, 0, Qt::AlignRight); layout->addWidget(nameEdit_, 0, 1); layout->addWidget(buttons_, 1, 0, 1, 2); setLayout(layout); } ================================================ FILE: src/manager/forms/folderdialog.h ================================================ #ifndef FORMS_FOLDERDIALOG_H #define FORMS_FOLDERDIALOG_H #include class QDialogButtonBox; class DirectoryModel; class LineEdit; class FolderDialog : public QDialog { Q_OBJECT public: FolderDialog(DirectoryModel* model, QWidget* parent = nullptr); public slots: void accept(); private: DirectoryModel* model_; LineEdit* nameEdit_; QDialogButtonBox* buttons_; void setupUi(); }; #endif // FORMS_FOLDERDIALOG_H ================================================ FILE: src/manager/forms/linkdialog.cpp ================================================ #include "linkdialog.h" #include #include #include #include #include #include #include #include "common/config.h" #include "core/application.h" #include "forms/filedialog.h" #include "models/linksmodel.h" #include "models/loadersmodel.h" #include "models/prefixesmodel.h" #include "widgets/lineedit.h" LinkDialog::LinkDialog(QWidget* parent) : QDialog(parent), item_(nullptr) { setupUi(); } LinkItem* LinkDialog::item() const { return item_; } void LinkDialog::setItem(LinkItem* item) { item_ = item; if(item) { locationEdit_->setText(item->location()); int index = prefixCombo_->findText(item->prefix()); prefixCombo_->setCurrentIndex(index); index = loaderCombo_->findText(item->loader()); loaderCombo_->setCurrentIndex(index); index = static_cast(item->logLevel()) + 1; logLevelCombo_->setCurrentIndex(index); nameEdit_->setText(item->name()); targetEdit_->setText(item->target()); } else { nameEdit_->clear(); locationEdit_->clear(); targetEdit_->clear(); int index = prefixCombo_->findText("default"); prefixCombo_->setCurrentIndex(index); index = loaderCombo_->findText("default"); loaderCombo_->setCurrentIndex(index); } } void LinkDialog::setupUi() { setWindowIcon(QIcon(":/edit_link.png")); setWindowTitle("Link properties"); setMinimumWidth(500); resize(600, 180); setMinimumHeight(260); loaderCombo_ = new QComboBox; loaderCombo_->setModel(qApp->loaders()); loaderCombo_->setCurrentIndex(loaderCombo_->findText("default")); prefixCombo_ = new QComboBox; prefixCombo_->setModel(qApp->prefixes()); prefixCombo_->setCurrentIndex(prefixCombo_->findText("default")); connect(prefixCombo_, SIGNAL(currentIndexChanged(int)), SLOT(onPrefixChanged())); logLevelCombo_ = new QComboBox; logLevelCombo_->addItem(QIcon(":/star.png"), "default"); logLevelCombo_->addItem(QIcon(":/mute.png"), "quiet"); logLevelCombo_->addItem(QIcon(":/warning.png"), "error"); logLevelCombo_->addItem(QIcon(":/trace.png"), "trace"); logLevelCombo_->addItem(QIcon(":/bug.png"), "debug"); logLevelCombo_->addItem(QIcon(":/scull.png"), "flood"); targetEdit_ = new LineEdit; targetEdit_->setButtonEnabled(true); targetEdit_->setButtonStyle(LineEdit::kLightAutoRaise); targetEdit_->setButtonIcon(QIcon(":/open.png")); targetEdit_->setButtonToolTip("Browse"); targetEdit_->setPrefix("${WINEPREFIX}/"); targetEdit_->setPrefixColor(Qt::darkGreen); connect(targetEdit_, SIGNAL(buttonClicked()), SLOT(browsePlugin())); locationEdit_ = new LineEdit; locationEdit_->setButtonEnabled(true); locationEdit_->setButtonStyle(LineEdit::kLightAutoRaise); locationEdit_->setButtonIcon(QIcon(":/open.png")); locationEdit_->setButtonToolTip("Browse"); QSettings settings; QString vstPath = settings.value("vstPath", qgetenv("VST_PATH")).toString(); locationEdit_->setText(vstPath.split(':').first()); connect(locationEdit_, SIGNAL(buttonClicked()), SLOT(browseLocation())); nameEdit_ = new LineEdit; buttons_ = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons_, SIGNAL(accepted()), SLOT(accept())); connect(buttons_, SIGNAL(rejected()), SLOT(reject())); QGridLayout* mainLayout = new QGridLayout; mainLayout->addWidget(new QLabel("WINE loader:"), 0, 0, Qt::AlignRight); mainLayout->addWidget(loaderCombo_, 0, 1, 1, 1); mainLayout->addWidget(new QLabel("WINE prefix:"), 1, 0, Qt::AlignRight); mainLayout->addWidget(prefixCombo_, 1, 1, 1, 1); mainLayout->addWidget(new QLabel("VST plugin:"), 2, 0, Qt::AlignRight); mainLayout->addWidget(targetEdit_, 2, 1, 1, 2); mainLayout->addWidget(new QLabel("Link location:"), 3, 0, Qt::AlignRight); mainLayout->addWidget(locationEdit_, 3, 1, 1, 2); mainLayout->addWidget(new QLabel("Link name:"), 4, 0, Qt::AlignRight); mainLayout->addWidget(nameEdit_, 4, 1, 1, 2); mainLayout->addWidget(new QLabel("Log level:"), 5, 0, Qt::AlignRight); mainLayout->addWidget(logLevelCombo_, 5, 1, 1, 1); mainLayout->addWidget(new QWidget, 6, 0); mainLayout->addWidget(buttons_, 7, 1, 1, 2); mainLayout->setRowStretch(5, 1); mainLayout->setColumnStretch(0, 0); mainLayout->setColumnStretch(1, 0); mainLayout->setColumnStretch(2, 1); setLayout(mainLayout); } void LinkDialog::browsePlugin() { QString prefix = currentPrefix(); QFileInfo prefixInfo(prefix); if(!prefixInfo.isDir()) { QMessageBox::critical(this, "Error", "Selected prefix directory doesn't exists."); return; } FileDialog dialog(FileDialog::kOpenDialog); dialog.setAcceptMode(FileDialog::kAcceptExistingFile); dialog.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Files); dialog.setNameFilter("*.dll"); dialog.setWindowTitle("Select the source VST plugin"); dialog.setRootDirectory(prefix); if(targetEdit_->text().isEmpty()) { QFileInfo info(prefixInfo.absoluteFilePath(), "drive_c"); dialog.setDirectory(info.absoluteFilePath()); } else { QFileInfo info(prefix, targetEdit_->text()); while(!info.isDir()) info = QFileInfo(info.absolutePath()); dialog.setDirectory(info.absoluteFilePath()); } if(dialog.exec()) { QString prefixPath = prefixInfo.absoluteFilePath(); int length = prefixPath.length(); if(!prefixPath.endsWith('/')) length++; targetEdit_->setText(dialog.selectedPath().mid(length)); QString name = dialog.selectedName(); name.chop(4); // Remove ".dll" extension nameEdit_->setText(name); } } void LinkDialog::browseLocation() { FileDialog dialog(FileDialog::kOpenDialog); dialog.setAcceptMode(FileDialog::kAcceptExistingDirectory); dialog.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); dialog.setWindowTitle("Select directory where the link will be placed"); QString text = locationEdit_->text(); if(text.isEmpty()) { dialog.setDirectory(QDir::homePath()); } else { dialog.setDirectory(text); } if(dialog.exec()) { locationEdit_->setText(dialog.selectedPath()); } } void LinkDialog::accept() { QString prefix = currentPrefix(); QFileInfo vstInfo(prefix, targetEdit_->text()); if(!vstInfo.isFile() || vstInfo.suffix() != "dll") { QMessageBox::critical(this, "Error", "VST plugin is invalid or doesn't exists."); return; } QFileInfo locationInfo(locationEdit_->text()); if(!locationInfo.isDir()) { QMessageBox::critical(this, "Error", "Location directory doesn't exists."); return; } QString name = nameEdit_->text(); if(name.isEmpty()) { QMessageBox::critical(this, "Error", "Link name cannot be empty."); return; } QString pluginPath = getPluginPath(); if(pluginPath.isEmpty()) { QMessageBox::critical(this, "Error", "VST plugin is corrupted."); return; } int index = logLevelCombo_->currentIndex(); Airwave::LogLevel level = static_cast(index - 1); if(level == Airwave::LogLevel::kFlood) { QString message = "WARNING!
" "By using the 'flood' log level, you will get an enormous count of log " "messages from this link, the plugin performance will be low and the " "audio playback may become very choppy.

" "Do you really want to proceed?"; if(QMessageBox::question(this, "Question", message) == QMessageBox::No) return; } if(!item_) { item_ = qApp->links()->createLink(nameEdit_->text(), locationEdit_->text(), targetEdit_->text(), prefixCombo_->currentText(), loaderCombo_->currentText()); if(!item_) { QMessageBox::critical(this, "Error", "Unable to create link."); return; } int value = logLevelCombo_->currentIndex() - 1; item_->setLogLevel(static_cast(value)); } else { if(item_->name() != name) { LinkItem* item = qApp->links()->root()->firstChild(); while(item) { if(item->name() == name) { QString message = QString("Link with name '%1' is already exists.") .arg(name); QMessageBox::critical(this, "Error", message); return; } item = item->nextSibling(); } } QDir dir(locationInfo.absoluteFilePath()); dir.remove(item_->name() + ".so"); item_->setName(nameEdit_->text()); item_->setLocation(locationEdit_->text()); item_->setTarget(targetEdit_->text()); item_->setPrefix(prefixCombo_->currentText()); item_->setLoader(loaderCombo_->currentText()); int value = logLevelCombo_->currentIndex() - 1; item_->setLogLevel(static_cast(value)); } qApp->storage()->save(); QFile::copy(pluginPath, locationInfo.absoluteFilePath() + '/' + name + ".so"); QDialog::accept(); } void LinkDialog::onPrefixChanged() { targetEdit_->clear(); nameEdit_->clear(); } QString LinkDialog::currentPrefix() const { int index = prefixCombo_->currentIndex(); if(index != -1) { PrefixItem* item = qApp->prefixes()->root()->childAt(index); if(item) return item->path(); } return QString(); } QString LinkDialog::getPluginPath() const { QString pluginPath = QString::fromStdString(qApp->storage()->binariesPath()); return pluginPath + "/" PLUGIN_BASENAME ".so"; } ================================================ FILE: src/manager/forms/linkdialog.h ================================================ #ifndef FORMS_LINKEDITDIALOG_H #define FORMS_LINKEDITDIALOG_H #include class QComboBox; class QDialogButtonBox; class LineEdit; class LinkItem; class LinkDialog : public QDialog { Q_OBJECT public: LinkDialog(QWidget* parent = nullptr); LinkItem* item() const; void setItem(LinkItem* item); private: QComboBox* loaderCombo_; QComboBox* prefixCombo_; QComboBox* logLevelCombo_; LineEdit* targetEdit_; LineEdit* locationEdit_; LineEdit* nameEdit_; QDialogButtonBox* buttons_; LinkItem* item_; void setupUi(); QString currentPrefix() const; QString getPluginPath() const; private slots: void browsePlugin(); void browseLocation(); void onPrefixChanged(); void accept(); }; #endif // FORMS_LINKEDITDIALOG_H ================================================ FILE: src/manager/forms/loaderdialog.cpp ================================================ #include "loaderdialog.h" #include #include #include #include #include #include "core/application.h" #include "forms/filedialog.h" #include "models/loadersmodel.h" #include "widgets/lineedit.h" LoaderDialog::LoaderDialog(QWidget* parent) : QDialog(parent), item_(nullptr) { setupUi(); } void LoaderDialog::setupUi() { setWindowIcon(QIcon(":/windows.png")); setWindowTitle("WINE loader properties"); setFixedWidth(320); setFixedHeight(130); nameEdit_ = new LineEdit; pathEdit_ = new LineEdit; pathEdit_->setButtonEnabled(true); pathEdit_->setButtonStyle(LineEdit::kLightAutoRaise); pathEdit_->setButtonIcon(QIcon(":/open.png")); pathEdit_->setButtonToolTip("Browse"); connect(pathEdit_, SIGNAL(buttonClicked()), SLOT(browseForWineLoader())); buttons_ = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons_, SIGNAL(accepted()), SLOT(accept())); connect(buttons_, SIGNAL(rejected()), SLOT(reject())); QGridLayout* mainLayout = new QGridLayout; mainLayout->addWidget(new QLabel("Name:"), 0, 0, Qt::AlignRight); mainLayout->addWidget(nameEdit_, 0, 1); mainLayout->addWidget(new QLabel("Path:"), 1, 0, Qt::AlignRight); mainLayout->addWidget(pathEdit_, 1, 1); mainLayout->addWidget(new QWidget, 2, 1); mainLayout->setRowStretch(2, 1); mainLayout->addWidget(buttons_, 3, 0, 1, -1); setLayout(mainLayout); } void LoaderDialog::browseForWineLoader() { FileDialog dialog(FileDialog::kOpenDialog); dialog.setAcceptMode(FileDialog::kAcceptExistingFile); dialog.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Files); dialog.setWindowTitle("Select the WINE loader binary"); QString text = pathEdit_->text(); if(text.isEmpty()) { dialog.setDirectory(QDir::homePath()); } else { dialog.setDirectory(text); } if(dialog.exec()) { pathEdit_->setText(dialog.selectedPath()); } } LoaderItem* LoaderDialog::item() const { return item_; } void LoaderDialog::setItem(LoaderItem* item) { item_ = item; if(item_) { nameEdit_->setText(item->name()); pathEdit_->setText(item->path()); } else { nameEdit_->clear(); pathEdit_->clear(); } } void LoaderDialog::accept() { QString name = nameEdit_->text(); QString message = QString("The loader with name '%1' is already exist.").arg(name); if(!item_) { if(!qApp->loaders()->createLoader(nameEdit_->text(), pathEdit_->text())) { QMessageBox::critical(this, "Error", message); return; } } else if(name != item_->name()) { Storage::Loader loader = qApp->storage()->loader(name.toStdString()); if(!loader.isNull()) { QMessageBox::critical(this, "Error", message); return; } item_->setName(nameEdit_->text()); item_->setPath(pathEdit_->text()); } else { item_->setPath(pathEdit_->text()); } QDialog::accept(); } ================================================ FILE: src/manager/forms/loaderdialog.h ================================================ #ifndef FORMS_LOADERDIALOG_H #define FORMS_LOADERDIALOG_H #include class QDialogButtonBox; class LineEdit; class LoaderItem; class LoaderDialog : public QDialog { Q_OBJECT public: LoaderDialog(QWidget* parent = nullptr); LoaderItem* item() const; void setItem(LoaderItem* item); private: LineEdit* nameEdit_; LineEdit* pathEdit_; QDialogButtonBox* buttons_; LoaderItem* item_; void setupUi(); private slots: void browseForWineLoader(); void accept(); }; #endif // FORMS_LOADERDIALOG_H ================================================ FILE: src/manager/forms/mainform.cpp ================================================ #include "mainform.h" #include #include #include #include #include #include #include #include #include #include #include "common/config.h" #include "core/application.h" #include "forms/linkdialog.h" #include "forms/settingsdialog.h" #include "models/linksmodel.h" #include "widgets/linksview.h" #include "widgets/logview.h" MainForm::MainForm(QWidget* parent) : QMainWindow(parent) { setupUi(); loadSettings(); updateToolbarButtons(); QString logSocketPath = QString::fromStdString(qApp->storage()->logSocketPath()); LogSocket* socket = qApp->logSocket(); if(!socket->listen(logSocketPath)) qDebug("Unable to create logger socket."); connect(socket, SIGNAL(newMessage(quint64,QString,QString)), logView_, SLOT(addMessage(quint64,QString,QString))); connect(qApp->links(), SIGNAL(rowsInserted(QModelIndex,int,int)), SLOT(updateToolbarButtons())); connect(qApp->links(), SIGNAL(rowsRemoved(QModelIndex,int,int)), SLOT(updateToolbarButtons())); connect(qApp->links(), SIGNAL(layoutChanged()), SLOT(updateToolbarButtons())); } MainForm::~MainForm() { saveSettings(); } void MainForm::loadSettings() { QSettings settings; settings.beginGroup("mainForm"); resize(settings.value("size", QSize(800, 600)).toSize()); restoreState(settings.value("windowState").toByteArray()); splitter_->restoreState(settings.value("mainSplitter").toByteArray()); toggleWordWrap_->setChecked(settings.value("logWordWrap", true).toBool()); toggleAutoScroll_->setChecked(settings.value("logAutoScroll", true).toBool()); QHeaderView* header = linksView_->header(); int width = settings.value("linkNameWidth", 150).toInt(); header->resizeSection(0, width); width = settings.value("logLevelWidth", 90).toInt(); header->resizeSection(1, width); width = settings.value("prefixNameWidth", 70).toInt(); header->resizeSection(2, width); width = settings.value("loaderNameWidth", 70).toInt(); header->resizeSection(3, width); settings.endGroup(); } void MainForm::saveSettings() { QSettings settings; settings.beginGroup("mainForm"); settings.setValue("size", size()); settings.setValue("windowState", saveState()); settings.setValue("mainSplitter", splitter_->saveState()); settings.setValue("logWordWrap", toggleWordWrap_->isChecked()); settings.setValue("logAutoScroll", toggleAutoScroll_->isChecked()); QHeaderView* header = linksView_->header(); settings.setValue("linkNameWidth", header->sectionSize(0)); settings.setValue("logLevelWidth", header->sectionSize(1)); settings.setValue("prefixNameWidth", header->sectionSize(2)); settings.setValue("loaderNameWidth", header->sectionSize(3)); settings.endGroup(); } void MainForm::setupUi() { setWindowIcon(QIcon(":/" PROJECT_NAME "-manager.png")); setWindowTitle(PROJECT_NAME " manager " VERSION_STRING); setCentralWidget(new QWidget); QVBoxLayout* layout = new QVBoxLayout; layout->setSpacing(0); layout->setMargin(1); linksView_ = new LinksView; linksView_->setModel(qApp->links()); QHeaderView* header = linksView_->header(); header->setStretchLastSection(false); header->setSectionResizeMode(0, QHeaderView::Interactive); header->setSectionResizeMode(1, QHeaderView::Interactive); header->setSectionResizeMode(2, QHeaderView::Interactive); header->setSectionResizeMode(3, QHeaderView::Interactive); header->setSectionResizeMode(4, QHeaderView::Stretch); connect(linksView_, SIGNAL(itemSelectionChanged(QItemSelection,QItemSelection)), SLOT(updateToolbarButtons())); connect(linksView_, SIGNAL(itemDoubleClicked(LinkItem*)), SLOT(editLink())); logView_ = new LogView; splitter_ = new QSplitter(Qt::Vertical); splitter_->addWidget(linksView_); splitter_->addWidget(logView_); int size = splitter_->height(); splitter_->setSizes(QList() << size * 0.618 << size * 0.382); layout->addWidget(splitter_); centralWidget()->setLayout(layout); // // Toolbar // toolBar_ = new QToolBar(this); toolBar_->setObjectName("toolBar_"); toolBar_->setFloatable(false); toolBar_->setMovable(false); toolBar_->setIconSize(QSize(20, 20)); addToolBar(toolBar_); // Create link action createLink_ = new QAction(QIcon(":/create_link.png"), "Create link", this); toolBar_->addAction(createLink_); connect(createLink_, SIGNAL(triggered()), SLOT(createLink())); // Edit link action editLink_ = new QAction(QIcon(":/edit.png"), "Edit link", this); editLink_->setEnabled(false); toolBar_->addAction(editLink_); connect(editLink_, SIGNAL(triggered()), SLOT(editLink())); // Remove link action removeLink_ = new QAction(QIcon(":/remove.png"), "Remove link", this); removeLink_->setEnabled(false); toolBar_->addAction(removeLink_); connect(removeLink_, SIGNAL(triggered()), SLOT(removeLink())); toolBar_->addSeparator(); // Show in file browser action showInBrowser_ = new QAction(QIcon(":/open_in_browser.png"), "Open in file manager the WINE prefix directory of the link", this); showInBrowser_->setEnabled(false); toolBar_->addAction(showInBrowser_); connect(showInBrowser_, SIGNAL(triggered()), SLOT(showInBrowser())); // Update all links action updateLinks_ = new QAction(QIcon(":/update.png"), "Update links", this); toolBar_->addAction(updateLinks_); connect(updateLinks_, SIGNAL(triggered()), SLOT(updateLinks())); toolBar_->addSeparator(); // Toggle word wrap action toggleWordWrap_ = new QAction( QIcon(":/outline.png"), "Wrap long lines in the log view", this); toggleWordWrap_->setCheckable(true); toolBar_->addAction(toggleWordWrap_); connect(toggleWordWrap_, SIGNAL(triggered(bool)), logView_, SLOT(setWordWrap(bool))); // Toggle auto scroll action toggleAutoScroll_ = new QAction( QIcon(":/download.png"), "Autoscroll log on new message", this); toggleAutoScroll_->setCheckable(true); toolBar_->addAction(toggleAutoScroll_); connect(toggleAutoScroll_, SIGNAL(triggered(bool)), logView_, SLOT(setAutoScroll(bool))); // Add separator action addSeparator_ = new QAction(QIcon(":/draw_line.png"), "Add separation line", this); toolBar_->addAction(addSeparator_); connect(addSeparator_, SIGNAL(triggered()), logView_, SLOT(addSeparator())); // Clear log action clearLog_ = new QAction(QIcon(":/erase.png"), "Clear log messages", this); toolBar_->addAction(clearLog_); connect(clearLog_, SIGNAL(triggered()), logView_, SLOT(clear())); toolBar_->addSeparator(); QWidget* spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); toolBar_->addWidget(spacer); toolBar_->addSeparator(); // Show about window action // showAbout_ = new QAction(QIcon(":/about.png"), "About", this); // toolBar_->addAction(showAbout_); // connect(showAbout_, SIGNAL(triggered()), SLOT(showAbout())); // Show settings action showSettings_ = new QAction(QIcon(":/settings.png"), "Settings", this); toolBar_->addAction(showSettings_); connect(showSettings_, SIGNAL(triggered()), SLOT(showSettings())); } bool MainForm::checkBinaries() { QStringList files = qApp->checkMissingBinaries(); if(!files.isEmpty()) { QString message = "Some binaries aren't found, please choose the correct\n" "binaries location in settings dialog!\n\nThe missed binaries are:\n\n"; foreach(const QString& fileName, files) message += fileName + '\n'; QMessageBox::critical(this, "Error", message); return false; } return true; } void MainForm::createLink() { if(checkBinaries()) { LinkDialog dialog; dialog.exec(); } else { SettingsDialog dialog; dialog.exec(); } } void MainForm::editLink() { if(checkBinaries()) { LinkDialog dialog; dialog.setItem(linksView_->currentItem()); dialog.exec(); } else { SettingsDialog dialog; dialog.exec(); } } void MainForm::removeLink() { LinkItem* item = linksView_->currentItem(); if(!item) return; QString message = QString("Do you really want to remove the '%1' link?") .arg(item->name()); if(QMessageBox::question(this, "Question", message) == QMessageBox::Yes) { QFileInfo info(item->path()); QString fileName = item->name() + ".so"; if(qApp->links()->removeLink(linksView_->currentItem())) { info.dir().remove(fileName); qApp->storage()->save(); } } } void MainForm::updateLinks() { QString pluginPath = QString::fromStdString(qApp->storage()->binariesPath()); LinkItem* item = qApp->links()->root()->firstChild(); while(item) { QFileInfo linkInfo(item->path()); QDir dir(linkInfo.absoluteDir()); dir.remove(linkInfo.fileName()); QString pluginName = PLUGIN_BASENAME ".so"; QFile::copy(pluginPath + '/' + pluginName, linkInfo.absoluteFilePath()); item = item->nextSibling(); } } void MainForm::showInBrowser() { LinkItem* item = linksView_->currentItem(); if(!item) return; auto prefix = qApp->storage()->prefix(item->prefix().toStdString()); if(!prefix) { QMessageBox::critical(this, "Error", "WINE prefix is corrupted"); return; } QString path = QString::fromStdString(prefix.path()); if(!QDir(path).exists()) { QMessageBox::critical(this, "Error", "WINE prefix directory doesn't exist"); return; } path = QDir::toNativeSeparators(path); QDesktopServices::openUrl(QUrl("file:///" + path)); } void MainForm::showAbout() { } void MainForm::showSettings() { SettingsDialog dialog; dialog.exec(); } void MainForm::updateToolbarButtons() { bool enable = linksView_->hasSelection(); editLink_->setEnabled(enable); showInBrowser_->setEnabled(enable); removeLink_->setEnabled(enable); updateLinks_->setEnabled(linksView_->model()->root()->childCount()); } ================================================ FILE: src/manager/forms/mainform.h ================================================ #ifndef FORMS_MAINFORM_H #define FORMS_MAINFORM_H #include class QAction; class QSplitter; class LinksModel; class LinksView; class LogView; class MainForm : public QMainWindow { Q_OBJECT public: explicit MainForm(QWidget* parent = nullptr); ~MainForm(); public slots: void loadSettings(); void saveSettings(); private: QToolBar* toolBar_; QAction* createLink_; QAction* editLink_; QAction* showInBrowser_; QAction* removeLink_; QAction* updateLinks_; QAction* toggleWordWrap_; QAction* toggleAutoScroll_; QAction* addSeparator_; QAction* clearLog_; QAction* showAbout_; QAction* showSettings_; QSplitter* splitter_; LinksView* linksView_; LogView* logView_; void setupUi(); bool checkBinaries(); private slots: void createLink(); void editLink(); void removeLink(); void updateLinks(); void showInBrowser(); void showAbout(); void showSettings(); void updateToolbarButtons(); }; #endif // FORMS_MAINFORM_H ================================================ FILE: src/manager/forms/prefixdialog.cpp ================================================ #include "prefixdialog.h" #include #include #include #include #include #include "core/application.h" #include "forms/filedialog.h" #include "models/prefixesmodel.h" #include "widgets/lineedit.h" PrefixDialog::PrefixDialog(QWidget* parent) : QDialog(parent), item_(nullptr) { setupUi(); } void PrefixDialog::setupUi() { setWindowIcon(QIcon(":/windows.png")); setWindowTitle("WINE prefix properties"); setFixedWidth(320); setFixedHeight(130); nameEdit_ = new LineEdit; pathEdit_ = new LineEdit; pathEdit_->setButtonEnabled(true); pathEdit_->setButtonStyle(LineEdit::kLightAutoRaise); pathEdit_->setButtonIcon(QIcon(":/open.png")); pathEdit_->setButtonToolTip("Browse"); connect(pathEdit_, SIGNAL(buttonClicked()), SLOT(browseForWinePrefix())); buttons_ = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons_, SIGNAL(accepted()), SLOT(accept())); connect(buttons_, SIGNAL(rejected()), SLOT(reject())); QGridLayout* mainLayout = new QGridLayout; mainLayout->addWidget(new QLabel("Name:"), 0, 0, Qt::AlignRight); mainLayout->addWidget(nameEdit_, 0, 1); mainLayout->addWidget(new QLabel("Path:"), 1, 0, Qt::AlignRight); mainLayout->addWidget(pathEdit_, 1, 1); mainLayout->addWidget(new QWidget, 2, 1); mainLayout->setRowStretch(2, 1); mainLayout->addWidget(buttons_, 3, 0, 1, -1); setLayout(mainLayout); } void PrefixDialog::browseForWinePrefix() { FileDialog dialog(FileDialog::kOpenDialog); dialog.setAcceptMode(FileDialog::kAcceptExistingDirectory); dialog.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); dialog.setWindowTitle("Select the WINE prefix directory"); QString text = pathEdit_->text(); if(text.isEmpty()) { dialog.setDirectory(QDir::homePath()); } else { dialog.setDirectory(text); } if(dialog.exec()) { pathEdit_->setText(dialog.selectedPath()); } } PrefixItem* PrefixDialog::item() const { return item_; } void PrefixDialog::setItem(PrefixItem* item) { item_ = item; if(item_) { nameEdit_->setText(item->name()); pathEdit_->setText(item->path()); } else { nameEdit_->clear(); pathEdit_->clear(); } } void PrefixDialog::accept() { QString name = nameEdit_->text(); QString message = QString("The prefix with name '%1' is already exist.").arg(name); if(!item_) { if(!qApp->prefixes()->createPrefix(nameEdit_->text(), pathEdit_->text())) { QMessageBox::critical(this, "Error", message); return; } } else if(name != item_->name()) { Storage::Prefix prefix = qApp->storage()->prefix(name.toStdString()); if(!prefix.isNull()) { QMessageBox::critical(this, "Error", message); return; } item_->setName(nameEdit_->text()); item_->setPath(pathEdit_->text()); } else { item_->setPath(pathEdit_->text()); } QDialog::accept(); } ================================================ FILE: src/manager/forms/prefixdialog.h ================================================ #ifndef FORMS_PREFIXDIALOG_H #define FORMS_PREFIXDIALOG_H #include class QDialogButtonBox; class LineEdit; class PrefixItem; class PrefixDialog : public QDialog { Q_OBJECT public: PrefixDialog(QWidget* parent = nullptr); PrefixItem* item() const; void setItem(PrefixItem* item); private: LineEdit* nameEdit_; LineEdit* pathEdit_; QDialogButtonBox* buttons_; PrefixItem* item_; void setupUi(); private slots: void browseForWinePrefix(); void accept(); }; #endif // FORMS_PREFIXDIALOG_H ================================================ FILE: src/manager/forms/settingsdialog.cpp ================================================ #include "settingsdialog.h" #include #include #include #include #include #include #include #include #include #include "common/config.h" #include "core/application.h" #include "core/logsocket.h" #include "forms/filedialog.h" #include "forms/loaderdialog.h" #include "forms/prefixdialog.h" #include "models/loadersmodel.h" #include "models/prefixesmodel.h" #include "widgets/lineedit.h" #include "widgets/loadersview.h" #include "widgets/prefixesview.h" #include "widgets/separatorlabel.h" SettingsDialog::SettingsDialog(QWidget* parent) : QDialog(parent) { setupUi(); QSettings settings; QString vstPath = settings.value("vstPath", qgetenv("VST_PATH")).toString(); vstPathEdit_->setText(vstPath.split(':').first()); Storage* storage = qApp->storage(); binariesPathEdit_->setText(QString::fromStdString(storage->binariesPath())); logSocketEdit_->setText(QString::fromStdString(storage->logSocketPath())); int index = static_cast(storage->defaultLogLevel()); logLevelCombo_->setCurrentIndex(index); } SettingsDialog::~SettingsDialog() { QSettings settings; settings.setValue("vstPath", vstPathEdit_->text()); } void SettingsDialog::setupUi() { setWindowIcon(QIcon(":/settings.png")); setMinimumWidth(400); resize(500, 450); vstPathEdit_ = new LineEdit; vstPathEdit_->setToolTip("Directory, where all of your native VSTs are located"); vstPathEdit_->setButtonEnabled(true); vstPathEdit_->setButtonStyle(LineEdit::kLightAutoRaise); vstPathEdit_->setButtonIcon(QIcon(":/open.png")); vstPathEdit_->setButtonToolTip("Browse"); connect(vstPathEdit_, SIGNAL(buttonClicked()), SLOT(browseForVstPath())); binariesPathEdit_ = new LineEdit; binariesPathEdit_->setToolTip("Directory, where airwave binaries are located"); binariesPathEdit_->setButtonEnabled(true); binariesPathEdit_->setButtonStyle(LineEdit::kLightAutoRaise); binariesPathEdit_->setButtonIcon(QIcon(":/open.png")); binariesPathEdit_->setButtonToolTip("Browse"); connect(binariesPathEdit_, SIGNAL(buttonClicked()), SLOT(browseForBinariesPath())); logSocketEdit_ = new LineEdit; logSocketEdit_->setToolTip("Socket file, used for logging"); logSocketEdit_->setButtonEnabled(true); logSocketEdit_->setButtonStyle(LineEdit::kLightAutoRaise); logSocketEdit_->setButtonIcon(QIcon(":/open.png")); logSocketEdit_->setButtonToolTip("Browse"); connect(logSocketEdit_, SIGNAL(buttonClicked()), SLOT(browseForSocketPath())); logLevelCombo_ = new QComboBox; logLevelCombo_->setToolTip("Log level, used for links with the 'default' log level.\n" "The higher the level, the more messages will appear."); logLevelCombo_->addItem(QIcon(":/mute.png"), "quiet"); logLevelCombo_->addItem(QIcon(":/warning.png"), "error"); logLevelCombo_->addItem(QIcon(":/trace.png"), "trace"); logLevelCombo_->addItem(QIcon(":/bug.png"), "debug"); logLevelCombo_->addItem(QIcon(":/scull.png"), "flood"); QGridLayout* generalLayout = new QGridLayout; generalLayout->addWidget(new QLabel("VST location:"), 0, 0, Qt::AlignRight); generalLayout->addWidget(vstPathEdit_, 0, 1, 1, 4); generalLayout->addWidget(new QLabel("Binaries location:"), 1, 0, Qt::AlignRight); generalLayout->addWidget(binariesPathEdit_, 1, 1, 1, 4); generalLayout->addWidget(new QLabel("Log socket path:"), 2, 0, Qt::AlignRight); generalLayout->addWidget(logSocketEdit_, 2, 1, 1, 4); generalLayout->addWidget(new QLabel("Default log level:"), 3, 0, Qt::AlignRight); generalLayout->addWidget(logLevelCombo_, 3, 1); prefixesView_ = new PrefixesView; prefixesView_->setModel(qApp->prefixes()); addPrefixButton_ = new QPushButton("Add"); connect(addPrefixButton_, SIGNAL(clicked()), SLOT(createPrefix())); editPrefixButton_ = new QPushButton("Edit"); connect(editPrefixButton_, SIGNAL(clicked()), SLOT(editPrefix())); removePrefixButton_ = new QPushButton("Remove"); connect(removePrefixButton_, SIGNAL(clicked()), SLOT(removePrefix())); QVBoxLayout* vl = new QVBoxLayout; vl->addWidget(addPrefixButton_); vl->addWidget(editPrefixButton_); vl->addWidget(removePrefixButton_); vl->addStretch(1); QHBoxLayout* prefixLayout = new QHBoxLayout; prefixLayout->addWidget(prefixesView_); prefixLayout->addLayout(vl); loadersView_ = new LoadersView; loadersView_->setModel(qApp->loaders()); addLoaderButton_ = new QPushButton("Add"); connect(addLoaderButton_, SIGNAL(clicked()), SLOT(createLoader())); editLoaderButton_ = new QPushButton("Edit"); connect(editLoaderButton_, SIGNAL(clicked()), SLOT(editLoader())); removeLoaderButton_ = new QPushButton("Remove"); connect(removeLoaderButton_, SIGNAL(clicked()), SLOT(removeLoader())); vl = new QVBoxLayout; vl->addWidget(addLoaderButton_); vl->addWidget(editLoaderButton_); vl->addWidget(removeLoaderButton_); vl->addStretch(1); QHBoxLayout* loaderslayout = new QHBoxLayout; loaderslayout->addWidget(loadersView_); loaderslayout->addLayout(vl); buttons_ = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons_, SIGNAL(accepted()), SLOT(accept())); connect(buttons_, SIGNAL(rejected()), SLOT(reject())); QVBoxLayout* mainLayout = new QVBoxLayout; mainLayout->addWidget(new SeparatorLabel("General:")); mainLayout->addLayout(generalLayout); mainLayout->addSpacing(10); mainLayout->addWidget(new SeparatorLabel("WINE prefixes:")); mainLayout->addLayout(prefixLayout); mainLayout->addSpacing(10); mainLayout->addWidget(new SeparatorLabel("WINE loaders:")); mainLayout->addLayout(loaderslayout); mainLayout->addSpacing(10); mainLayout->addWidget(buttons_); setLayout(mainLayout); } void SettingsDialog::browseForVstPath() { FileDialog dialog(FileDialog::kOpenDialog); dialog.setAcceptMode(FileDialog::kAcceptExistingDirectory); dialog.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); dialog.setWindowTitle("Select directory with the native VST plugins"); QString path = vstPathEdit_->text(); QFileInfo info(path); if(!info.exists(path) || !info.isDir()) path = QDir::homePath(); dialog.setDirectory(path); if(dialog.exec()) vstPathEdit_->setText(dialog.selectedPath()); } void SettingsDialog::browseForBinariesPath() { FileDialog dialog(FileDialog::kOpenDialog); dialog.setAcceptMode(FileDialog::kAcceptExistingDirectory); dialog.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Files); QStringList nameFilters; nameFilters << HOST_BASENAME "-32.exe" << HOST_BASENAME "-64.exe"; nameFilters << PLUGIN_BASENAME ".so"; dialog.setNameFilters(nameFilters); dialog.setWindowTitle("Select directory containing airwave binaries"); QString path = binariesPathEdit_->text(); if(path.isEmpty()) path = QString::fromStdString(qApp->storage()->binariesPath()); dialog.setDirectory(path); if(dialog.exec()) binariesPathEdit_->setText(dialog.selectedPath()); } void SettingsDialog::browseForSocketPath() { FileDialog dialog(FileDialog::kSaveDialog); dialog.setAcceptMode(FileDialog::kAcceptFile); dialog.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Files); dialog.setDefaultSuffix(".sock"); dialog.setWindowTitle("Enter file name of domain socket"); QString path = logSocketEdit_->text(); if(path.isEmpty()) path = QString::fromStdString(qApp->storage()->logSocketPath()); QFileInfo info(path); path = info.absolutePath(); dialog.setDirectory(path); if(dialog.exec()) logSocketEdit_->setText(dialog.selectedPath()); } void SettingsDialog::createPrefix() { PrefixDialog dialog; dialog.exec(); } void SettingsDialog::editPrefix() { PrefixItem* item = prefixesView_->currentItem(); if(!item) { QMessageBox::critical(this, "Error", "You should select prefix item to edit."); return; } if(item->name() == "default") { QMessageBox::critical(this, "Error", "You cannot edit default WINE prefix."); return; } PrefixDialog dialog; dialog.setItem(item); dialog.exec(); } void SettingsDialog::removePrefix() { PrefixItem* item = prefixesView_->currentItem(); if(!item) { QMessageBox::critical(this, "Error", "You should select prefix item to remove."); return; } QString prefix = item->name(); if(prefix == "default") { QMessageBox::critical(this, "Error", "You cannot remove default WINE prefix."); return; } QString text = QString("Do you really want to remove the '%1' prefix?").arg(prefix); if(QMessageBox::question(this, "Question", text) == QMessageBox::Yes) { if(!qApp->prefixes()->removePrefix(item)) QMessageBox::critical(this, "Error", "Unable to delete selected prefix."); } } void SettingsDialog::createLoader() { LoaderDialog dialog; dialog.exec(); } void SettingsDialog::editLoader() { LoaderItem* item = loadersView_->currentItem(); if(!item) { QMessageBox::critical(this, "Error", "You should select loader item to edit."); return; } if(item->name() == "default") { QMessageBox::critical(this, "Error", "You cannot edit default WINE loader."); return; } LoaderDialog dialog; dialog.setItem(item); dialog.exec(); } void SettingsDialog::removeLoader() { LoaderItem* item = loadersView_->currentItem(); if(!item) { QMessageBox::critical(this, "Error", "You should select loader item to remove."); return; } QString loader = item->name(); if(loader == "default") { QMessageBox::critical(this, "Error", "You cannot remove default WINE loader."); return; } QString text = QString("Do you really want to remove the '%1' loader?").arg(loader); if(QMessageBox::question(this, "Question", text) == QMessageBox::Yes) { if(!qApp->loaders()->removeLoader(item)) QMessageBox::critical(this, "Error", "Unable to delete selected loader."); } } void SettingsDialog::accept() { if(binariesPathEdit_->text().isEmpty()) { QMessageBox::critical(this, "Error", "You should select the binaries location."); return; } if(!QDir().exists(binariesPathEdit_->text())) { QMessageBox::critical(this, "Error", "Binaries location doesn't exists."); return; } QFileInfo fileInfo(binariesPathEdit_->text()); if(!fileInfo.isDir()) { QMessageBox::critical(this, "Error", "Binaries location is not a directory."); return; } QStringList files = qApp->checkMissingBinaries(binariesPathEdit_->text()); if(!files.isEmpty()) { QString message = "Some binaries aren't found, please choose the correct\n" "binaries location!\n\nThe missed binaries are:\n\n"; foreach(const QString& fileName, files) message += fileName + '\n'; QMessageBox::critical(this, "Error", message); return; } if(logSocketEdit_->text().isEmpty()) { QMessageBox::critical(this, "Error", "Log socket is not defined"); return; } Airwave::Storage* storage = qApp->storage(); int index = logLevelCombo_->currentIndex(); Airwave::LogLevel level = static_cast(index); if(level == Airwave::LogLevel::kFlood) { QString message = "WARNING!
" "By using the 'flood' log level as default, you will get an enormous " "count of log messages from links with 'default' log level, the " "performance will be low and the audio playback may become very choppy." "

" "Do you really want to proceed?"; if(QMessageBox::question(this, "Question", message) == QMessageBox::No) return; } LogSocket* socket = qApp->logSocket(); if(logSocketEdit_->text() != socket->id()) { socket->close(); socket->listen(logSocketEdit_->text()); } storage->setDefaultLogLevel(level); storage->setBinariesPath(binariesPathEdit_->text().toStdString()); storage->save(); QDialog::accept(); } ================================================ FILE: src/manager/forms/settingsdialog.h ================================================ #ifndef FORMS_SETTINGSDIALOG_H #define FORMS_SETTINGSDIALOG_H #include class QComboBox; class QDialogButtonBox; class QLabel; class QPushButton; class LineEdit; class LoadersModel; class LoadersView; class PrefixesModel; class PrefixesView; class SettingsDialog : public QDialog { Q_OBJECT public: SettingsDialog(QWidget* parent = nullptr); ~SettingsDialog(); private: LineEdit* vstPathEdit_; LineEdit* binariesPathEdit_; LineEdit* logSocketEdit_; QComboBox* logLevelCombo_; PrefixesView* prefixesView_; QPushButton* addPrefixButton_; QPushButton* editPrefixButton_; QPushButton* removePrefixButton_; LoadersView* loadersView_; QPushButton* addLoaderButton_; QPushButton* editLoaderButton_; QPushButton* removeLoaderButton_; QDialogButtonBox* buttons_; void setupUi(); private slots: void browseForVstPath(); void browseForBinariesPath(); void browseForSocketPath(); void createPrefix(); void editPrefix(); void removePrefix(); void createLoader(); void editLoader(); void removeLoader(); void accept(); }; #endif // FORMS_SETTINGSDIALOG_H ================================================ FILE: src/manager/main.cpp ================================================ #include "common/config.h" #include "core/application.h" #include "forms/mainform.h" int main(int argc, char** argv) { Application application(argc, argv); if(application.isRunning()) return EXIT_SUCCESS; application.setOrganizationName("phantom-code"); application.setOrganizationDomain("darkhub.net"); application.setApplicationName(PROJECT_NAME "-manager"); application.setApplicationVersion(VERSION_STRING); MainForm mainForm; mainForm.show(); application.setActivationWindow(&mainForm); return application.exec(); } ================================================ FILE: src/manager/models/directorymodel.cpp ================================================ #include "directorymodel.h" #include #include #include DirectoryItem::DirectoryItem(const QFileInfo& info) : info_(info), type_(getType()) { } bool DirectoryItem::isDirectory() const { return info_.isDir(); } QString DirectoryItem::name() const { return info_.fileName(); } QString DirectoryItem::path() const { return info_.filePath(); } QString DirectoryItem::fullPath() const { return info_.canonicalFilePath(); } i64 DirectoryItem::size() const { return i64(info_.size()); } QString DirectoryItem::humanReadableSize() const { const char* kUnitsTable[] = { " bytes", " KiB", " MiB", " GiB", " TiB" }; double value = size(); uint i = 0; while(value >= 1024.0 && i < sizeof(kUnitsTable)) { value /= 1024.0; ++i; } return QString().setNum(value, 'f', 1) + kUnitsTable[i]; } QString DirectoryItem::type() const { return type_; } QString DirectoryItem::getType() const { if(info_.isRoot()) return "Drive"; if(info_.isFile()) { if(!info_.suffix().isEmpty()) return QString("%1 File").arg(info_.suffix()); return "File"; } if(info_.isDir()) return "Folder"; if(info_.isSymLink()) return "Shortcut"; return "Unknown"; } DirectoryModel::DirectoryModel(QObject* parent) : GenericTreeModel(new DirectoryItem(), parent), filters_(QDir::AllEntries), isFilesEnabled_(true) { connect(&watcher_, SIGNAL(directoryChanged(QString)), SLOT(update(QString))); } int DirectoryModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 3; } QVariant DirectoryModel::data(const QModelIndex& index, int role) const { if(index.isValid()) { DirectoryItem* item = indexToItem(index); if(role == Qt::DisplayRole) { int column = index.column(); if(column == 0) { return item->name(); } else if(column == 1) { if(!item->isDirectory()) { return item->humanReadableSize(); } return ""; } else if(column == 2) { return item->type(); } } else if(role == Qt::DecorationRole && index.column() == 0) { if(item->name() == "..") { return qApp->style()->standardIcon(QStyle::SP_ArrowUp); } else if(item->isDirectory()) { return qApp->style()->standardIcon(QStyle::SP_DirIcon); } else { return qApp->style()->standardIcon(QStyle::SP_FileIcon); } } } return QVariant(); } QVariant DirectoryModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(orientation); if(role == Qt::DisplayRole) { if(section == 0) { return "Name"; } else if(section == 1) { return "Size"; } else if(section == 2) { return "Type"; } } return QVariant(); } Qt::ItemFlags DirectoryModel::flags(const QModelIndex& index) const { Qt::ItemFlags flags = GenericTreeModel::flags(index); DirectoryItem* item = indexToItem(index); if(item && !item->isDirectory() && !isFilesEnabled_) flags &= ~Qt::ItemIsEnabled; return flags; } void DirectoryModel::update(const QString& path) { QDir dir(path); if(!dir.exists()) return; clear(); dir_ = dir.canonicalPath(); dir_.setFilter(filters_); dir_.setNameFilters(nameFilters_); for(const QFileInfo& info : dir_.entryInfoList()) { if(dir.isRoot() && info.fileName() == "..") continue; DirectoryItem* item = new DirectoryItem(info); root()->insertChild(item); } sort(0, Qt::AscendingOrder); } QString DirectoryModel::directory() const { return dir_.canonicalPath(); } void DirectoryModel::setDirectory(const QString& path) { watcher_.removePath(dir_.canonicalPath()); update(path); watcher_.addPath(dir_.canonicalPath()); emit directoryChanged(dir_.canonicalPath()); } QStringList DirectoryModel::nameFilters() const { return QStringList(); } void DirectoryModel::setNameFilters(const QStringList& filters) { nameFilters_ = filters; update(directory()); } QDir::Filters DirectoryModel::filters() const { return filters_; } void DirectoryModel::setFilters(QDir::Filters filters) { filters_ = filters; update(directory()); } void DirectoryModel::sort(int column, Qt::SortOrder order) { Q_UNUSED(column); emit layoutAboutToBeChanged(); if(order == Qt::AscendingOrder) { root()->sortChildren(lessThan); } else { root()->sortChildren(greaterThan); } emit layoutChanged(); } bool DirectoryModel::lessThan(DirectoryItem* item1, DirectoryItem* item2) { if(item1->name() == "..") { return true; } else if(item2->name() == "..") { return false; } if(item1->isDirectory() == item2->isDirectory()) return item1->name().compare(item2->name(), Qt::CaseInsensitive) < 0; return item1->isDirectory(); } bool DirectoryModel::greaterThan(DirectoryItem* item1, DirectoryItem* item2) { if(item1->name() == "..") { return false; } else if(item2->name() == "..") { return true; } if(item1->isDirectory() == item2->isDirectory()) return item1->name().compare(item2->name(), Qt::CaseInsensitive) > 0; return item2->isDirectory(); } bool DirectoryModel::isFilesEnabled() const { return isFilesEnabled_; } void DirectoryModel::setFilesEnabled(bool enabled) { if(isFilesEnabled_ == enabled) return; isFilesEnabled_ = enabled; update(directory()); } ================================================ FILE: src/manager/models/directorymodel.h ================================================ #ifndef MODELS_DIRECTORYMODEL_H #define MODELS_DIRECTORYMODEL_H #include #include #include "common/types.h" #include "models/generictreemodel.h" class DirectoryItem : public GenericTreeItem { public: DirectoryItem(const QFileInfo& info = QFileInfo()); bool isDirectory() const; QString name() const; QString path() const; QString fullPath() const; i64 size() const; QString humanReadableSize() const; QString type() const; private: QFileInfo info_; QString type_; QString getType() const; }; class DirectoryModel : public GenericTreeModel { Q_OBJECT public: DirectoryModel(QObject* parent = nullptr); int columnCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; Qt::ItemFlags flags(const QModelIndex& index) const; QString directory() const; QStringList nameFilters() const; QDir::Filters filters() const; bool isFilesEnabled() const; public slots: void setDirectory(const QString& path); void setNameFilters(const QStringList& filters); void setFilters(QDir::Filters filters); void setFilesEnabled(bool enabled); signals: void directoryChanged(const QString& path); private: QDir dir_; QFileSystemWatcher watcher_; QStringList nameFilters_; QDir::Filters filters_; bool isFilesEnabled_; void sort(int column, Qt::SortOrder order); static bool lessThan(DirectoryItem* item1, DirectoryItem* item2); static bool greaterThan(DirectoryItem* item1, DirectoryItem* item2); private slots: void update(const QString& path); }; #endif // MODELS_DIRECTORYMODEL_H ================================================ FILE: src/manager/models/generictreemodel.h ================================================ #ifndef MODELS_GENERICTREEMODEL_H #define MODELS_GENERICTREEMODEL_H #include template class GenericTreeModel; template class GenericTreeItem { public: typedef bool (*LessThanProc)(Derived*, Derived*); /** * Конструирует новый элемент и устанавливает признак возможности отложенной загрузки * информации о его дочерних элементах. */ GenericTreeItem(bool canFetchMore = false); virtual ~GenericTreeItem(); /** * Возвращает родительский элемент или @c nullptr, в случае его отсутствия. */ Derived* parent() const; /** * Возвращает количество дочерниих элементов. */ int childCount() const; /** * Возвращает @c true, если @p item является дочерним элементом для текущего. */ bool hasChild(Derived* item) const; /** * Возвращает @c true, если элемент имеет хотя бы один дочерний элемент. */ bool hasChildren() const; /** * Возвращает дочерний элемент на позиции @p row. */ Derived* childAt(int row) const; /** * Возвращает первый дочерний элемент или @c nullptr, в случае его отсутствия. */ Derived* firstChild() const; /** * Возвращает последний дочерний элемент или @c nullptr, в случае его отсутствия. */ Derived* lastChild() const; /** * Возвращает следующий смежный элемент или @c nullptr, в случае его отсутствия. */ Derived* nextSibling() const; /** * Возвращает предыдущий смежный элемент или @c nullptr, в случае его отсутствия. */ Derived* previousSibling() const; /** * Производит вставку элемента @p item в дочерние элементы на позицию @p row. Если @p * row меньше нуля или больше количества дочерних элементов, то элемент @p item * помещается на последниюю позицию. Право владения элементом @p item передается * текущему элементу. * * @param item вставляемый элемент. * @param row позиция вставки. */ void insertChild(Derived* item, int row = -1); /** * Производит перемещение элемента @p item в дочерние элементы на позицию @p row. * Если @c row меньше нуля или больше количества дочерних элементов, то элемент @p * item помещается на последнюю позицию. Если @p item является вышестоящим элементом * или относится к другому экземпляру модели, то перемещения не происходит и функция * возвращает @c false. * * @param item перемещаемый элемент. * @param row позиция, на которую требуется переместить @p item. * @return @c true в случае успеха. */ bool moveChild(Derived* item, int row = -1); /** * Производит извлечение дочернего элемента с позиции @p row и возвращает этот * элемент. Если @p row меньше нуля или больше количества дочерних элементов, то * возвращается @c nullptr. Право владения элементом передается вызывающему коду. * * @param row позиция извлекаемого элемента. * @return извлеченный элемент или @c nullptr. */ Derived* takeChild(int row); /** * Производит извлечение дочернего элемента на позиции @p row с последующем его * уничтожением. * * @param row позиция удаляемого элемента. */ void removeChild(int row); /** * Рекурсивно уничтожает все дочерние элементы. */ void removeChildren(); Derived* takeFromParent(); /** * Возвращает позицию элемента в списке дочерних элементов владельца. */ int row() const; /** * Возвращает модель, к которой относится элемент, или @c nullptr, если элемент не * относится ни к одной модели. */ GenericTreeModel* model() const; void sortChildren(LessThanProc lessThan); /** * Возвращает @c true, если информация о дочерних элементах не была получена. */ bool canFetchMore() const; protected: /** * Устанавливает признак возможности получения информации о дочерних элементах. */ void setCanFetchMore(bool canFetchMore); /** * Получает информацию о дочерних элементах. Базовая реализация просто устанавливает * @p canFetchMore в @c false. При необходимости выполнять отложенную загрузку * потомки должны переопределить эту функцию и реализовать загрузку в ней. */ virtual void fetchMore(); /** * Производит уведомление модели о необходимости обновить данные элемента. Функция * должна вызываться потомками после любого изменения данных элемента. */ void updateData(); /** * Вызывается при установке элементу новой модели. При необходимости выполнить * дополнительные действия во время помещения элемента в модель, потомки должны * переопределить эту функцию и выполнить эти действия в ней. В переопределенной * функции запрещается производить действия над элементами модели, связанные со * вставкой, удалением или перемещением, т.к. это может привести к рекурсии или * непредсказуемому результату. */ virtual void attached() { } /** * Вызывается при извлечении элемента из модели. При необходимости выполнить * дополнительные действия во время извлечения элемента из модели, потомки должны * переопределить эту функцию и выполнить эти действия в ней. В переопределенной * функции запрещается производить действия над элементами модели, связанные со * вставкой, удалением или перемещением, т.к. это может привести к рекурсии или * непредсказуемому результату. */ virtual void detached() { } /** * Вызывается при изменении положения элемента. При необходимости выполнить * дополнительные действия по этому событию (например обновить parent id элемента в * БД) потомки должны переопределить эту функцию и выполнить требуемые действия в * ней. В переопределенной функции запрещается производить действия над элементами * модели, связанные со вставкой, удалением или перемещением, т.к. это может привести * к рекурсии или непредсказуемому результату. */ virtual void reattached() { } /** * Вызывается сразу после вставки дочернего элемента @p item. Потомки могут * переобпределить эту функцию, чтобы получать уведомления о событии. В * переопределенной функции запрещается производить действия над элементами модели, * связанные с вставкой, удалением или перемещением, т.к. это может привести к * рекурсии или непредсказуемому результату. * * @param item новый дочерний элемент. */ virtual void childInserted(Derived* item) { Q_UNUSED(item); } /** * Вызывается сразу после извлечения дочернего элемента @p item. Потомки могут * переобпределить эту функцию, чтобы получать уведомления о событии. В * переопределенной функции запрещается производить действия над элементами модели, * связанные с вставкой, удалением или перемещением, т.к. это может привести к * рекурсии или непредсказуемому результату. * * @param item извлеченный дочерний элемент. */ virtual void childRemoved(Derived* item) { Q_UNUSED(item); } private: friend class GenericTreeModel; Derived* parent_; QList children_; int row_; GenericTreeModel* model_; bool canFetchMore_; void attach(); void detach(); }; template class GenericTreeModel : public QAbstractItemModel { public: typedef T ItemType; /** * Конструирует модель и устанавливает root в качестве фиктивного корневого элемента. */ GenericTreeModel(T* root = new T(), QObject* parent = nullptr); virtual ~GenericTreeModel(); /** * Уничтожает все элементы модели. */ void clear(); /** * Преобразует модельный индекс @p index в элемент. В случае невалидного индекса * возвращает @c rootItem(). */ T* indexToItem(const QModelIndex& index) const; /** * Преобразует элемент в модельный индекс. В случае, если @p item равен @c nullptr, * или @p item не принадлежит модели, или @p item равен @c rootItem(), возвращается * невалидный модельный индекс. * * @param item преобразуемый элемент. * @param column колонка в преобразуемом элементе. */ QModelIndex itemToIndex(T* item, int column = 0) const; /** * Возвращает фиктивный корневой элемент модели. Данный элемент является невидимым * для всех работающих с моделью представлений и служит для унификации интерфейса * добавления/перемещения/удаления дочерних элементов. */ T* root() const; virtual QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const; virtual QModelIndex parent(const QModelIndex& index = QModelIndex()) const; virtual int rowCount(const QModelIndex& parent = QModelIndex()) const; virtual bool hasChildren(const QModelIndex& parent = QModelIndex()) const; virtual bool canFetchMore(const QModelIndex& parent = QModelIndex()) const; virtual void fetchMore(const QModelIndex& parent = QModelIndex()); protected: /** * Сбрасывает модель в ее первоначальное состояние. Базовая реализация просто * уничтожает все элементы модели, при этом вызов AbstractItemModel::reset() не * производится, поэтому функция является безопасной при использовании proxy моделей. */ void reset(); void updateData(T* item); private: friend class GenericTreeItem; T* rootItem_; void beginInsert(T* parentItem, int row, int count = 1); void endInsert(); bool beginMove(T* srcParent, int srcRow, T* destParent, int destRow, int count = 1); void endMove(); void beginRemove(T* parentItem, int row, int count = 1); void endRemove(); QModelIndex createNewIndex(int row, int column); void changePersistentIndexes(const QModelIndexList& from, const QModelIndexList& to); }; //---------------------------------- GenericTreeItem -----------------------------------// template GenericTreeItem::GenericTreeItem(bool canFetchMore) : parent_(nullptr), row_(0), model_(nullptr), canFetchMore_(canFetchMore) { } template GenericTreeItem::~GenericTreeItem() { qDeleteAll(children_); } template Derived* GenericTreeItem::parent() const { return parent_; } template int GenericTreeItem::childCount() const { return children_.count(); } template bool GenericTreeItem::hasChild(Derived* item) const { return (children_.indexOf(item) != -1); } template bool GenericTreeItem::hasChildren() const { return !children_.isEmpty(); } template Derived* GenericTreeItem::childAt(int row) const { return children_.at(row); } template Derived* GenericTreeItem::firstChild() const { if(children_.isEmpty()) return nullptr; return children_.first(); } template Derived* GenericTreeItem::lastChild() const { if(children_.isEmpty()) return nullptr; return children_.last(); } template Derived* GenericTreeItem::nextSibling() const { if(!parent_ || row_ + 1 == parent_->children_.count()) return nullptr; return parent_->children_.at(row_ + 1); } template Derived* GenericTreeItem::previousSibling() const { if(!parent_ || row_ == 0) return nullptr; return parent_->children_.at(row_ - 1); } template void GenericTreeItem::attach() { model_ = parent_->model_; Derived* item = static_cast(this); item = item->firstChild(); while(item) { item->attach(); item = item->nextSibling(); } attached(); } template void GenericTreeItem::detach() { model_ = nullptr; Derived* item = static_cast(this); item = item->firstChild(); while(item) { item->detach(); item = item->nextSibling(); } detached(); } template void GenericTreeItem::insertChild(Derived* item, int row) { Q_ASSERT(item); if(item->parent_) item->parent_->takeChild(item->row()); item->parent_ = static_cast(this); if((row < 0) || (row > children_.count())) item->row_ = children_.count(); else item->row_ = row; if(model_) model_->beginInsert(item->parent_, item->row_); for(int i = item->row_; i < children_.count(); ++i) children_[i]->row_++; children_.insert(item->row_, item); if(model_) { item->attach(); model_->endInsert(); } childInserted(item); } template bool GenericTreeItem::moveChild(Derived* item, int row) { Q_ASSERT(item); // Перемещать элементы можно только в пределах одной модели if(item->model_ != model_) return false; if((row < 0) || (row > children_.count())) row = children_.count(); int modelRow = row; Derived* oldParent = item->parent_; Derived* newParent = static_cast(this); if(oldParent == newParent) { // Если перемещение идет на свое собственно место, дополнительные действия не // требуются if(item->row_ == row) return true; // Перемещение вниз if(item->row_ < row) ++modelRow; } // Нельзя перемещать элемент в один из его дочерних элементов Derived* temp = static_cast(this); while(temp) { if(item == temp) return false; temp = temp->parent_; } if(model_ && !model_->beginMove(oldParent, item->row_, newParent, modelRow)) return false; if(oldParent == newParent) { if(row > item->row_) { for(int i = item->row_ + 1; i < row; ++i) children_[i]->row_--; children_.move(item->row_, row - 1); item->row_ = row - 1; } else if(row < item->row_) { for(int i = row; i < item->row_; ++i) children_[i]->row_++; children_.move(item->row_, row); item->row_ = row; } } else { oldParent->children_.takeAt(item->row_); for(int i = item->row_; i < oldParent->children_.count(); ++i) oldParent->children_[i]->row_--; item->row_ = row; item->parent_ = newParent; for(int i = item->row_; i < newParent->children_.count(); ++i) newParent->children_[i]->row_++; children_.insert(row, item); } if(model_) model_->endMove(); if(oldParent != newParent) { oldParent->childRemoved(item); newParent->childInserted(item); } item->reattached(); return true; } template Derived* GenericTreeItem::takeChild(int row) { if(model_) model_->beginRemove(static_cast(this), row); Derived* item = children_.takeAt(row); for(int i = item->row_; i < children_.count(); ++i) children_[i]->row_--; item->parent_ = nullptr; item->row_ = 0; item->model_ = nullptr; item->detach(); if(model_) model_->endRemove(); childRemoved(item); return item; } template void GenericTreeItem::removeChild(int row) { delete takeChild(row); } template void GenericTreeItem::removeChildren() { int count = children_.count(); // Удаляем дочерние элементы от последнего к первому, чтобы избежать лишних // копирований элементов внутри children_. while(count--) removeChild(count); } template Derived* GenericTreeItem::takeFromParent() { if(parent_) return parent_->takeChild(row_); return static_cast(this); } template int GenericTreeItem::row() const { return row_; } template bool GenericTreeItem::canFetchMore() const { return canFetchMore_; } template void GenericTreeItem::setCanFetchMore(bool canFetchMore) { canFetchMore_ = canFetchMore; } template void GenericTreeItem::fetchMore() { canFetchMore_ = false; } template GenericTreeModel* GenericTreeItem::model() const { return model_; } template void GenericTreeItem::updateData() { if(model_) model_->updateData(static_cast(this)); } template void GenericTreeItem::sortChildren(LessThanProc lessThan) { qSort(children_.begin(), children_.end(), lessThan); if(model_) { QModelIndexList fromIndexes; QModelIndexList toIndexes; for(int row = 0; row < children_.count(); ++row) { Derived* item = children_[row]; int oldRow = item->row_; item->row_ = row; for(int i = 0; i < model()->columnCount(); ++i) { fromIndexes.append(model_->createNewIndex(oldRow, i)); toIndexes.append(model_->createNewIndex(row, i)); } } model_->changePersistentIndexes(fromIndexes, toIndexes); } } //---------------------------------- GenericTreeModel ----------------------------------// template GenericTreeModel::GenericTreeModel(T* root, QObject* parent) : QAbstractItemModel(parent), rootItem_(root) { Q_ASSERT(root); rootItem_->model_ = this; if(rootItem_->hasChildren()) { beginInsert(rootItem_, 0, rootItem_->childCount()); foreach(T* item, rootItem_->children_) item->model_ = this; endInsert(); } } template GenericTreeModel::~GenericTreeModel() { delete rootItem_; } template void GenericTreeModel::clear() { beginResetModel(); rootItem_->removeChildren(); endResetModel(); } template T* GenericTreeModel::indexToItem(const QModelIndex& index) const { if(!index.isValid()) return rootItem_; return static_cast(index.internalPointer()); } template QModelIndex GenericTreeModel::itemToIndex(T* item, int column) const { if(!item || item->model() != this || !item->parent()) return QModelIndex(); return createIndex(item->row(), column, item); } template T* GenericTreeModel::root() const { return rootItem_; } template QModelIndex GenericTreeModel::index(int row, int column, const QModelIndex& parent) const { Q_UNUSED(column); T* parentItem = indexToItem(parent); if(!parentItem || (row < 0) || (parentItem->childCount() <= row)) return QModelIndex(); return itemToIndex(parentItem->childAt(row), column); } template QModelIndex GenericTreeModel::parent(const QModelIndex& index) const { return itemToIndex(indexToItem(index)->parent()); } template int GenericTreeModel::rowCount(const QModelIndex& parent) const { T* parentItem = indexToItem(parent); return parentItem->childCount(); } template bool GenericTreeModel::hasChildren(const QModelIndex& parent) const { T* item = indexToItem(parent); if(item->canFetchMore()) return true; else return item->hasChildren(); } template bool GenericTreeModel::canFetchMore(const QModelIndex& parent) const { T* item = indexToItem(parent); return item->canFetchMore(); } template void GenericTreeModel::fetchMore(const QModelIndex& parent) { T* item = indexToItem(parent); if(item->canFetchMore()) item->fetchMore(); } template void GenericTreeModel::reset() { clear(); } template void GenericTreeModel::updateData(T* item) { QModelIndex from = itemToIndex(item); QModelIndex parent = from.parent(); int last = qMax(columnCount() - 1, 0); QModelIndex to = index(from.row(), last, parent); emit dataChanged(from, to); } template void GenericTreeModel::beginInsert(T* parentItem, int row, int count) { beginInsertRows(itemToIndex(parentItem), row, row + count - 1); } template void GenericTreeModel::endInsert() { endInsertRows(); } template bool GenericTreeModel::beginMove(T* srcParent, int srcRow, T* destParent, int destRow, int count) { return beginMoveRows(itemToIndex(srcParent), srcRow, srcRow + count - 1, itemToIndex(destParent), destRow); } template void GenericTreeModel::endMove() { endMoveRows(); } template void GenericTreeModel::beginRemove(T* parentItem, int row, int count) { beginRemoveRows(itemToIndex(parentItem), row, row + count - 1); } template void GenericTreeModel::endRemove() { endRemoveRows(); } template inline QModelIndex GenericTreeModel::createNewIndex(int row, int column) { return createIndex(row, column); } template inline void GenericTreeModel::changePersistentIndexes( const QModelIndexList& from, const QModelIndexList& to) { changePersistentIndexList(from, to); } #endif // MODELS_GENERICTREEMODEL_H ================================================ FILE: src/manager/models/linksmodel.cpp ================================================ #include "linksmodel.h" #include #include #include "core/application.h" LinkItem::LinkItem(Storage::Link link) : link_(link) { if(!link_.isNull()) { Storage* storage = qApp->storage(); QString prefix = QString::fromStdString(storage->prefix(link_.prefix()).path()); QFileInfo info(QDir(prefix), QString::fromStdString(link_.target())); arch_ = ModuleInfo::instance()->getArch(info.absoluteFilePath().toStdString()); } } QString LinkItem::name() const { QString path = QString::fromStdString(link_.path()); int pos = path.lastIndexOf('/'); if(pos == -1) return QString(); return path.mid(pos + 1, path.count() - pos - 4); } void LinkItem::setName(const QString& name) { QString path = QString::fromStdString(link_.path()); int pos = path.lastIndexOf('/'); if(pos == -1) return; path.truncate(pos + 1); path += name + ".so"; if(link_.setPath(path.toStdString())) updateData(); } QString LinkItem::location() const { QString path = QString::fromStdString(link_.path()); int pos = path.lastIndexOf('/'); if(pos == -1) return QString(); return path.left(pos); } void LinkItem::setLocation(const QString& path) { QString location = path + '/' + name() + ".so"; if(link_.setPath(location.toStdString())) updateData(); } ModuleInfo::Arch LinkItem::arch() const { return arch_; } QString LinkItem::prefix() const { return QString::fromStdString(link_.prefix()); } void LinkItem::setPrefix(const QString& prefix) { link_.setPrefix(prefix.toStdString()); updateData(); } QString LinkItem::loader() const { return QString::fromStdString(link_.loader()); } void LinkItem::setLoader(const QString& loader) { link_.setLoader(loader.toStdString()); updateData(); } QString LinkItem::target() const { return QString::fromStdString(link_.target()); } void LinkItem::setTarget(const QString& source) { link_.setTarget(source.toStdString()); updateData(); } QString LinkItem::path() const { return QString::fromStdString(link_.path()); } void LinkItem::setPath(const QString& path) { if(link_.setPath(path.toStdString())) updateData(); } LogLevel LinkItem::logLevel() const { return link_.logLevel(); } void LinkItem::setLogLevel(LogLevel level) { link_.setLogLevel(level); updateData(); } LinksModel::LinksModel(QObject* parent) : GenericTreeModel(new LinkItem(), parent) { update(); } int LinksModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 5; } QVariant LinksModel::data(const QModelIndex& index, int role) const { if(index.isValid()) { LinkItem* item = indexToItem(index); if(role == Qt::DisplayRole) { int column = index.column(); if(column == 0) { return item->name(); } else if(column == 1) { return logLevelString(item->logLevel()); } else if(column == 2) { return item->loader(); } else if(column == 3) { return item->prefix(); } else if(column == 4) { return item->target(); } } else if(role == Qt::ToolTipRole) { int column = index.column(); if(column == 0) { return item->path(); } if(column == 1) { } if(column == 2) { auto loader = qApp->storage()->loader(item->loader().toStdString()); return QString::fromStdString(loader.path()); } if(column == 3) { auto prefix = qApp->storage()->prefix(item->prefix().toStdString()); return QString::fromStdString(prefix.path()); } if(column == 4) { return item->target(); } } else if(role == Qt::DecorationRole) { int column = index.column(); if(column == 0) { if(item->arch() == ModuleInfo::kArch32) { return QIcon(":/32bit.png"); } else if(item->arch() == ModuleInfo::kArch64) { return QIcon(":/64bit.png"); } else { return QIcon(":/unknown.png"); } } else if(column == 1) { switch(item->logLevel()) { case LogLevel::kDefault: return QIcon(":/star.png"); case LogLevel::kQuiet: return QIcon(":/mute.png"); case LogLevel::kError: return QIcon(":/warning.png"); case LogLevel::kTrace: return QIcon(":/trace.png"); case LogLevel::kDebug: return QIcon(":/bug.png"); case LogLevel::kFlood: return QIcon(":/scull.png"); default: return QIcon(); } } } } return QVariant(); } QVariant LinksModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(orientation); if(role == Qt::DisplayRole) { if(section == 0) { return "Name"; } else if(section == 1) { return "Log level"; } else if(section == 2) { return "Loader"; } else if(section == 3) { return "Prefix"; } else if(section == 4) { return "VST plugin path (relative to prefix)"; } } return QVariant(); } LinkItem* LinksModel::createLink(const QString& name, const QString& location, const QString& target, const QString& prefix, const QString& loader) { Storage* s = qApp->storage(); QFileInfo info(QDir(location), name + ".so"); std::string path = info.absoluteFilePath().toStdString(); Storage::Link link = s->createLink(path, target.toStdString(), prefix.toStdString(), loader.toStdString()); if(!link) return nullptr; LinkItem* item = new LinkItem(link); root()->insertChild(item); return item; } bool LinksModel::removeLink(LinkItem* item) { if(!item || item->model() != this) return false; if(qApp->storage()->removeLink(item->link_)) { delete item->takeFromParent(); return true; } return false; } void LinksModel::update() { clear(); Storage* s = qApp->storage(); auto link = s->link(); while(!link.isNull()) { LinkItem* item = new LinkItem(link); root()->insertChild(item); link = link.next(); } } QString LinksModel::logLevelString(LogLevel level) const { switch(level) { default: case LogLevel::kDefault: return "default"; case LogLevel::kQuiet: return "quiet"; case LogLevel::kError: return "error"; case LogLevel::kTrace: return "trace"; case LogLevel::kDebug: return "debug"; case LogLevel::kFlood: return "flood"; } } ================================================ FILE: src/manager/models/linksmodel.h ================================================ #ifndef MODELS_LINKSMODEL_H #define MODELS_LINKSMODEL_H #include "common/logger.h" #include "common/moduleinfo.h" #include "common/storage.h" #include "models/generictreemodel.h" using Airwave::Storage; using Airwave::LogLevel; class LinkItem : public GenericTreeItem { public: LinkItem(Storage::Link link = Storage::Link()); QString name() const; void setName(const QString& name); QString location() const; void setLocation(const QString& path); ModuleInfo::Arch arch() const; QString prefix() const; void setPrefix(const QString& prefix); QString loader() const; void setLoader(const QString& loader); QString target() const; void setTarget(const QString& source); QString path() const; void setPath(const QString& path); LogLevel logLevel() const; void setLogLevel(LogLevel level); private: friend class LinksModel; Storage::Link link_; ModuleInfo::Arch arch_; LogLevel level_; }; class LinksModel : public GenericTreeModel { Q_OBJECT public: LinksModel(QObject* parent = nullptr); int columnCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; LinkItem* createLink(const QString& name, const QString& location, const QString& target, const QString& prefix, const QString& loader); bool removeLink(LinkItem* item); void update(); private: QString logLevelString(LogLevel level) const; }; #endif // MODELS_LINKSMODEL_H ================================================ FILE: src/manager/models/loadersmodel.cpp ================================================ #include "loadersmodel.h" #include #include "core/application.h" #include "models/linksmodel.h" LoaderItem::LoaderItem(Storage::Loader loader) : loader_(loader) { } QString LoaderItem::name() const { return QString::fromStdString(loader_.name()); } void LoaderItem::setName(const QString& name) { if(loader_.setName(name.toStdString())) { updateData(); qApp->links()->update(); } } QString LoaderItem::path() const { return QString::fromStdString(loader_.path()); } void LoaderItem::setPath(const QString& path) { loader_.setPath(path.toStdString()); updateData(); } LoadersModel::LoadersModel(QObject* parent) : GenericTreeModel(new LoaderItem(), parent) { Storage* s = qApp->storage(); auto loader = s->loader(); while(!loader.isNull()) { LoaderItem* item = new LoaderItem(loader); root()->insertChild(item); loader = loader.next(); } } int LoadersModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 2; } QVariant LoadersModel::data(const QModelIndex& index, int role) const { if(index.isValid()) { LoaderItem* item = indexToItem(index); if(role == Qt::DisplayRole) { if(index.column() == 0) { return item->name(); } else if(index.column() == 1) { return item->path(); } } } return QVariant(); } QVariant LoadersModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(orientation); if(role == Qt::DisplayRole) { if(section == 0) { return "Name"; } else if(section == 1) { return "Path"; } } return QVariant(); } LoaderItem* LoadersModel::createLoader(const QString& name, const QString& path) { Storage* s = qApp->storage(); Storage::Loader loader = s->createLoader(name.toStdString(), path.toStdString()); if(!loader) return nullptr; LoaderItem* item = new LoaderItem(loader); root()->insertChild(item); return item; } bool LoadersModel::removeLoader(LoaderItem* item) { if(!item || item == root()) return false; if(!qApp->storage()->removeLoader(item->loader_)) return false; delete item->takeFromParent(); return true; } ================================================ FILE: src/manager/models/loadersmodel.h ================================================ #ifndef MODELS_LOADERSMODEL_H #define MODELS_LOADERSMODEL_H #include "generictreemodel.h" #include "common/storage.h" using Airwave::Storage; class LoaderItem : public GenericTreeItem { public: LoaderItem(Storage::Loader loader = Storage::Loader()); QString name() const; void setName(const QString& name); QString path() const; void setPath(const QString& path); private: friend class LoadersModel; Storage::Loader loader_; }; class LoadersModel : public GenericTreeModel { Q_OBJECT public: LoadersModel(QObject* parent = nullptr); int columnCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; LoaderItem* createLoader(const QString& name, const QString& path); bool removeLoader(LoaderItem* item); }; #endif // MODELS_LOADERSMODEL_H ================================================ FILE: src/manager/models/prefixesmodel.cpp ================================================ #include "prefixesmodel.h" #include #include "core/application.h" #include "models/linksmodel.h" PrefixItem::PrefixItem(Storage::Prefix prefix) : prefix_(prefix) { } QString PrefixItem::name() const { return QString::fromStdString(prefix_.name()); } void PrefixItem::setName(const QString& name) { if(prefix_.setName(name.toStdString())) { updateData(); qApp->links()->update(); } } QString PrefixItem::path() const { return QString::fromStdString(prefix_.path()); } void PrefixItem::setPath(const QString& path) { prefix_.setPath(path.toStdString()); updateData(); } PrefixesModel::PrefixesModel(QObject* parent) : GenericTreeModel(new PrefixItem(), parent) { Storage* s = qApp->storage(); auto prefix = s->prefix(); while(!prefix.isNull()) { PrefixItem* item = new PrefixItem(prefix); root()->insertChild(item); prefix = prefix.next(); } } int PrefixesModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 2; } QVariant PrefixesModel::data(const QModelIndex& index, int role) const { if(index.isValid()) { PrefixItem* item = indexToItem(index); if(role == Qt::DisplayRole) { if(index.column() == 0) { return item->name(); } else if(index.column() == 1) { return item->path(); } } } return QVariant(); } QVariant PrefixesModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(orientation); if(role == Qt::DisplayRole) { if(section == 0) { return "Name"; } else if(section == 1) { return "Path"; } } return QVariant(); } PrefixItem* PrefixesModel::createPrefix(const QString& name, const QString& path) { Storage* s = qApp->storage(); Storage::Prefix prefix = s->createPrefix(name.toStdString(), path.toStdString()); if(!prefix) return nullptr; PrefixItem* item = new PrefixItem(prefix); root()->insertChild(item); return item; } bool PrefixesModel::removePrefix(PrefixItem* item) { if(!item || item == root()) return false; if(!qApp->storage()->removePrefix(item->prefix_)) return false; delete item->takeFromParent(); return true; } ================================================ FILE: src/manager/models/prefixesmodel.h ================================================ #ifndef MODELS_PREFIXMODEL_H #define MODELS_PREFIXMODEL_H #include "generictreemodel.h" #include "common/storage.h" using Airwave::Storage; class PrefixItem : public GenericTreeItem { public: PrefixItem(Storage::Prefix prefix = Storage::Prefix()); QString name() const; void setName(const QString& name); QString path() const; void setPath(const QString& path); private: friend class PrefixesModel; Storage::Prefix prefix_; }; class PrefixesModel : public GenericTreeModel { Q_OBJECT public: PrefixesModel(QObject* parent = nullptr); int columnCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; PrefixItem* createPrefix(const QString& name, const QString& path); bool removePrefix(PrefixItem* item); }; #endif // MODELS_PREFIXMODEL_H ================================================ FILE: src/manager/resources/resources.qrc ================================================ airwave-manager.png create_link.png edit.png update.png remove.png open_in_browser.png outline.png download.png draw_line.png erase.png settings.png 32bit.png 64bit.png unknown.png go_up.png create_folder.png show.png open.png save.png mute.png bug.png scull.png star.png trace.png warning.png about.png ================================================ FILE: src/manager/widgets/directoryview.cpp ================================================ #include "directoryview.h" #include #include "nofocusdelegate.h" DirectoryView::DirectoryView(QWidget* parent) : GenericTreeView(parent) { setAutoClearSelection(true); setRootIsDecorated(false); NoFocusDelegate* delegate = new NoFocusDelegate(this); // delegate->setExtraHeight(4); setItemDelegate(delegate); setContextMenuPolicy(Qt::CustomContextMenu); } void DirectoryView::setModel(DirectoryModel* model) { GenericTreeView::setModel(model); if(model) { QHeaderView* header = this->header(); header->setStretchLastSection(false); header->setSectionResizeMode(0, QHeaderView::Stretch); header->setSectionResizeMode(1, QHeaderView::Interactive); header->setSectionResizeMode(2, QHeaderView::Interactive); } } void DirectoryView::currentChangeEvent(DirectoryItem* current, DirectoryItem* previous) { emit currentItemChanged(current, previous); } void DirectoryView::selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected) { emit itemSelectionChanged(selected, deselected); } void DirectoryView::mouseDoubleClickEvent(QMouseEvent* event) { QModelIndex index = indexAt(event->pos()); DirectoryItem* item = model()->indexToItem(index); if(item) emit itemDoubleClicked(item); } ================================================ FILE: src/manager/widgets/directoryview.h ================================================ #ifndef WIDGETS_DIRECTORYVIEW_H #define WIDGETS_DIRECTORYVIEW_H #include "models/directorymodel.h" #include "widgets/generictreeview.h" class DirectoryView : public GenericTreeView { Q_OBJECT public: DirectoryView(QWidget* parent = nullptr); public slots: void setModel(DirectoryModel* model); signals: void currentItemChanged(DirectoryItem* current, DirectoryItem* previous); void itemSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); void itemDoubleClicked(DirectoryItem* current); protected: void currentChangeEvent(DirectoryItem* current, DirectoryItem* previous); void selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected); void mouseDoubleClickEvent(QMouseEvent* event); }; #endif // WIDGETS_DIRECTORYVIEW_H ================================================ FILE: src/manager/widgets/generictreeview.h ================================================ #ifndef WIDGETS_GENERICTREEVIEW_H #define WIDGETS_GENERICTREEVIEW_H #include #include template class GenericTreeView : public QTreeView { public: typedef typename Model::ItemType ItemType; typedef QList ItemList; GenericTreeView(QWidget* parent = nullptr); Model* model() const; void setModel(Model* model); ItemType* rootItem() const; void setAutoClearSelection(bool enabled); bool isAutoClearSelection() const; void setAutoExpanding(bool enabled); bool isAutoExpanding() const; bool hasSelection() const; void clearSelection(); bool hasCurrentItem() const; ItemType* currentItem() const; void clearCurrentItem(); ItemList selectedItems() const; bool isSelected(ItemType* item) const; void toggleSelection(ItemType* item); void setSelected(ItemType* item, bool selected); ItemType* itemAt(const QPoint& point) const; protected: virtual void currentChangeEvent(ItemType* current, ItemType* previous); virtual void selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected); private: bool isAutoClearSelection_; bool isAutoExpanding_; void mousePressEvent(QMouseEvent* event); void rowsInserted(const QModelIndex& parent, int start, int end); void currentChanged(const QModelIndex& current, const QModelIndex& previous); void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected); }; template GenericTreeView::GenericTreeView(QWidget* parent) : QTreeView(parent), isAutoClearSelection_(false), isAutoExpanding_(false) { setSelectionMode(SingleSelection); setSelectionBehavior(SelectRows); setDragEnabled(true); setDragDropMode(QAbstractItemView::InternalMove); } template Model* GenericTreeView::model() const { return static_cast(QTreeView::model()); } template void GenericTreeView::setModel(Model* model) { QTreeView::setModel(model); currentChangeEvent(nullptr, nullptr); } template typename GenericTreeView::ItemType* GenericTreeView::rootItem() const { if(model()) return model()->root(); return nullptr; } template void GenericTreeView::setAutoClearSelection(bool enabled) { isAutoClearSelection_ = enabled; } template bool GenericTreeView::isAutoClearSelection() const { return isAutoClearSelection_; } template void GenericTreeView::setAutoExpanding(bool enabled) { isAutoExpanding_ = enabled; } template bool GenericTreeView::isAutoExpanding() const { return isAutoExpanding_; } template bool GenericTreeView::hasSelection() const { if(selectionModel()) return selectionModel()->hasSelection(); return false; } template void GenericTreeView::clearSelection() { if(selectionModel()) { selectionModel()->setCurrentIndex(QModelIndex(), QItemSelectionModel::NoUpdate); selectionModel()->clear(); } } template bool GenericTreeView::hasCurrentItem() const { return currentIndex().isValid(); } template typename GenericTreeView::ItemType* GenericTreeView::currentItem() const { if(!model()) return nullptr; ItemType* item = model()->indexToItem(currentIndex()); if(item == rootItem()) return nullptr; return item; } template void GenericTreeView::clearCurrentItem() { if(selectionModel()) selectionModel()->clearCurrentIndex(); } template typename GenericTreeView::ItemList GenericTreeView::selectedItems() const { if(!selectionModel()) return ItemList(); ItemList result; foreach(const QModelIndex& index, selectionModel()->selectedRows()) result += model()->indexToItem(index); return result; } template bool GenericTreeView::isSelected(ItemType* item) const { if(!selectionModel() || !item) return false; QModelIndex index = model()->itemToIndex(item->parent()); int row = item->row(); return selectionModel()->isRowSelected(row, index); } template void GenericTreeView::toggleSelection(ItemType* item) { if(!selectionModel() || !item) return; QModelIndex index = model()->itemToIndex(item); if(index.isValid()) { QItemSelectionModel::SelectionFlags flags; flags = QItemSelectionModel::Toggle | QItemSelectionModel::Rows; selectionModel()->select(index, flags); } } template void GenericTreeView::setSelected(ItemType* item, bool selected) { if(!selectionModel() || !item) return; QModelIndex index = model()->itemToIndex(item); if(index.isValid()) { QItemSelectionModel::SelectionFlags flags; flags = QItemSelectionModel::Rows; if(selected) { flags |= QItemSelectionModel::Select; } else { flags |= QItemSelectionModel::Deselect; } selectionModel()->select(index, flags); } } template typename GenericTreeView::ItemType* GenericTreeView::itemAt( const QPoint& point) const { if(!model()) return nullptr; ItemType* item = model()->indexToItem(indexAt(point)); if(item == rootItem()) return nullptr; return item; } template void GenericTreeView::mousePressEvent(QMouseEvent* event) { if(isAutoClearSelection_) { QModelIndex index = indexAt(event->pos()); if(!index.isValid()) clearSelection(); } QTreeView::mousePressEvent(event); } template void GenericTreeView::rowsInserted(const QModelIndex& parent, int start, int end) { QTreeView::rowsInserted(parent, start, end); // При добавлении первого элемента, он делается текущим в QAbstractItemView. Чтобы // синхронизовать текущий элемент с выделением (которого после создания первого // элемента нет), мы делаем текущий элемент невалидным. if(rootItem()->childCount() == 1) setCurrentIndex(QModelIndex()); if(isAutoExpanding_) { for(int i = start; i <= end; ++i) { QModelIndex index = model()->index(i, 0, parent); setExpanded(index, true); } } } template void GenericTreeView::currentChangeEvent(ItemType* current, ItemType* previous) { Q_UNUSED(current); Q_UNUSED(previous); } template void GenericTreeView::selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected) { Q_UNUSED(selected); Q_UNUSED(deselected); } template void GenericTreeView::currentChanged(const QModelIndex& current, const QModelIndex& previous) { QTreeView::currentChanged(current, previous); ItemType* currentItem = model()->indexToItem(current); if(currentItem == rootItem()) currentItem = nullptr; ItemType* previousItem = model()->indexToItem(previous); if(previousItem == rootItem()) previousItem = nullptr; currentChangeEvent(currentItem, previousItem); } template void GenericTreeView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { QTreeView::selectionChanged(selected, deselected); selectionChangeEvent(selected, deselected); } #endif // WIDGETS_GENERICTREEVIEW_H ================================================ FILE: src/manager/widgets/lineedit.cpp ================================================ #include #include #include #include #include #include #include #include #include "lineedit.h" LineEdit::LineEdit(QWidget* parent) : QLineEdit(parent), hasButton_(false), button_(new QToolButton(this)), buttonStyle_(kNormal), isAutoClearMode_(false), prefixColor_(qApp->palette().text().color()), suffixColor_(qApp->palette().text().color()) { button_->hide(); button_->setCursor(Qt::ArrowCursor); button_->setToolButtonStyle(Qt::ToolButtonIconOnly); button_->setFocusPolicy(Qt::NoFocus); connect(button_, SIGNAL(clicked()), SLOT(onButtonClicked())); connect(this, SIGNAL(textChanged(QString)), SLOT(onTextChanged())); timer_.setInterval(200); timer_.setSingleShot(true); connect(&timer_, SIGNAL(timeout()), SLOT(onTimeout())); } bool LineEdit::hasButton() const { return hasButton_; } void LineEdit::setButtonEnabled(bool enabled) { if(enabled != hasButton_) { hasButton_ = enabled; button_->setVisible(enabled); updateLayout(); update(); } } LineEdit::ButtonStyle LineEdit::buttonStyle() const { return buttonStyle_; } void LineEdit::setButtonStyle(ButtonStyle style) { QColor col = palette().toolTipBase().color(); QString sheet = "QToolButton { background-color: rgba(255, 255, 255, %1);} " "QToolButton QWidget { background-color: rgb(%2, %3, %4);}"; switch(style) { case kNormal: button_->setAutoRaise(false); button_->setStyleSheet(""); break; case kAutoRaise: button_->setAutoRaise(true); button_->setStyleSheet(""); break; case kLightAutoRaise: button_->setAutoRaise(true); sheet = sheet.arg(80).arg(col.red()).arg(col.green()).arg(col.blue()); button_->setStyleSheet(sheet); break; case kTransparent: button_->setAutoRaise(true); sheet = sheet.arg(0).arg(col.red()).arg(col.green()).arg(col.blue()); button_->setStyleSheet(sheet); break; } } bool LineEdit::isAutoClearMode() const { return isAutoClearMode_; } void LineEdit::setAutoClearMode(bool enabled) { isAutoClearMode_ = enabled; button_->setToolTip(tr("Clear")); QIcon icon = style()->standardIcon(QStyle::SP_DockWidgetCloseButton); button_->setIcon(icon); } QIcon LineEdit::buttonIcon() const { return button_->icon(); } QString LineEdit::buttonToolTip() const { return button_->toolTip(); } void LineEdit::setButtonToolTip(const QString& toolTip) { button_->setToolTip(toolTip); } void LineEdit::setButtonIcon(const QIcon& icon) { button_->setIcon(icon); } uint LineEdit::editTimeout() const { return timer_.interval(); } void LineEdit::setEditTimeout(uint msecs) { timer_.setInterval(msecs); } bool LineEdit::hasIcon() const { return !icon_.isNull(); } void LineEdit::setIcon(const QIcon& icon) { icon_ = icon.pixmap(16, 16); updateLayout(); update(); } void LineEdit::updateLayout() { int size = height(); int leftMargin = 0; int rightMargin = 0; if(hasButton()) { rightMargin = size; button_->setGeometry(width() - size + 1, 1, size - 2, size - 2); } if(hasIcon()) leftMargin = 16; if(!prefix_.isEmpty()) { QFontMetrics fm(font()); leftMargin += fm.width(prefix_); } if(!suffix_.isEmpty()) { QFontMetrics fm(font()); rightMargin += fm.width(suffix_); } setTextMargins(leftMargin, 0, rightMargin, 0); } void LineEdit::paintEvent(QPaintEvent* event) { QLineEdit::paintEvent(event); if(hasIcon()) { QPainter painter(this); painter.drawPixmap(3, 2, icon_); } QPainter painter(this); QFontMetrics fm(font()); QMargins margins = textMargins(); int half = (height() - fm.height()) / 2; if(!prefix_.isEmpty()) { int x = margins.left() - fm.width(prefix_) + 6; int y = margins.top() + fm.ascent() + half; painter.setPen(prefixColor_); painter.drawText(x, y, prefix_); } if(!suffix_.isEmpty()) { int x = width() - margins.right(); int y = margins.top() + fm.ascent() + half; painter.setPen(suffixColor_); painter.drawText(x, y, suffix_); } } void LineEdit::resizeEvent(QResizeEvent* event) { QLineEdit::resizeEvent(event); updateLayout(); } void LineEdit::keyPressEvent(QKeyEvent* event) { if(event->key() == Qt::Key_Escape && isAutoClearMode()) { clear(); } else { QLineEdit::keyPressEvent(event); } } void LineEdit::mouseMoveEvent(QMouseEvent* event) { QLineEdit::mouseMoveEvent(event); if(hasIcon()) { if(event->x() < 16 + 2) { setCursor(Qt::PointingHandCursor); } else { setCursor(Qt::IBeamCursor); } } } void LineEdit::onButtonClicked() { if(isAutoClearMode_) clear(); emit buttonClicked(); } void LineEdit::onTextChanged() { timer_.start(); } void LineEdit::onTimeout() { emit textEditTimeout(text()); } QString LineEdit::prefix() const { return prefix_; } void LineEdit::setPrefix(const QString& prefix) { prefix_ = prefix; updateLayout(); update(); } QColor LineEdit::prefixColor() const { return prefixColor_; } void LineEdit::setPrefixColor(const QColor& color) { prefixColor_ = color; update(); } QString LineEdit::suffix() const { return prefix_; } void LineEdit::setSuffix(const QString& suffix) { suffix_ = suffix; updateLayout(); update(); } QColor LineEdit::suffixColor() const { return suffixColor_; } void LineEdit::setSuffixColor(const QColor& color) { suffixColor_ = color; update(); } ================================================ FILE: src/manager/widgets/lineedit.h ================================================ #ifndef WIDGETS_LINEEDIT_H #define WIDGETS_LINEEDIT_H #include #include class QToolButton; class LineEdit: public QLineEdit { Q_OBJECT public: enum ButtonStyle { kNormal, kAutoRaise, kLightAutoRaise, kTransparent }; LineEdit(QWidget* parent = nullptr); bool hasButton() const; void setButtonEnabled(bool enabled); ButtonStyle buttonStyle() const; void setButtonStyle(ButtonStyle style); bool isAutoClearMode() const; void setAutoClearMode(bool enabled); QString buttonToolTip() const; void setButtonToolTip(const QString& toolTip); QIcon buttonIcon() const; void setButtonIcon(const QIcon& icon); uint editTimeout() const; void setEditTimeout(uint msecs); bool hasIcon() const; void setIcon(const QIcon& icon); QString prefix() const; void setPrefix(const QString& prefix); QColor prefixColor() const; void setPrefixColor(const QColor& color); QString suffix() const; void setSuffix(const QString& suffix); QColor suffixColor() const; void setSuffixColor(const QColor& color); signals: void buttonClicked(); void textEditTimeout(const QString& text); protected: virtual void paintEvent(QPaintEvent* event); virtual void resizeEvent(QResizeEvent* event); virtual void keyPressEvent(QKeyEvent* event); virtual void mouseMoveEvent(QMouseEvent* event); private: bool hasButton_; QToolButton* button_; ButtonStyle buttonStyle_; bool isAutoClearMode_; QTimer timer_; QPixmap icon_; QString prefix_; QString suffix_; QColor prefixColor_; QColor suffixColor_; void updateLayout(); private slots: void onButtonClicked(); void onTextChanged(); void onTimeout(); }; #endif // WIDGETS_LINEEDIT_H ================================================ FILE: src/manager/widgets/linksview.cpp ================================================ #include "linksview.h" #include #include "widgets/nofocusdelegate.h" LinksView::LinksView(QWidget* parent) : GenericTreeView(parent) { setAutoClearSelection(true); setRootIsDecorated(false); NoFocusDelegate* delegate = new NoFocusDelegate(this); // delegate->setExtraHeight(4); setItemDelegate(delegate); setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(onItemDoubleClicked(QModelIndex))); } void LinksView::setModel(LinksModel* model) { GenericTreeView::setModel(model); // if(model) { // QHeaderView* header = this->header(); // header->setStretchLastSection(false); // header->setSectionResizeMode(0, QHeaderView::ResizeToContents); // header->setSectionResizeMode(1, QHeaderView::ResizeToContents); // header->setSectionResizeMode(2, QHeaderView::ResizeToContents); // header->setSectionResizeMode(3, QHeaderView::Stretch); // } } void LinksView::currentChangeEvent(LinkItem* current, LinkItem* previous) { emit currentItemChanged(current, previous); } void LinksView::selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected) { emit itemSelectionChanged(selected, deselected); } void LinksView::onItemDoubleClicked(const QModelIndex& index) { emit itemDoubleClicked(model()->indexToItem(index)); } ================================================ FILE: src/manager/widgets/linksview.h ================================================ #ifndef WIDGETS_LINKSVIEW_H #define WIDGETS_LINKSVIEW_H #include "models/linksmodel.h" #include "widgets/generictreeview.h" class LinksView : public GenericTreeView { Q_OBJECT public: LinksView(QWidget* parent = nullptr); public slots: void setModel(LinksModel* model); signals: void currentItemChanged(LinkItem* current, LinkItem* previous); void itemSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); void itemDoubleClicked(LinkItem* item); protected: void currentChangeEvent(LinkItem* current, LinkItem* previous); void selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected); private slots: void onItemDoubleClicked(const QModelIndex& index); }; #endif // WIDGETS_LINKSVIEW_H ================================================ FILE: src/manager/widgets/loadersview.cpp ================================================ #include "loadersview.h" #include #include "nofocusdelegate.h" LoadersView::LoadersView(QWidget* parent) : GenericTreeView(parent) { setAutoClearSelection(true); setRootIsDecorated(false); NoFocusDelegate* delegate = new NoFocusDelegate(this); // delegate->setExtraHeight(4); setItemDelegate(delegate); setContextMenuPolicy(Qt::CustomContextMenu); } void LoadersView::setModel(LoadersModel* model) { GenericTreeView::setModel(model); // if(model) { // QHeaderView* header = this->header(); // header->setStretchLastSection(false); // header->setSectionResizeMode(0, QHeaderView::ResizeToContents); // header->setSectionResizeMode(1, QHeaderView::ResizeToContents); // header->setSectionResizeMode(2, QHeaderView::ResizeToContents); // header->setSectionResizeMode(3, QHeaderView::Stretch); // } } void LoadersView::currentChangeEvent(LoaderItem* current, LoaderItem* previous) { emit currentItemChanged(current, previous); } void LoadersView::selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected) { emit itemSelectionChanged(selected, deselected); } ================================================ FILE: src/manager/widgets/loadersview.h ================================================ #ifndef WIDGETS_LOADERSVIEW_H #define WIDGETS_LOADERSVIEW_H #include "generictreeview.h" #include "models/loadersmodel.h" class LoadersView : public GenericTreeView { Q_OBJECT public: LoadersView(QWidget* parent = nullptr); public slots: void setModel(LoadersModel* model); signals: void currentItemChanged(LoaderItem* current, LoaderItem* previous); void itemSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); protected: void currentChangeEvent(LoaderItem* current, LoaderItem* previous); void selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected); }; #endif // WIDGETS_LOADERSVIEW_H ================================================ FILE: src/manager/widgets/logview.cpp ================================================ #include #include #include #include "logview.h" #include "common/config.h" LogView::LogView(QWidget* parent) : QTextEdit(parent), isAutoScroll_(true), isWordWrap_(true) { setReadOnly(true); QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); setFont(font); setWordWrap(isWordWrap_); } bool LogView::isAutoScroll() const { return isAutoScroll_; } bool LogView::isWordWrap() const { return isWordWrap_; } void LogView::setAutoScroll(bool enabled) { isAutoScroll_ = enabled; } void LogView::setWordWrap(bool enabled) { isWordWrap_ = enabled; if(isWordWrap_) { setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); } else { setWordWrapMode(QTextOption::NoWrap); } } void LogView::addMessage(quint64 time, const QString& sender, const QString& text) { setTextColor(QColor(0x909090)); insertPlainText(QString::number(time >> 32)); insertPlainText("."); insertPlainText(QString::number(time & 0xFFFFFFFF).rightJustified(9, '0')); insertPlainText(" "); if(sender == HOST_BASENAME || sender.endsWith(".dll")) { setTextColor(QColor(0x804000)); } else { setTextColor(QColor(0x004080)); } insertPlainText(sender.rightJustified(20, ' ', true)); insertPlainText(" : "); setTextColor(0x222222); insertPlainText(text); insertPlainText("\n"); if(isAutoScroll_) { int maximum = verticalScrollBar()->maximum(); verticalScrollBar()->setValue(maximum); } } void LogView::addSeparator() { insertHtml("

"); if(isAutoScroll_) { int maximum = verticalScrollBar()->maximum(); verticalScrollBar()->setValue(maximum); } } ================================================ FILE: src/manager/widgets/logview.h ================================================ #ifndef WIDGETS_LOGVIEW_H #define WIDGETS_LOGVIEW_H #include class LogView : public QTextEdit { Q_OBJECT public: LogView(QWidget* parent = nullptr); bool isAutoScroll() const; bool isWordWrap() const; public slots: void setAutoScroll(bool enabled); void setWordWrap(bool enabled); void addMessage(quint64 time, const QString& sender, const QString& text); void addSeparator(); private: bool isAutoScroll_; bool isWordWrap_; }; #endif // WIDGETS_LOGVIEW_H ================================================ FILE: src/manager/widgets/nofocusdelegate.cpp ================================================ #include "nofocusdelegate.h" NoFocusDelegate::NoFocusDelegate(QWidget* parent) : QStyledItemDelegate(parent), extraHeight_(0) { } void NoFocusDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItemV4 opt = option; opt.state &= ~QStyle::State_HasFocus; QStyledItemDelegate::paint(painter, opt, index); } QSize NoFocusDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { QSize size = QStyledItemDelegate::sizeHint(option, index); size.setHeight(size.height() + extraHeight_); return size; } void NoFocusDelegate::setExtraHeight(int value) { extraHeight_ = qMax(0, value); } ================================================ FILE: src/manager/widgets/nofocusdelegate.h ================================================ #ifndef WIDGETS_NOFOCUSDELEGATE_H #define WIDGETS_NOFOCUSDELEGATE_H #include class NoFocusDelegate : public QStyledItemDelegate { Q_OBJECT public: explicit NoFocusDelegate(QWidget* parent = nullptr); void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; void setExtraHeight(int value); private: int extraHeight_; }; #endif // WIDGETS_NOFOCUSDELEGATE_H ================================================ FILE: src/manager/widgets/prefixesview.cpp ================================================ #include "prefixesview.h" #include #include "nofocusdelegate.h" PrefixesView::PrefixesView(QWidget* parent) : GenericTreeView(parent) { setAutoClearSelection(true); setRootIsDecorated(false); NoFocusDelegate* delegate = new NoFocusDelegate(this); // delegate->setExtraHeight(4); setItemDelegate(delegate); setContextMenuPolicy(Qt::CustomContextMenu); } void PrefixesView::setModel(PrefixesModel* model) { GenericTreeView::setModel(model); // if(model) { // QHeaderView* header = this->header(); // header->setStretchLastSection(false); // header->setSectionResizeMode(0, QHeaderView::ResizeToContents); // header->setSectionResizeMode(1, QHeaderView::ResizeToContents); // header->setSectionResizeMode(2, QHeaderView::ResizeToContents); // header->setSectionResizeMode(3, QHeaderView::Stretch); // } } void PrefixesView::currentChangeEvent(PrefixItem* current, PrefixItem* previous) { emit currentItemChanged(current, previous); } void PrefixesView::selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected) { emit itemSelectionChanged(selected, deselected); } ================================================ FILE: src/manager/widgets/prefixesview.h ================================================ #ifndef WIDGETS_PREFIXESVIEW_H #define WIDGETS_PREFIXESVIEW_H #include "generictreeview.h" #include "models/prefixesmodel.h" class PrefixesView : public GenericTreeView { Q_OBJECT public: PrefixesView(QWidget* parent = nullptr); public slots: void setModel(PrefixesModel* model); signals: void currentItemChanged(PrefixItem* current, PrefixItem* previous); void itemSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); protected: void currentChangeEvent(PrefixItem* current, PrefixItem* previous); void selectionChangeEvent(const QItemSelection& selected, const QItemSelection& deselected); }; #endif // WIDGETS_PREFIXESVIEW_H ================================================ FILE: src/manager/widgets/separatorlabel.cpp ================================================ #include "separatorlabel.h" #include #include #include SeparatorLabel::SeparatorLabel(const QString& text, QWidget* parent) : QWidget(parent) { label_ = new QLabel(text); QFont font; font.setBold(true); label_->setFont(font); QFrame* line = new QFrame; line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QHBoxLayout* layout = new QHBoxLayout; layout->setMargin(0); layout->addWidget(label_); layout->addWidget(line); setLayout(layout); } ================================================ FILE: src/manager/widgets/separatorlabel.h ================================================ #ifndef WIDGET_SEPARATORLABEL_H_ #define WIDGET_SEPARATORLABEL_H_ #include class QLabel; class SeparatorLabel : public QWidget { Q_OBJECT public: SeparatorLabel(const QString& text = QString(), QWidget* parent = nullptr); private: QLabel* label_; }; #endif //WIDGET_SEPARATORLABEL_H_ ================================================ FILE: src/plugin/CMakeLists.txt ================================================ set(TARGET_NAME ${PLUGIN_BASENAME}) project(${TARGET_NAME}) find_package(LibDl REQUIRED) find_package(LibMagic REQUIRED) find_package(Threads REQUIRED) find_package(X11 REQUIRED) include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ${LIBDL_INCLUDE_DIR} ${X11_INCLUDE_DIR} ${VSTSDK_INCLUDE_DIR} ) # Workaround for VST 2.4 SDK on Linux add_definitions(-D__cdecl=) if(DEBUG_BINARY_DIR) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${DEBUG_BINARY_DIR}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${DEBUG_BINARY_DIR}) endif() # Common sources set(SOURCES main.cpp plugin.cpp ../common/dataport.cpp ../common/event.cpp ../common/filesystem.cpp ../common/json.cpp ../common/logger.cpp ../common/moduleinfo.cpp ../common/storage.cpp ../common/vsteventkeeper.cpp ) set(HEADERS ../common/json.h ../common/protocol.h ../common/vst24.h ) # Configure library base name set(CMAKE_SHARED_LIBRARY_PREFIX "") # Set target add_library(${TARGET_NAME} SHARED ${SOURCES}) # Link with libraries target_link_libraries(${TARGET_NAME} ${LIBDL_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} ${X11_X11_LIB} ${LIBMAGIC_LIBRARY} ) install(TARGETS ${TARGET_NAME} LIBRARY DESTINATION bin) ================================================ FILE: src/plugin/main.cpp ================================================ #include #include #include #include "plugin.h" #include "common/config.h" #include "common/filesystem.h" #include "common/logger.h" #include "common/moduleinfo.h" #include "common/storage.h" using namespace Airwave; extern "C" { AEffect* VSTPluginMain(AudioMasterProc audioMasterProc); AEffect* mainStub(AudioMasterProc audioMasterProc) asm ("main"); } void signalHandler(int signum) { if(signum == SIGCHLD) { TRACE("Child process terminated"); } else { TRACE("Received signal %d", signum); } } AEffect* VSTPluginMain(AudioMasterProc audioMasterProc) { // FIXME Without this signal handler the Renoise tracker is unable to start the child // winelib application. signal(SIGCHLD, signalHandler); Storage storage; loggerInit(storage.logSocketPath(), PLUGIN_BASENAME); // Get path to own binary Dl_info info; if(dladdr(reinterpret_cast(VSTPluginMain), &info) == 0) { ERROR("Unable to get library filename"); return nullptr; } std::string selfPath = FileSystem::realPath(info.dli_fname); if(selfPath.empty()) { ERROR("Unable to get an absolute path of the plugin binary", selfPath.c_str()); return nullptr; } // Get path of the linked VST plugin binary Storage::Link link = storage.link(selfPath); if(!link) { ERROR("Link '%s' is corrupted", selfPath.c_str()); return nullptr; } LogLevel level = link.logLevel(); if(level == LogLevel::kDefault) level = storage.defaultLogLevel(); loggerSetSenderId(FileSystem::baseName(info.dli_fname)); loggerSetLogLevel(level); TRACE("Initializing plugin endpoint %s", VERSION_STRING); TRACE("Plugin binary: %s", selfPath.c_str()); std::string winePrefix = link.prefix(); Storage::Prefix prefix = storage.prefix(winePrefix); if(!prefix) { ERROR("Invalid WINE prefix '%s'", winePrefix.c_str()); return nullptr; } std::string prefixPath = FileSystem::realPath(prefix.path()); if(!FileSystem::isDirExists(prefixPath)) { ERROR("WINE prefix directory '%s' doesn't exists", prefixPath.c_str()); return nullptr; } TRACE("WINE prefix: %s", prefixPath.c_str()); std::string wineLoader = link.loader(); Storage::Loader loader = storage.loader(wineLoader); if(!loader) { ERROR("Invalid WINE loader '%s'", wineLoader.c_str()); return nullptr; } std::string loaderPath = FileSystem::realPath(loader.path()); if(!FileSystem::isFileExists(loaderPath)) { ERROR("WINE loader binary '%s' doesn't exists", loaderPath.c_str()); return nullptr; } TRACE("WINE loader: %s", loaderPath.c_str()); std::string vstPath = prefixPath + '/' + link.target(); if(!FileSystem::isFileExists(vstPath)) { ERROR("VST binary '%s' doesn't exists", vstPath.c_str()); return nullptr; } TRACE("VST binary: %s", vstPath.c_str()); // Find host binary path ModuleInfo::Arch arch = ModuleInfo::instance()->getArch(vstPath); std::string hostName; if(arch == ModuleInfo::kArch64) { hostName = HOST_BASENAME "-64.exe"; } else if(arch == ModuleInfo::kArch32) { hostName = HOST_BASENAME "-32.exe"; } else { ERROR("Unable to determine VST plugin architecture"); return nullptr; } std::string hostPath = FileSystem::realPath(storage.binariesPath() + '/' + hostName); if(!FileSystem::isFileExists(hostPath)) { ERROR("Host binary '%s' doesn't exists", hostPath.c_str()); return nullptr; } TRACE("Host binary: %s", hostPath.c_str()); // We process only two cases, because messages with log levels lower than 'trace' // wouldn't be logged anyway. if(level == LogLevel::kTrace) { TRACE("Log level: trace"); } else if(level == LogLevel::kDebug) { TRACE("Log level: debug"); } // Initialize plugin endpoint Plugin* plugin; plugin = new Plugin(vstPath, hostPath, prefixPath, loaderPath, storage.logSocketPath(), audioMasterProc); if(!plugin->effect()) { ERROR("Unable to initialize plugin endpoint"); return nullptr; } TRACE("Plugin endpoint is initialized"); return plugin->effect(); } // Deprecated main() stub which is still used by some hosts AEffect* mainStub(AudioMasterProc audioMasterProc) { return VSTPluginMain(audioMasterProc); } ================================================ FILE: src/plugin/plugin.cpp ================================================ #include "plugin.h" #include #include #include #include "common/logger.h" #include "common/protocol.h" #define XEMBED_EMBEDDED_NOTIFY 0 #define XEMBED_FOCUS_OUT 5 #define kVstExtMaxParamStrLen 24 namespace Airwave { Plugin::Plugin(const std::string& vstPath, const std::string& hostPath, const std::string& prefixPath, const std::string& loaderPath, const std::string& logSocketPath, AudioMasterProc masterProc) : masterProc_(masterProc), effect_(nullptr), data_(nullptr), dataLength_(0), childPid_(-1), processCallbacks_(ATOMIC_FLAG_INIT), mainThreadId_(std::this_thread::get_id()), lastIndex_(-1), lastValue_(0) { // The constructor will return early when error occurs. In this case the effect() // fucntion will be returning nullptr, indicating the error. DEBUG("Main thread id: %p", mainThreadId_); // FIXME: frame size should be verified. if(!controlPort_.create(65536)) { ERROR("Unable to create control port"); return; } // FIXME: frame size should be verified. if(!callbackPort_.create(1024)) { ERROR("Unable to create callback port"); controlPort_.disconnect(); return; } // Start the host endpoint's process. childPid_ = fork(); if(childPid_ == -1) { ERROR("fork() call failed"); controlPort_.disconnect(); callbackPort_.disconnect(); return; } else if(childPid_ == 0) { setenv("WINEPREFIX", prefixPath.c_str(), 1); setenv("WINELOADER", loaderPath.c_str(), 1); std::string id = std::to_string(controlPort_.id()); std::string level = std::to_string(static_cast(loggerLogLevel())); execl("/bin/sh", "/bin/sh", hostPath.c_str(), vstPath.c_str(), id.c_str(), level.c_str(), logSocketPath.c_str(), nullptr); // We should never reach this point on success child execution. ERROR("execl() call failed"); return; } DEBUG("Child process started, pid=%d", childPid_); std::memset(&rect_, 0, sizeof(ERect)); processCallbacks_.test_and_set(); callbackThread_ = std::thread(&Plugin::callbackThread, this); condition_.wait(); // Send host info to the host endpoint. DataFrame* frame = controlPort_.frame(); frame->command = Command::HostInfo; frame->opcode = callbackPort_.id(); controlPort_.sendRequest(); TRACE("Waiting response from host endpoint..."); // Wait for the host endpoint initialization. if(!controlPort_.waitResponse()) { ERROR("Host endpoint is not responding"); kill(childPid_, SIGKILL); controlPort_.disconnect(); callbackPort_.disconnect(); childPid_ = -1; return; } PluginInfo* info = reinterpret_cast(frame->data); effect_ = new AEffect; std::memset(effect_, 0, sizeof(AEffect)); effect_->magic = kEffectMagic; effect_->object = this; effect_->dispatcher = dispatchProc; effect_->getParameter = getParameterProc; effect_->setParameter = setParameterProc; effect_->__processDeprecated = nullptr; effect_->processReplacing = processReplacingProc; effect_->processDoubleReplacing = processDoubleReplacingProc; effect_->flags = info->flags; effect_->numPrograms = info->programCount; effect_->numParams = info->paramCount; effect_->numInputs = info->inputCount; effect_->numOutputs = info->outputCount; effect_->initialDelay = info->initialDelay; effect_->uniqueID = info->uniqueId; effect_->version = info->version; DEBUG("VST plugin summary:"); DEBUG(" flags: 0x%08X", effect_->flags); DEBUG(" program count: %d", effect_->numPrograms); DEBUG(" param count: %d", effect_->numParams); DEBUG(" input count: %d", effect_->numInputs); DEBUG(" output count: %d", effect_->numOutputs); DEBUG(" initial delay: %d", effect_->initialDelay); DEBUG(" unique ID: 0x%08X", effect_->uniqueID); DEBUG(" version: %d", effect_->version); } Plugin::~Plugin() { TRACE("Waiting for callback thread termination..."); processCallbacks_.clear(); if(callbackThread_.joinable()) callbackThread_.join(); controlPort_.disconnect(); callbackPort_.disconnect(); audioPort_.disconnect(); TRACE("Waiting for child process termination..."); int status; waitpid(childPid_, &status, 0); if(effect_) delete effect_; TRACE("Plugin endpoint terminated"); } AEffect* Plugin::effect() { return effect_; } void Plugin::callbackThread() { TRACE("Callback thread started"); condition_.post(); while(processCallbacks_.test_and_set()) { if(callbackPort_.waitRequest(100)) { DataFrame* frame = callbackPort_.frame(); frame->value = handleAudioMaster(); callbackPort_.sendResponse(); } } TRACE("Callback thread terminated"); } intptr_t Plugin::setBlockSize(DataPort* port, intptr_t frames) { size_t frameSize = sizeof(DataFrame) + sizeof(double) * (frames * effect_->numInputs + frames * effect_->numOutputs); if(audioPort_.frameSize() < frameSize) { DEBUG("Setting block size to %d frames", frames); audioPort_.disconnect(); if(!audioPort_.create(frameSize)) { ERROR("Unable to create audio port"); return 0; } DataFrame* frame = controlPort_.frame(); frame->command = Command::Dispatch; frame->opcode = effSetBlockSize; frame->index = audioPort_.id(); port->sendRequest(); port->waitResponse(); return frame->value; } return 1; } intptr_t Plugin::handleAudioMaster() { DataFrame* frame = callbackPort_.frame(); if(frame->opcode != audioMasterGetTime && frame->opcode != audioMasterIdle) { FLOOD("(%p) handleAudioMaster(opcode: %s, index: %d, value: %d, opt: %g)", std::this_thread::get_id(), kAudioMasterEvents[frame->opcode], frame->index, frame->value, frame->opt); } switch(frame->opcode) { case audioMasterVersion: case __audioMasterWantMidiDeprecated: case audioMasterIdle: case audioMasterBeginEdit: case audioMasterEndEdit: case audioMasterUpdateDisplay: case audioMasterGetVendorVersion: case audioMasterSizeWindow: case audioMasterGetInputLatency: case audioMasterGetOutputLatency: case audioMasterGetCurrentProcessLevel: case audioMasterGetAutomationState: case audioMasterCurrentId: case audioMasterGetSampleRate: return masterProc_(effect_, frame->opcode, frame->index, frame->value, nullptr, frame->opt); case audioMasterAutomate: { lastThreadId_ = std::this_thread::get_id(); lastIndex_ = frame->index; lastValue_ = frame->value; intptr_t result = masterProc_(effect_, frame->opcode, frame->index, frame->value, nullptr, frame->opt); lastIndex_ = -1; return result; } case audioMasterIOChanged: { PluginInfo* info = reinterpret_cast(frame->data); effect_->flags = info->flags; effect_->numPrograms = info->programCount; effect_->numParams = info->paramCount; effect_->numInputs = info->inputCount; effect_->numOutputs = info->outputCount; effect_->initialDelay = info->initialDelay; effect_->uniqueID = info->uniqueId; effect_->version = info->version; return masterProc_(effect_, frame->opcode, frame->index, frame->value, nullptr, frame->opt); } case audioMasterGetVendorString: case audioMasterGetProductString: case audioMasterCanDo: return masterProc_(effect_, frame->opcode, frame->index, frame->value, frame->data, frame->opt); case audioMasterGetTime: { intptr_t value = masterProc_(effect_, frame->opcode, frame->index, frame->value, nullptr, frame->opt); VstTimeInfo* timeInfo = reinterpret_cast(value); if(timeInfo) { std::memcpy(frame->data, timeInfo, sizeof(VstTimeInfo)); return 1; } return 0; } case audioMasterProcessEvents: { VstEvent* events = reinterpret_cast(frame->data); events_.reload(frame->index, events); VstEvents* e = events_.events(); return masterProc_(effect_, frame->opcode, 0, 0, e, 0.0f); } } ERROR("Unhandled audio master event: %s %d", kAudioMasterEvents[frame->opcode], frame->opcode); return 0; } intptr_t Plugin::dispatch(DataPort* port, i32 opcode, i32 index, intptr_t value, void* ptr, float opt) { if(opcode != effEditIdle && opcode) FLOOD("(%p) dispatch: %s", std::this_thread::get_id(), kDispatchEvents[opcode]); DataFrame* frame = port->frame(); frame->command = Command::Dispatch; frame->opcode = opcode; frame->index = index; frame->value = value; frame->opt = opt; switch(opcode) { // We will not transmit effEditIdle event because the host endpoint processes window // events continuously in its main thread. case effEditIdle: return 1; case effOpen: { port->sendRequest(); port->waitResponse(); int result = frame->value; setBlockSize(port, 256); return result; } case effGetVstVersion: case effGetPlugCategory: case effSetSampleRate: case effGetVendorVersion: case effEditClose: case effMainsChanged: case effCanBeAutomated: case effGetProgram: case effStartProcess: case effSetProgram: case effBeginSetProgram: case effEndSetProgram: case effStopProcess: case effGetNumMidiInputChannels: case effGetNumMidiOutputChannels: case effSetPanLaw: case effGetTailSize: case effSetEditKnobMode: case __effConnectInputDeprecated: case __effConnectOutputDeprecated: case __effKeysRequiredDeprecated: case __effIdentifyDeprecated: port->sendRequest(); port->waitResponse(); return frame->value; case effClose: port->sendRequest(); port->waitResponse(); TRACE("Closing plugin"); delete this; loggerFree(); return 1; case effSetBlockSize: return setBlockSize(port, value); case effEditOpen: { Display* display = XOpenDisplay(nullptr); Window parent = reinterpret_cast(ptr); port->sendRequest(); port->waitResponse(); union Cast { u8* data; ERect* rect; }; Cast cast; cast.data = frame->data; rect_ = *cast.rect; int width = rect_.right - rect_.left; int height = rect_.bottom - rect_.top; DEBUG("Requested window size: %dx%d", width, height); XResizeWindow(display, parent, width, height); XSync(display, false); // FIXME without this delay, the VST window sometimes stays black. usleep(100000); Window child = frame->value; XReparentWindow(display, child, parent, 0, 0); sendXembedMessage(display, child, XEMBED_EMBEDDED_NOTIFY, 0, parent, 0); sendXembedMessage(display, child, XEMBED_FOCUS_OUT, 0, 0, 0); frame->command = Command::ShowWindow; port->sendRequest(); port->waitResponse(); // FIXME without this delay, the VST window sometimes stays black. usleep(100000); XMapWindow(display, child); XSync(display, false); XCloseDisplay(display); return frame->value; } case effEditGetRect: { port->sendRequest(); port->waitResponse(); union Cast { u8* data; ERect* rect; }; Cast cast; cast.data = frame->data; rect_ = *cast.rect; ERect** rectPtr = static_cast(ptr); *rectPtr = &rect_; return frame->value; } case effCanDo: { const char* source = static_cast(ptr); char* dest = reinterpret_cast(frame->data); size_t maxLength = port->frameSize() - sizeof(DataFrame); vst_strncpy(dest, source, maxLength); port->sendRequest(); port->waitResponse(); return frame->value; } case effGetProgramName: { port->sendRequest(); port->waitResponse(); const char* source = reinterpret_cast(frame->data); char* dest = static_cast(ptr); vst_strncpy(dest, source, kVstMaxProgNameLen); return frame->value; } case effSetProgramName: { const char* source = static_cast(ptr); char* dest = reinterpret_cast(frame->data); vst_strncpy(dest, source, kVstMaxProgNameLen); port->sendRequest(); port->waitResponse(); return frame->value; } case effGetVendorString: case effGetProductString: case effShellGetNextPlugin: { port->sendRequest(); port->waitResponse(); const char* source = reinterpret_cast(frame->data); char* dest = static_cast(ptr); vst_strncpy(dest, source, kVstMaxVendorStrLen); return frame->value; } case effGetParamName: case effGetParamLabel: case effGetParamDisplay: { port->sendRequest(); port->waitResponse(); const char* source = reinterpret_cast(frame->data); char* dest = static_cast(ptr); // vst_strncpy(dest, source, kVstMaxParamStrLen); // vst_strncpy(dest, source, kVstExtMaxParamStrLen); // Workaround for Variety of Sound plugins bug (non-printable characters) int i; for(i = 0; i < kVstExtMaxParamStrLen - 1; ++i) { if(!isprint(source[i])) break; dest[i] = source[i]; } dest[i] = '\0'; return frame->value; } case effGetEffectName: { port->sendRequest(); port->waitResponse(); const char* source = reinterpret_cast(frame->data); char* dest = static_cast(ptr); vst_strncpy(dest, source, kVstMaxEffectNameLen); return frame->value; } case effGetParameterProperties: port->sendRequest(); port->waitResponse(); std::memcpy(ptr, frame->data, sizeof(VstParameterProperties)); return frame->value; case effGetOutputProperties: case effGetInputProperties: port->sendRequest(); port->waitResponse(); std::memcpy(ptr, frame->data, sizeof(VstPinProperties)); return frame->value; case effGetProgramNameIndexed: { port->sendRequest(); port->waitResponse(); const char* source = reinterpret_cast(frame->data); char* dest = static_cast(ptr); vst_strncpy(dest, source, kVstMaxProgNameLen); return frame->value; } case effGetMidiKeyName: port->sendRequest(); port->waitResponse(); std::memcpy(ptr, frame->data, sizeof(MidiKeyName)); return frame->value; case effProcessEvents: { VstEvents* events = static_cast(ptr); VstEvent* event = reinterpret_cast(frame->data); frame->index = events->numEvents; for(int i = 0; i < events->numEvents; ++i) event[i] = *events->events[i]; port->sendRequest(); port->waitResponse(); return frame->value; } case effGetChunk: { DEBUG("effGetChunk"); // Tell the block size to the host endpoint. ptrdiff_t blockSize = port->frameSize() - sizeof(DataFrame); frame->value = blockSize; port->sendRequest(); port->waitResponse(); DEBUG("effGetChunk: chunk size %d bytes", frame->value); // If VST plugin supports the effGetChunk event, it has placed first data block // (or even the entire chunk) in the frame buffer. size_t chunkSize = frame->value; size_t count = frame->index; if(chunkSize == 0 || count == 0) { ERROR("effGetChunk is unsupported by the VST plugin"); return 0; } chunk_.resize(chunkSize); auto it = chunk_.begin(); it = std::copy(frame->data, frame->data + count, it); while(it != chunk_.end()) { frame->command = Command::GetDataBlock; frame->index = std::min(blockSize, chunk_.end() - it); DEBUG("effGetChunk: requesting next %d bytes", frame->index); port->sendRequest(); port->waitResponse(); size_t count = frame->index; if(count == 0) { ERROR("effGetChunk: premature end of data transmission"); return 0; } it = std::copy(frame->data, frame->data + count, it); } DEBUG("effGetChunk: received %d bytes", chunkSize); void** chunk = static_cast(ptr); *chunk = static_cast(chunk_.data()); return chunkSize; } case effSetChunk: { DEBUG("effSetChunk: %d bytes", frame->value); size_t chunkSize = frame->value; bool isPreset = frame->index; data_ = static_cast(ptr); dataLength_ = frame->value; size_t blockSize = port->frameSize() - sizeof(DataFrame); while(dataLength_) { frame->command = Command::SetDataBlock; size_t count = std::min(blockSize, dataLength_); frame->index = count; std::memcpy(frame->data, data_, count); DEBUG("effSetChunk: sending next %d bytes", count); port->sendRequest(); port->waitResponse(); data_ += count; dataLength_ -= count; } frame->command = Command::Dispatch; frame->opcode = effSetChunk; frame->index = isPreset; port->sendRequest(); port->waitResponse(); DEBUG("effSetChunk: sent %d bytes", chunkSize); return frame->value; } case effBeginLoadBank: case effBeginLoadProgram: std::memcpy(frame->data, ptr, sizeof(VstPatchChunkInfo)); port->sendRequest(); port->waitResponse(); return frame->value; case effSetSpeakerArrangement: { void* pluginInput = reinterpret_cast(value); void* pluginOutput = ptr; u8* data = frame->data; std::memcpy(data, pluginInput, sizeof(VstSpeakerArrangement)); data += sizeof(VstSpeakerArrangement); std::memcpy(data, pluginOutput, sizeof(VstSpeakerArrangement)); port->sendRequest(); port->waitResponse(); return frame->value; } } ERROR("Unhandled dispatch event: %s", kDispatchEvents[opcode]); return 0; } void Plugin::sendXembedMessage(Display* display, Window window, long message, long detail, long data1, long data2) { XEvent event; memset(&event, 0, sizeof(event)); event.xclient.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = XInternAtom(display, "_XEMBED", false); event.xclient.format = 32; event.xclient.data.l[0] = CurrentTime; event.xclient.data.l[1] = message; event.xclient.data.l[2] = detail; event.xclient.data.l[3] = data1; event.xclient.data.l[4] = data2; XSendEvent(display, window, false, NoEventMask, &event); XSync(display, false); } float Plugin::getParameter(i32 index) { DataFrame* frame = audioPort_.frame(); frame->command = Command::GetParameter; frame->index = index; audioPort_.sendRequest(); audioPort_.waitResponse(); return frame->opt; } void Plugin::setParameter(i32 index, float value) { DataFrame* frame = audioPort_.frame(); frame->command = Command::SetParameter; frame->index = index; frame->opt = value; audioPort_.sendRequest(); audioPort_.waitResponse(); } void Plugin::processReplacing(float** inputs, float** outputs, i32 count) { DataFrame* frame = audioPort_.frame(); frame->command = Command::ProcessSingle; frame->value = count; float* data = reinterpret_cast(frame->data); for(int i = 0; i < effect_->numInputs; ++i) { std::memcpy(data, inputs[i], sizeof(float) * count); data += count; } audioPort_.sendRequest(); audioPort_.waitResponse(); data = reinterpret_cast(frame->data); for(int i = 0; i < effect_->numOutputs; ++i) { std::memcpy(outputs[i], data, sizeof(float) * count); data += count; } } void Plugin::processDoubleReplacing(double** inputs, double** outputs, i32 count) { DataFrame* frame = audioPort_.frame(); frame->command = Command::ProcessDouble; frame->value = count; double* data = reinterpret_cast(frame->data); for(int i = 0; i < effect_->numInputs; ++i) data = std::copy(inputs[i], inputs[i] + count, data); audioPort_.sendRequest(); audioPort_.waitResponse(); data = reinterpret_cast(frame->data); for(int i = 0; i < effect_->numOutputs; ++i) data = std::copy(outputs[i], outputs[i] + count, data); } intptr_t Plugin::dispatchProc(AEffect* effect, i32 opcode, i32 index, intptr_t value, void* ptr, float opt) { // Most of VST hosts send some dispatch events in separate threads. So, if the // current thread is different than the main thread, we will send this event through // the audio port for processing it inside the dedicated audio thread by the host // endpoint. Plugin* plugin = static_cast(effect->object); DataPort* port; RecursiveMutex* guard; // Ardour seems to be sending effEditOpen on something else besides the main thread. // However, we do want to send it to the control port, since that's where our // bridge expects it. if(opcode == effEditOpen || std::this_thread::get_id() == plugin->mainThreadId_) { port = &plugin->controlPort_; guard = &plugin->guard_; } else { port = &plugin->audioPort_; guard = &plugin->audioGuard_; } guard->lock(); int result = plugin->dispatch(port, opcode, index, value, ptr, opt); // If opcode equals to effClose, then plugin will be destroyed inside of // plugin->dispatch() call, thus we don't need to unlock the mutex and can't // dereference the guard pointer here if(opcode != effClose) guard->unlock(); return result; } float Plugin::getParameterProc(AEffect* effect, i32 index) { Plugin* plugin = static_cast(effect->object); if(plugin->lastIndex_ != -1 && std::this_thread::get_id() == plugin->lastThreadId_) { if(plugin->lastIndex_ != index) { ERROR("Unable to get parameter (%d!=%d)", plugin->lastIndex_, index); return 0.0f; } return plugin->lastValue_; } RecursiveLock lock(plugin->audioGuard_); return plugin->getParameter(index); } void Plugin::setParameterProc(AEffect* effect, i32 index, float value) { Plugin* plugin = static_cast(effect->object); RecursiveLock lock(plugin->audioGuard_); plugin->setParameter(index, value); } void Plugin::processReplacingProc(AEffect* effect, float** inputs, float** outputs, i32 sampleCount) { Plugin* plugin = static_cast(effect->object); RecursiveLock lock(plugin->audioGuard_); plugin->processReplacing(inputs, outputs, sampleCount); } void Plugin::processDoubleReplacingProc(AEffect* effect, double** inputs, double** outputs, i32 sampleCount) { Plugin* plugin = static_cast(effect->object); RecursiveLock lock(plugin->audioGuard_); plugin->processDoubleReplacing(inputs, outputs, sampleCount); } } // namespace Airwave ================================================ FILE: src/plugin/plugin.h ================================================ #ifndef PLUGIN_PLUGIN_H #define PLUGIN_PLUGIN_H #include #include #include #include #include #include #include "common/dataport.h" #include "common/event.h" #include "common/vst24.h" #include "common/vsteventkeeper.h" namespace Airwave { using RecursiveMutex = std::recursive_mutex; using RecursiveLock = std::lock_guard; class Plugin { public: Plugin(const std::string& vstPath, const std::string& hostPath, const std::string& prefixPath, const std::string& loaderPath, const std::string& logSocketPath, AudioMasterProc masterProc); ~Plugin(); AEffect* effect(); private: AudioMasterProc masterProc_; AEffect* effect_; ERect rect_; VstEventKeeper events_; uint8_t* data_; size_t dataLength_; std::vector chunk_; RecursiveMutex guard_; RecursiveMutex audioGuard_; DataPort controlPort_; DataPort callbackPort_; DataPort audioPort_; Event condition_; int childPid_; std::thread callbackThread_; std::atomic_flag processCallbacks_; std::thread::id mainThreadId_; // When handling audioMasterAutomate, Ardour calls back into the plugin using // getParameter(). It's unclear whether that's VST-legal or not, but at the moment it // seems to deadlock when processReplacing() is going on at the same time. // We will remember the parameter's value and feed it to the host when it will call // getParameter() from audioMasterAutomate handler. i32 lastIndex_; float lastValue_; std::thread::id lastThreadId_; void callbackThread(); intptr_t setBlockSize(DataPort* port, intptr_t frames); intptr_t handleAudioMaster(); intptr_t dispatch(DataPort* port, i32 opcode, i32 index, intptr_t value, void* ptr, float opt); void sendXembedMessage(Display* display, Window window, long message, long detail, long data1, long data2); float getParameter(i32 index); void setParameter(i32 index, float value); void processReplacing(float** inputs, float** outputs, i32 count); void processDoubleReplacing(double** inputs, double** outputs, i32 count); static intptr_t dispatchProc(AEffect* effect, i32 opcode, i32 index, intptr_t value, void* ptr, float opt); static float getParameterProc(AEffect* effect, i32 index); static void setParameterProc(AEffect* effect, i32 index, float value); static void processReplacingProc(AEffect* effect, float** inputs, float** outputs, i32 sampleCount); static void processDoubleReplacingProc(AEffect* effect, double** inputs, double** outputs, i32 sampleCount); }; } // namespace Airwave #endif // PLUGIN_PLUGIN_H