Full Code of psycha0s/airwave for AI

master e44976c37dde cached
85 files
440.3 KB
115.0k tokens
231 symbols
1 requests
Download .txt
Showing preview only (471K chars total). Download the full file or copy to clipboard to get everything.
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-<arch>.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. 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 <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#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<void*>(-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<void*>(-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<ControlBlock*>(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<typename T>
	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<typename T>
T* DataPort::frame()
{
	return static_cast<T*>(frameBuffer());
}


} // namespace Airwave


#endif // COMMON_DATAPORT_H


================================================
FILE: src/common/event.cpp
================================================
#include "event.h"

#include <errno.h>
#include <syscall.h>
#include <time.h>
#include <unistd.h>
#include <linux/futex.h>


#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 <atomic>

#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<int> count_;
};


#endif // COMMON_EVENT_H


================================================
FILE: src/common/filesystem.cpp
================================================
#include "filesystem.h"

#include <vector>
#include <pwd.h>
#include <unistd.h>
#include <linux/limits.h>
#include <sys/stat.h>


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 <string>


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<char>(cp);
  } else if (cp <= 0x7FF) {
    result.resize(2);
    result[1] = static_cast<char>(0x80 | (0x3f & cp));
    result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
  } else if (cp <= 0xFFFF) {
    result.resize(3);
    result[2] = static_cast<char>(0x80 | (0x3f & cp));
    result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
    result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
  } else if (cp <= 0x10FFFF) {
    result.resize(4);
    result[3] = static_cast<char>(0x80 | (0x3f & cp));
    result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
    result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
    result[0] = static_cast<char>(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 <json/assertions.h>
#include <json/reader.h>
#include <json/value.h>
#include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <utility>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <istream>
#include <sstream>
#include <memory>
#include <set>

#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<CharReader> CharReaderPtr;
#else
typedef std::auto_ptr<CharReader>   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<char> begin(sin);
  // std::istream_iterator<char> 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_ = &currentValue();
  }

  --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::StructuredError> Reader::getStructuredErrors() const {
  std::vector<Reader::StructuredError> 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<StructuredError> 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<ErrorInfo> 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<Value*> 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_ = &currentValue();
  }

  --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::StructuredError> OurReader::getStructuredErrors() const {
  std::vector<OurReader::StructuredError> 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<std::string>* 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<std::string> 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 <json/assertions.h>
#include <json/value.h>
#include <json/writer.h>
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <math.h>
#include <sstream>
#include <utility>
#include <cstring>
#include <cassert>
#ifdef JSON_USE_CPPTL
#include <cpptl/conststring.h>
#endif
#include <cstddef> // size_t
#include <algorithm> // 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<const Value&>(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 <typename T, typename U>
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<double>(Int64(value / 2)) * 2.0 + Int64(value & 1);
}

template <typename T> static inline double integerToDouble(T value) {
  return static_cast<double>(value);
}

template <typename T, typename U>
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<char*>(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<char*>(malloc(actualLength));
  if (newString == 0) {
    throwRuntimeError(
        "in Json::Value::duplicateAndPrefixStringValue(): "
        "Failed to allocate string value buffer");
  }
  *reinterpret_cast<unsigned*>(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<unsigned const*>(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<char*>(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<unsigned>(strlen(value)));
}

Value::Value(const char* beginValue, const char* endValue) {
  initBasic(stringValue, true);
  value_.string_ =
      duplicateAndPrefixStringValue(beginValue, static_cast<unsigned>(endValue - beginValue));
}

Value::Value(const std::string& value) {
  initBasic(stringValue, true);
  value_.string_ =
      duplicateAndPrefixStringValue(value.data(), static_cast<unsigned>(value.length()));
}

Value::Value(const StaticString& value) {
  initBasic(stringValue);
  value_.string_ = const_cast<char*>(value.c_str());
}

#ifdef JSON_USE_CPPTL
Value::Value(const CppTL::ConstString& value) {
  initBasic(stringValue, true);
  value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(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<double>(value_.int_);
  case uintValue:
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
    return static_cast<double>(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<float>(value_.int_);
  case uintValue:
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
    return static_cast<float>(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<float>(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<unsigned>(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<unsigned>(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<unsigned>(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<unsigned>(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<const CZString &>() ),
//         MemberNamesTransform() ) );
//   }
//   return EnumMemberNames();
//}
//
//
// EnumValues
// Value::enumValues() const
//{
//   if ( type_ == objectValue  ||  type_ == arrayValue )
//      return CppTL::Enum::anyValues( *(value_.map_),
//                                     CppTL::Type<const Value &>() );
//   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 <json/writer.h>
#include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include <set>
#include <cassert>
#include <cstring>
#include <cstdio>

#if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
#include <float.h>
#define isfinite _finite
#elif defined(__sun) && defined(__SVR4) //Solaris
#include <ieeefp.h>
#define isfinite finite
#else
#include <cmath>
#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<StreamWriter> StreamWriterPtr;
#else
typedef std::auto_ptr<StreamWriter>   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 </
    // sequence.
    // Should add a flag to allow this compatibility mode and prevent this
    // sequence from occurring.
    default:
      if (isControlCharacter(*c)) {
        std::ostringstream oss;
        oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
            << std::setw(4) << static_cast<int>(*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 </
    // sequence.
    // Should add a flag to allow this compatibility mode and prevent this
    // sequence from occurring.
    default:
      if ((isControlCharacter(*c)) || (*c == 0)) {
        std::ostringstream oss;
        oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
            << std::setw(4) << static_cast<int>(*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<unsigned>(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<std::string> 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<unsigned>(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<std::string>* 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<std::string> 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 <cpptl/config.h>
#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 <string>
#include <vector>
#include <exception>

#ifndef JSON_USE_CPPTL_SMALLMAP
#include <map>
#else
#include <cpptl/smallmap.h>
#endif
#ifdef JSON_USE_CPPTL
#include <cpptl/forwards.h>
#endif

// Disable warning C4251: <data member>: <type> 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<const char *> EnumMemberNames;
//   typedef CppTL::AnyEnumerator<const Value &> 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 <a HREF="http://www.json.org">JSON</a> 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<std::string> 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<CZString, Value> ObjectValues;
#else
  typedef CppTL::SmallMap<CZString, Value> 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 initializ
Download .txt
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
Download .txt
SYMBOL INDEX (231 symbols across 61 files)

FILE: src/common/dataport.cpp
  type Airwave (line 10) | namespace Airwave {

FILE: src/common/dataport.h
  function class (line 11) | class DataPort {

FILE: src/common/event.h
  function class (line 11) | class Event {

FILE: src/common/filesystem.cpp
  type Airwave (line 10) | namespace Airwave {
    type passwd (line 19) | struct passwd
    type stat (line 45) | struct stat

FILE: src/common/filesystem.h
  function namespace (line 7) | namespace Airwave {

FILE: src/common/json.cpp
  type Json (line 101) | namespace Json {
    function codePointToUTF8 (line 104) | static inline std::string codePointToUTF8(unsigned int cp) {
    function isControlCharacter (line 133) | static inline bool isControlCharacter(char ch) { return ch > 0 && ch <...
    function uintToString (line 149) | static inline void uintToString(LargestUInt value, char*& current) {
    function fixNumericLocale (line 162) | static inline void fixNumericLocale(char* begin, char* end) {
    function Features (line 235) | Features Features::all() { return Features(); }
    function Features (line 237) | Features Features::strictMode() {
    function containsNewLine (line 249) | static bool containsNewLine(Reader::Location begin, Reader::Location e...
    function normalizeEOL (line 541) | static std::string normalizeEOL(Reader::Location begin, Reader::Locati...
    function Value (line 972) | Value& Reader::currentValue() { return *(nodes_.top()); }
    class OurFeatures (line 1095) | class OurFeatures {
    function OurFeatures (line 1120) | OurFeatures OurFeatures::all() { return OurFeatures(); }
    class OurReader (line 1126) | class OurReader {
      type StructuredError (line 1130) | struct StructuredError {
      type TokenType (line 1151) | enum TokenType {
      class Token (line 1168) | class Token {
      class ErrorInfo (line 1175) | class ErrorInfo {
    function Value (line 1935) | Value& OurReader::currentValue() { return *(nodes_.top()); }
    class OurCharReader (line 2053) | class OurCharReader : public CharReader {
      method OurCharReader (line 2057) | OurCharReader(
      method parse (line 2063) | virtual bool parse(
    function CharReader (line 2080) | CharReader* CharReaderBuilder::newCharReader() const
    function getValidReaderKeys (line 2094) | static void getValidReaderKeys(std::set<std::string>* valid_keys)
    function Value (line 2124) | Value& CharReaderBuilder::operator[](std::string key)
    function parseFromStream (line 2160) | bool parseFromStream(
    function Value (line 2228) | Value& ValueIteratorBase::deref() const {
    function Value (line 2280) | Value ValueIteratorBase::key() const {
    function UInt (line 2290) | UInt ValueIteratorBase::index() const {
    function ValueConstIterator (line 2334) | ValueConstIterator& ValueConstIterator::
    function ValueIterator (line 2359) | ValueIterator& ValueIterator::operator=(const SelfType& other) {
    function InRange (line 2435) | static inline bool InRange(double d, T min, U max) {
    function integerToDouble (line 2439) | static inline double integerToDouble(Json::UInt64 value) {
    function integerToDouble (line 2443) | static inline double integerToDouble(T value) {
    function InRange (line 2448) | static inline bool InRange(double d, T min, U max) {
    function decodePrefixedString (line 2501) | inline static void decodePrefixedString(
    function releaseStringValue (line 2515) | static inline void releaseStringValue(char* value) { free(value); }
    class JSON_API (line 2533) | class JSON_API
    function RuntimeError (line 2541) | class JSON_API RuntimeError : public Exception {
    function LogicError (line 2545) | class JSON_API LogicError : public Exception {
    function throwRuntimeError (line 2565) | void throwRuntimeError(std::string const& msg)
    function throwLogicError (line 2569) | void throwLogicError(std::string const& msg)
    function ArrayIndex (line 2674) | ArrayIndex Value::CZString::index() const { return index_; }
    function Value (line 2847) | Value& Value::operator=(Value other) {
    function ValueType (line 2869) | ValueType Value::type() const { return type_; }
    function LargestInt (line 3120) | LargestInt Value::asLargestInt() const {
    function LargestUInt (line 3128) | LargestUInt Value::asLargestUInt() const {
    function ArrayIndex (line 3232) | ArrayIndex Value::size() const {
    function Value (line 3298) | Value& Value::operator[](ArrayIndex index) {
    function Value (line 3314) | Value& Value::operator[](int index) {
    function Value (line 3321) | const Value& Value::operator[](ArrayIndex index) const {
    function Value (line 3334) | const Value& Value::operator[](int index) const {
    function Value (line 3352) | Value& Value::resolveReference(const char* key) {
    function Value (line 3371) | Value& Value::resolveReference(char const* key, char const* end)
    function Value (line 3390) | Value Value::get(ArrayIndex index, const Value& defaultValue) const {
    function Value (line 3397) | Value const* Value::find(char const* key, char const* end) const
    function Value (line 3408) | const Value& Value::operator[](const char* key) const
    function Value (line 3414) | Value const& Value::operator[](std::string const& key) const
    function Value (line 3421) | Value& Value::operator[](const char* key) {
    function Value (line 3425) | Value& Value::operator[](const std::string& key) {
    function Value (line 3429) | Value& Value::operator[](const StaticString& key) {
    function Value (line 3434) | Value& Value::operator[](const CppTL::ConstString& key) {
    function Value (line 3437) | Value const& Value::operator[](CppTL::ConstString const& key) const
    function Value (line 3445) | Value& Value::append(const Value& value) { return (*this)[size()] = va...
    function Value (line 3447) | Value Value::get(char const* key, char const* end, Value const& defaul...
    function Value (line 3452) | Value Value::get(char const* key, Value const& defaultValue) const
    function Value (line 3456) | Value Value::get(std::string const& key, Value const& defaultValue) const
    function Value (line 3483) | Value Value::removeMember(const char* key)
    function Value (line 3494) | Value Value::removeMember(const std::string& key)
    function Value (line 3523) | Value Value::get(const CppTL::ConstString& key,
    function IsIntegral (line 3591) | static bool IsIntegral(double d) {
    function Value (line 3861) | const Value& Path::resolve(const Value& root) const {
    function Value (line 3884) | Value Path::resolve(const Value& root, const Value& defaultValue) const {
    function Value (line 3903) | Value& Path::make(Value& root) const {
    function containsControlCharacter (line 3985) | static bool containsControlCharacter(const char* str) {
    function containsControlCharacter0 (line 3993) | static bool containsControlCharacter0(const char* str, unsigned len) {
    function valueToString (line 4003) | std::string valueToString(LargestInt value) {
    function valueToString (line 4016) | std::string valueToString(LargestUInt value) {
    function valueToString (line 4026) | std::string valueToString(Int value) {
    function valueToString (line 4030) | std::string valueToString(UInt value) {
    function valueToString (line 4036) | std::string valueToString(double value) {
    function valueToString (line 4073) | std::string valueToString(bool value) { return value ? "true" : "false...
    function valueToQuotedString (line 4075) | std::string valueToQuotedString(const char* value) {
    function valueToQuotedStringN (line 4152) | static std::string valueToQuotedStringN(const char* value, unsigned le...
    type CommentStyle (line 4715) | struct CommentStyle {
      type Enum (line 4717) | enum Enum {
    type BuiltStyledStreamWriter (line 4724) | struct BuiltStyledStreamWriter : public StreamWriter
    function StreamWriter (line 5011) | StreamWriter* StreamWriterBuilder::newStreamWriter() const
    function getValidWriterKeys (line 5040) | static void getValidWriterKeys(std::set<std::string>* valid_keys)
    function Value (line 5065) | Value& StreamWriterBuilder::operator[](std::string key)
    function writeString (line 5080) | std::string writeString(StreamWriter::Factory const& builder, Value co...
  type Json (line 220) | namespace Json {
    function codePointToUTF8 (line 104) | static inline std::string codePointToUTF8(unsigned int cp) {
    function isControlCharacter (line 133) | static inline bool isControlCharacter(char ch) { return ch > 0 && ch <...
    function uintToString (line 149) | static inline void uintToString(LargestUInt value, char*& current) {
    function fixNumericLocale (line 162) | static inline void fixNumericLocale(char* begin, char* end) {
    function Features (line 235) | Features Features::all() { return Features(); }
    function Features (line 237) | Features Features::strictMode() {
    function containsNewLine (line 249) | static bool containsNewLine(Reader::Location begin, Reader::Location e...
    function normalizeEOL (line 541) | static std::string normalizeEOL(Reader::Location begin, Reader::Locati...
    function Value (line 972) | Value& Reader::currentValue() { return *(nodes_.top()); }
    class OurFeatures (line 1095) | class OurFeatures {
    function OurFeatures (line 1120) | OurFeatures OurFeatures::all() { return OurFeatures(); }
    class OurReader (line 1126) | class OurReader {
      type StructuredError (line 1130) | struct StructuredError {
      type TokenType (line 1151) | enum TokenType {
      class Token (line 1168) | class Token {
      class ErrorInfo (line 1175) | class ErrorInfo {
    function Value (line 1935) | Value& OurReader::currentValue() { return *(nodes_.top()); }
    class OurCharReader (line 2053) | class OurCharReader : public CharReader {
      method OurCharReader (line 2057) | OurCharReader(
      method parse (line 2063) | virtual bool parse(
    function CharReader (line 2080) | CharReader* CharReaderBuilder::newCharReader() const
    function getValidReaderKeys (line 2094) | static void getValidReaderKeys(std::set<std::string>* valid_keys)
    function Value (line 2124) | Value& CharReaderBuilder::operator[](std::string key)
    function parseFromStream (line 2160) | bool parseFromStream(
    function Value (line 2228) | Value& ValueIteratorBase::deref() const {
    function Value (line 2280) | Value ValueIteratorBase::key() const {
    function UInt (line 2290) | UInt ValueIteratorBase::index() const {
    function ValueConstIterator (line 2334) | ValueConstIterator& ValueConstIterator::
    function ValueIterator (line 2359) | ValueIterator& ValueIterator::operator=(const SelfType& other) {
    function InRange (line 2435) | static inline bool InRange(double d, T min, U max) {
    function integerToDouble (line 2439) | static inline double integerToDouble(Json::UInt64 value) {
    function integerToDouble (line 2443) | static inline double integerToDouble(T value) {
    function InRange (line 2448) | static inline bool InRange(double d, T min, U max) {
    function decodePrefixedString (line 2501) | inline static void decodePrefixedString(
    function releaseStringValue (line 2515) | static inline void releaseStringValue(char* value) { free(value); }
    class JSON_API (line 2533) | class JSON_API
    function RuntimeError (line 2541) | class JSON_API RuntimeError : public Exception {
    function LogicError (line 2545) | class JSON_API LogicError : public Exception {
    function throwRuntimeError (line 2565) | void throwRuntimeError(std::string const& msg)
    function throwLogicError (line 2569) | void throwLogicError(std::string const& msg)
    function ArrayIndex (line 2674) | ArrayIndex Value::CZString::index() const { return index_; }
    function Value (line 2847) | Value& Value::operator=(Value other) {
    function ValueType (line 2869) | ValueType Value::type() const { return type_; }
    function LargestInt (line 3120) | LargestInt Value::asLargestInt() const {
    function LargestUInt (line 3128) | LargestUInt Value::asLargestUInt() const {
    function ArrayIndex (line 3232) | ArrayIndex Value::size() const {
    function Value (line 3298) | Value& Value::operator[](ArrayIndex index) {
    function Value (line 3314) | Value& Value::operator[](int index) {
    function Value (line 3321) | const Value& Value::operator[](ArrayIndex index) const {
    function Value (line 3334) | const Value& Value::operator[](int index) const {
    function Value (line 3352) | Value& Value::resolveReference(const char* key) {
    function Value (line 3371) | Value& Value::resolveReference(char const* key, char const* end)
    function Value (line 3390) | Value Value::get(ArrayIndex index, const Value& defaultValue) const {
    function Value (line 3397) | Value const* Value::find(char const* key, char const* end) const
    function Value (line 3408) | const Value& Value::operator[](const char* key) const
    function Value (line 3414) | Value const& Value::operator[](std::string const& key) const
    function Value (line 3421) | Value& Value::operator[](const char* key) {
    function Value (line 3425) | Value& Value::operator[](const std::string& key) {
    function Value (line 3429) | Value& Value::operator[](const StaticString& key) {
    function Value (line 3434) | Value& Value::operator[](const CppTL::ConstString& key) {
    function Value (line 3437) | Value const& Value::operator[](CppTL::ConstString const& key) const
    function Value (line 3445) | Value& Value::append(const Value& value) { return (*this)[size()] = va...
    function Value (line 3447) | Value Value::get(char const* key, char const* end, Value const& defaul...
    function Value (line 3452) | Value Value::get(char const* key, Value const& defaultValue) const
    function Value (line 3456) | Value Value::get(std::string const& key, Value const& defaultValue) const
    function Value (line 3483) | Value Value::removeMember(const char* key)
    function Value (line 3494) | Value Value::removeMember(const std::string& key)
    function Value (line 3523) | Value Value::get(const CppTL::ConstString& key,
    function IsIntegral (line 3591) | static bool IsIntegral(double d) {
    function Value (line 3861) | const Value& Path::resolve(const Value& root) const {
    function Value (line 3884) | Value Path::resolve(const Value& root, const Value& defaultValue) const {
    function Value (line 3903) | Value& Path::make(Value& root) const {
    function containsControlCharacter (line 3985) | static bool containsControlCharacter(const char* str) {
    function containsControlCharacter0 (line 3993) | static bool containsControlCharacter0(const char* str, unsigned len) {
    function valueToString (line 4003) | std::string valueToString(LargestInt value) {
    function valueToString (line 4016) | std::string valueToString(LargestUInt value) {
    function valueToString (line 4026) | std::string valueToString(Int value) {
    function valueToString (line 4030) | std::string valueToString(UInt value) {
    function valueToString (line 4036) | std::string valueToString(double value) {
    function valueToString (line 4073) | std::string valueToString(bool value) { return value ? "true" : "false...
    function valueToQuotedString (line 4075) | std::string valueToQuotedString(const char* value) {
    function valueToQuotedStringN (line 4152) | static std::string valueToQuotedStringN(const char* value, unsigned le...
    type CommentStyle (line 4715) | struct CommentStyle {
      type Enum (line 4717) | enum Enum {
    type BuiltStyledStreamWriter (line 4724) | struct BuiltStyledStreamWriter : public StreamWriter
    function StreamWriter (line 5011) | StreamWriter* StreamWriterBuilder::newStreamWriter() const
    function getValidWriterKeys (line 5040) | static void getValidWriterKeys(std::set<std::string>* valid_keys)
    function Value (line 5065) | Value& StreamWriterBuilder::operator[](std::string key)
    function writeString (line 5080) | std::string writeString(StreamWriter::Factory const& builder, Value co...
  type Json (line 2210) | namespace Json {
    function codePointToUTF8 (line 104) | static inline std::string codePointToUTF8(unsigned int cp) {
    function isControlCharacter (line 133) | static inline bool isControlCharacter(char ch) { return ch > 0 && ch <...
    function uintToString (line 149) | static inline void uintToString(LargestUInt value, char*& current) {
    function fixNumericLocale (line 162) | static inline void fixNumericLocale(char* begin, char* end) {
    function Features (line 235) | Features Features::all() { return Features(); }
    function Features (line 237) | Features Features::strictMode() {
    function containsNewLine (line 249) | static bool containsNewLine(Reader::Location begin, Reader::Location e...
    function normalizeEOL (line 541) | static std::string normalizeEOL(Reader::Location begin, Reader::Locati...
    function Value (line 972) | Value& Reader::currentValue() { return *(nodes_.top()); }
    class OurFeatures (line 1095) | class OurFeatures {
    function OurFeatures (line 1120) | OurFeatures OurFeatures::all() { return OurFeatures(); }
    class OurReader (line 1126) | class OurReader {
      type StructuredError (line 1130) | struct StructuredError {
      type TokenType (line 1151) | enum TokenType {
      class Token (line 1168) | class Token {
      class ErrorInfo (line 1175) | class ErrorInfo {
    function Value (line 1935) | Value& OurReader::currentValue() { return *(nodes_.top()); }
    class OurCharReader (line 2053) | class OurCharReader : public CharReader {
      method OurCharReader (line 2057) | OurCharReader(
      method parse (line 2063) | virtual bool parse(
    function CharReader (line 2080) | CharReader* CharReaderBuilder::newCharReader() const
    function getValidReaderKeys (line 2094) | static void getValidReaderKeys(std::set<std::string>* valid_keys)
    function Value (line 2124) | Value& CharReaderBuilder::operator[](std::string key)
    function parseFromStream (line 2160) | bool parseFromStream(
    function Value (line 2228) | Value& ValueIteratorBase::deref() const {
    function Value (line 2280) | Value ValueIteratorBase::key() const {
    function UInt (line 2290) | UInt ValueIteratorBase::index() const {
    function ValueConstIterator (line 2334) | ValueConstIterator& ValueConstIterator::
    function ValueIterator (line 2359) | ValueIterator& ValueIterator::operator=(const SelfType& other) {
    function InRange (line 2435) | static inline bool InRange(double d, T min, U max) {
    function integerToDouble (line 2439) | static inline double integerToDouble(Json::UInt64 value) {
    function integerToDouble (line 2443) | static inline double integerToDouble(T value) {
    function InRange (line 2448) | static inline bool InRange(double d, T min, U max) {
    function decodePrefixedString (line 2501) | inline static void decodePrefixedString(
    function releaseStringValue (line 2515) | static inline void releaseStringValue(char* value) { free(value); }
    class JSON_API (line 2533) | class JSON_API
    function RuntimeError (line 2541) | class JSON_API RuntimeError : public Exception {
    function LogicError (line 2545) | class JSON_API LogicError : public Exception {
    function throwRuntimeError (line 2565) | void throwRuntimeError(std::string const& msg)
    function throwLogicError (line 2569) | void throwLogicError(std::string const& msg)
    function ArrayIndex (line 2674) | ArrayIndex Value::CZString::index() const { return index_; }
    function Value (line 2847) | Value& Value::operator=(Value other) {
    function ValueType (line 2869) | ValueType Value::type() const { return type_; }
    function LargestInt (line 3120) | LargestInt Value::asLargestInt() const {
    function LargestUInt (line 3128) | LargestUInt Value::asLargestUInt() const {
    function ArrayIndex (line 3232) | ArrayIndex Value::size() const {
    function Value (line 3298) | Value& Value::operator[](ArrayIndex index) {
    function Value (line 3314) | Value& Value::operator[](int index) {
    function Value (line 3321) | const Value& Value::operator[](ArrayIndex index) const {
    function Value (line 3334) | const Value& Value::operator[](int index) const {
    function Value (line 3352) | Value& Value::resolveReference(const char* key) {
    function Value (line 3371) | Value& Value::resolveReference(char const* key, char const* end)
    function Value (line 3390) | Value Value::get(ArrayIndex index, const Value& defaultValue) const {
    function Value (line 3397) | Value const* Value::find(char const* key, char const* end) const
    function Value (line 3408) | const Value& Value::operator[](const char* key) const
    function Value (line 3414) | Value const& Value::operator[](std::string const& key) const
    function Value (line 3421) | Value& Value::operator[](const char* key) {
    function Value (line 3425) | Value& Value::operator[](const std::string& key) {
    function Value (line 3429) | Value& Value::operator[](const StaticString& key) {
    function Value (line 3434) | Value& Value::operator[](const CppTL::ConstString& key) {
    function Value (line 3437) | Value const& Value::operator[](CppTL::ConstString const& key) const
    function Value (line 3445) | Value& Value::append(const Value& value) { return (*this)[size()] = va...
    function Value (line 3447) | Value Value::get(char const* key, char const* end, Value const& defaul...
    function Value (line 3452) | Value Value::get(char const* key, Value const& defaultValue) const
    function Value (line 3456) | Value Value::get(std::string const& key, Value const& defaultValue) const
    function Value (line 3483) | Value Value::removeMember(const char* key)
    function Value (line 3494) | Value Value::removeMember(const std::string& key)
    function Value (line 3523) | Value Value::get(const CppTL::ConstString& key,
    function IsIntegral (line 3591) | static bool IsIntegral(double d) {
    function Value (line 3861) | const Value& Path::resolve(const Value& root) const {
    function Value (line 3884) | Value Path::resolve(const Value& root, const Value& defaultValue) const {
    function Value (line 3903) | Value& Path::make(Value& root) const {
    function containsControlCharacter (line 3985) | static bool containsControlCharacter(const char* str) {
    function containsControlCharacter0 (line 3993) | static bool containsControlCharacter0(const char* str, unsigned len) {
    function valueToString (line 4003) | std::string valueToString(LargestInt value) {
    function valueToString (line 4016) | std::string valueToString(LargestUInt value) {
    function valueToString (line 4026) | std::string valueToString(Int value) {
    function valueToString (line 4030) | std::string valueToString(UInt value) {
    function valueToString (line 4036) | std::string valueToString(double value) {
    function valueToString (line 4073) | std::string valueToString(bool value) { return value ? "true" : "false...
    function valueToQuotedString (line 4075) | std::string valueToQuotedString(const char* value) {
    function valueToQuotedStringN (line 4152) | static std::string valueToQuotedStringN(const char* value, unsigned le...
    type CommentStyle (line 4715) | struct CommentStyle {
      type Enum (line 4717) | enum Enum {
    type BuiltStyledStreamWriter (line 4724) | struct BuiltStyledStreamWriter : public StreamWriter
    function StreamWriter (line 5011) | StreamWriter* StreamWriterBuilder::newStreamWriter() const
    function getValidWriterKeys (line 5040) | static void getValidWriterKeys(std::set<std::string>* valid_keys)
    function Value (line 5065) | Value& StreamWriterBuilder::operator[](std::string key)
    function writeString (line 5080) | std::string writeString(StreamWriter::Factory const& builder, Value co...
  type Json (line 2402) | namespace Json {
    function codePointToUTF8 (line 104) | static inline std::string codePointToUTF8(unsigned int cp) {
    function isControlCharacter (line 133) | static inline bool isControlCharacter(char ch) { return ch > 0 && ch <...
    function uintToString (line 149) | static inline void uintToString(LargestUInt value, char*& current) {
    function fixNumericLocale (line 162) | static inline void fixNumericLocale(char* begin, char* end) {
    function Features (line 235) | Features Features::all() { return Features(); }
    function Features (line 237) | Features Features::strictMode() {
    function containsNewLine (line 249) | static bool containsNewLine(Reader::Location begin, Reader::Location e...
    function normalizeEOL (line 541) | static std::string normalizeEOL(Reader::Location begin, Reader::Locati...
    function Value (line 972) | Value& Reader::currentValue() { return *(nodes_.top()); }
    class OurFeatures (line 1095) | class OurFeatures {
    function OurFeatures (line 1120) | OurFeatures OurFeatures::all() { return OurFeatures(); }
    class OurReader (line 1126) | class OurReader {
      type StructuredError (line 1130) | struct StructuredError {
      type TokenType (line 1151) | enum TokenType {
      class Token (line 1168) | class Token {
      class ErrorInfo (line 1175) | class ErrorInfo {
    function Value (line 1935) | Value& OurReader::currentValue() { return *(nodes_.top()); }
    class OurCharReader (line 2053) | class OurCharReader : public CharReader {
      method OurCharReader (line 2057) | OurCharReader(
      method parse (line 2063) | virtual bool parse(
    function CharReader (line 2080) | CharReader* CharReaderBuilder::newCharReader() const
    function getValidReaderKeys (line 2094) | static void getValidReaderKeys(std::set<std::string>* valid_keys)
    function Value (line 2124) | Value& CharReaderBuilder::operator[](std::string key)
    function parseFromStream (line 2160) | bool parseFromStream(
    function Value (line 2228) | Value& ValueIteratorBase::deref() const {
    function Value (line 2280) | Value ValueIteratorBase::key() const {
    function UInt (line 2290) | UInt ValueIteratorBase::index() const {
    function ValueConstIterator (line 2334) | ValueConstIterator& ValueConstIterator::
    function ValueIterator (line 2359) | ValueIterator& ValueIterator::operator=(const SelfType& other) {
    function InRange (line 2435) | static inline bool InRange(double d, T min, U max) {
    function integerToDouble (line 2439) | static inline double integerToDouble(Json::UInt64 value) {
    function integerToDouble (line 2443) | static inline double integerToDouble(T value) {
    function InRange (line 2448) | static inline bool InRange(double d, T min, U max) {
    function decodePrefixedString (line 2501) | inline static void decodePrefixedString(
    function releaseStringValue (line 2515) | static inline void releaseStringValue(char* value) { free(value); }
    class JSON_API (line 2533) | class JSON_API
    function RuntimeError (line 2541) | class JSON_API RuntimeError : public Exception {
    function LogicError (line 2545) | class JSON_API LogicError : public Exception {
    function throwRuntimeError (line 2565) | void throwRuntimeError(std::string const& msg)
    function throwLogicError (line 2569) | void throwLogicError(std::string const& msg)
    function ArrayIndex (line 2674) | ArrayIndex Value::CZString::index() const { return index_; }
    function Value (line 2847) | Value& Value::operator=(Value other) {
    function ValueType (line 2869) | ValueType Value::type() const { return type_; }
    function LargestInt (line 3120) | LargestInt Value::asLargestInt() const {
    function LargestUInt (line 3128) | LargestUInt Value::asLargestUInt() const {
    function ArrayIndex (line 3232) | ArrayIndex Value::size() const {
    function Value (line 3298) | Value& Value::operator[](ArrayIndex index) {
    function Value (line 3314) | Value& Value::operator[](int index) {
    function Value (line 3321) | const Value& Value::operator[](ArrayIndex index) const {
    function Value (line 3334) | const Value& Value::operator[](int index) const {
    function Value (line 3352) | Value& Value::resolveReference(const char* key) {
    function Value (line 3371) | Value& Value::resolveReference(char const* key, char const* end)
    function Value (line 3390) | Value Value::get(ArrayIndex index, const Value& defaultValue) const {
    function Value (line 3397) | Value const* Value::find(char const* key, char const* end) const
    function Value (line 3408) | const Value& Value::operator[](const char* key) const
    function Value (line 3414) | Value const& Value::operator[](std::string const& key) const
    function Value (line 3421) | Value& Value::operator[](const char* key) {
    function Value (line 3425) | Value& Value::operator[](const std::string& key) {
    function Value (line 3429) | Value& Value::operator[](const StaticString& key) {
    function Value (line 3434) | Value& Value::operator[](const CppTL::ConstString& key) {
    function Value (line 3437) | Value const& Value::operator[](CppTL::ConstString const& key) const
    function Value (line 3445) | Value& Value::append(const Value& value) { return (*this)[size()] = va...
    function Value (line 3447) | Value Value::get(char const* key, char const* end, Value const& defaul...
    function Value (line 3452) | Value Value::get(char const* key, Value const& defaultValue) const
    function Value (line 3456) | Value Value::get(std::string const& key, Value const& defaultValue) const
    function Value (line 3483) | Value Value::removeMember(const char* key)
    function Value (line 3494) | Value Value::removeMember(const std::string& key)
    function Value (line 3523) | Value Value::get(const CppTL::ConstString& key,
    function IsIntegral (line 3591) | static bool IsIntegral(double d) {
    function Value (line 3861) | const Value& Path::resolve(const Value& root) const {
    function Value (line 3884) | Value Path::resolve(const Value& root, const Value& defaultValue) const {
    function Value (line 3903) | Value& Path::make(Value& root) const {
    function containsControlCharacter (line 3985) | static bool containsControlCharacter(const char* str) {
    function containsControlCharacter0 (line 3993) | static bool containsControlCharacter0(const char* str, unsigned len) {
    function valueToString (line 4003) | std::string valueToString(LargestInt value) {
    function valueToString (line 4016) | std::string valueToString(LargestUInt value) {
    function valueToString (line 4026) | std::string valueToString(Int value) {
    function valueToString (line 4030) | std::string valueToString(UInt value) {
    function valueToString (line 4036) | std::string valueToString(double value) {
    function valueToString (line 4073) | std::string valueToString(bool value) { return value ? "true" : "false...
    function valueToQuotedString (line 4075) | std::string valueToQuotedString(const char* value) {
    function valueToQuotedStringN (line 4152) | static std::string valueToQuotedStringN(const char* value, unsigned le...
    type CommentStyle (line 4715) | struct CommentStyle {
      type Enum (line 4717) | enum Enum {
    type BuiltStyledStreamWriter (line 4724) | struct BuiltStyledStreamWriter : public StreamWriter
    function StreamWriter (line 5011) | StreamWriter* StreamWriterBuilder::newStreamWriter() const
    function getValidWriterKeys (line 5040) | static void getValidWriterKeys(std::set<std::string>* valid_keys)
    function Value (line 5065) | Value& StreamWriterBuilder::operator[](std::string key)
    function writeString (line 5080) | std::string writeString(StreamWriter::Factory const& builder, Value co...
  type Json (line 2531) | namespace Json {
    function codePointToUTF8 (line 104) | static inline std::string codePointToUTF8(unsigned int cp) {
    function isControlCharacter (line 133) | static inline bool isControlCharacter(char ch) { return ch > 0 && ch <...
    function uintToString (line 149) | static inline void uintToString(LargestUInt value, char*& current) {
    function fixNumericLocale (line 162) | static inline void fixNumericLocale(char* begin, char* end) {
    function Features (line 235) | Features Features::all() { return Features(); }
    function Features (line 237) | Features Features::strictMode() {
    function containsNewLine (line 249) | static bool containsNewLine(Reader::Location begin, Reader::Location e...
    function normalizeEOL (line 541) | static std::string normalizeEOL(Reader::Location begin, Reader::Locati...
    function Value (line 972) | Value& Reader::currentValue() { return *(nodes_.top()); }
    class OurFeatures (line 1095) | class OurFeatures {
    function OurFeatures (line 1120) | OurFeatures OurFeatures::all() { return OurFeatures(); }
    class OurReader (line 1126) | class OurReader {
      type StructuredError (line 1130) | struct StructuredError {
      type TokenType (line 1151) | enum TokenType {
      class Token (line 1168) | class Token {
      class ErrorInfo (line 1175) | class ErrorInfo {
    function Value (line 1935) | Value& OurReader::currentValue() { return *(nodes_.top()); }
    class OurCharReader (line 2053) | class OurCharReader : public CharReader {
      method OurCharReader (line 2057) | OurCharReader(
      method parse (line 2063) | virtual bool parse(
    function CharReader (line 2080) | CharReader* CharReaderBuilder::newCharReader() const
    function getValidReaderKeys (line 2094) | static void getValidReaderKeys(std::set<std::string>* valid_keys)
    function Value (line 2124) | Value& CharReaderBuilder::operator[](std::string key)
    function parseFromStream (line 2160) | bool parseFromStream(
    function Value (line 2228) | Value& ValueIteratorBase::deref() const {
    function Value (line 2280) | Value ValueIteratorBase::key() const {
    function UInt (line 2290) | UInt ValueIteratorBase::index() const {
    function ValueConstIterator (line 2334) | ValueConstIterator& ValueConstIterator::
    function ValueIterator (line 2359) | ValueIterator& ValueIterator::operator=(const SelfType& other) {
    function InRange (line 2435) | static inline bool InRange(double d, T min, U max) {
    function integerToDouble (line 2439) | static inline double integerToDouble(Json::UInt64 value) {
    function integerToDouble (line 2443) | static inline double integerToDouble(T value) {
    function InRange (line 2448) | static inline bool InRange(double d, T min, U max) {
    function decodePrefixedString (line 2501) | inline static void decodePrefixedString(
    function releaseStringValue (line 2515) | static inline void releaseStringValue(char* value) { free(value); }
    class JSON_API (line 2533) | class JSON_API
    function RuntimeError (line 2541) | class JSON_API RuntimeError : public Exception {
    function LogicError (line 2545) | class JSON_API LogicError : public Exception {
    function throwRuntimeError (line 2565) | void throwRuntimeError(std::string const& msg)
    function throwLogicError (line 2569) | void throwLogicError(std::string const& msg)
    function ArrayIndex (line 2674) | ArrayIndex Value::CZString::index() const { return index_; }
    function Value (line 2847) | Value& Value::operator=(Value other) {
    function ValueType (line 2869) | ValueType Value::type() const { return type_; }
    function LargestInt (line 3120) | LargestInt Value::asLargestInt() const {
    function LargestUInt (line 3128) | LargestUInt Value::asLargestUInt() const {
    function ArrayIndex (line 3232) | ArrayIndex Value::size() const {
    function Value (line 3298) | Value& Value::operator[](ArrayIndex index) {
    function Value (line 3314) | Value& Value::operator[](int index) {
    function Value (line 3321) | const Value& Value::operator[](ArrayIndex index) const {
    function Value (line 3334) | const Value& Value::operator[](int index) const {
    function Value (line 3352) | Value& Value::resolveReference(const char* key) {
    function Value (line 3371) | Value& Value::resolveReference(char const* key, char const* end)
    function Value (line 3390) | Value Value::get(ArrayIndex index, const Value& defaultValue) const {
    function Value (line 3397) | Value const* Value::find(char const* key, char const* end) const
    function Value (line 3408) | const Value& Value::operator[](const char* key) const
    function Value (line 3414) | Value const& Value::operator[](std::string const& key) const
    function Value (line 3421) | Value& Value::operator[](const char* key) {
    function Value (line 3425) | Value& Value::operator[](const std::string& key) {
    function Value (line 3429) | Value& Value::operator[](const StaticString& key) {
    function Value (line 3434) | Value& Value::operator[](const CppTL::ConstString& key) {
    function Value (line 3437) | Value const& Value::operator[](CppTL::ConstString const& key) const
    function Value (line 3445) | Value& Value::append(const Value& value) { return (*this)[size()] = va...
    function Value (line 3447) | Value Value::get(char const* key, char const* end, Value const& defaul...
    function Value (line 3452) | Value Value::get(char const* key, Value const& defaultValue) const
    function Value (line 3456) | Value Value::get(std::string const& key, Value const& defaultValue) const
    function Value (line 3483) | Value Value::removeMember(const char* key)
    function Value (line 3494) | Value Value::removeMember(const std::string& key)
    function Value (line 3523) | Value Value::get(const CppTL::ConstString& key,
    function IsIntegral (line 3591) | static bool IsIntegral(double d) {
    function Value (line 3861) | const Value& Path::resolve(const Value& root) const {
    function Value (line 3884) | Value Path::resolve(const Value& root, const Value& defaultValue) const {
    function Value (line 3903) | Value& Path::make(Value& root) const {
    function containsControlCharacter (line 3985) | static bool containsControlCharacter(const char* str) {
    function containsControlCharacter0 (line 3993) | static bool containsControlCharacter0(const char* str, unsigned len) {
    function valueToString (line 4003) | std::string valueToString(LargestInt value) {
    function valueToString (line 4016) | std::string valueToString(LargestUInt value) {
    function valueToString (line 4026) | std::string valueToString(Int value) {
    function valueToString (line 4030) | std::string valueToString(UInt value) {
    function valueToString (line 4036) | std::string valueToString(double value) {
    function valueToString (line 4073) | std::string valueToString(bool value) { return value ? "true" : "false...
    function valueToQuotedString (line 4075) | std::string valueToQuotedString(const char* value) {
    function valueToQuotedStringN (line 4152) | static std::string valueToQuotedStringN(const char* value, unsigned le...
    type CommentStyle (line 4715) | struct CommentStyle {
      type Enum (line 4717) | enum Enum {
    type BuiltStyledStreamWriter (line 4724) | struct BuiltStyledStreamWriter : public StreamWriter
    function StreamWriter (line 5011) | StreamWriter* StreamWriterBuilder::newStreamWriter() const
    function getValidWriterKeys (line 5040) | static void getValidWriterKeys(std::set<std::string>* valid_keys)
    function Value (line 5065) | Value& StreamWriterBuilder::operator[](std::string key)
    function writeString (line 5080) | std::string writeString(StreamWriter::Factory const& builder, Value co...
  type Json (line 3977) | namespace Json {
    function codePointToUTF8 (line 104) | static inline std::string codePointToUTF8(unsigned int cp) {
    function isControlCharacter (line 133) | static inline bool isControlCharacter(char ch) { return ch > 0 && ch <...
    function uintToString (line 149) | static inline void uintToString(LargestUInt value, char*& current) {
    function fixNumericLocale (line 162) | static inline void fixNumericLocale(char* begin, char* end) {
    function Features (line 235) | Features Features::all() { return Features(); }
    function Features (line 237) | Features Features::strictMode() {
    function containsNewLine (line 249) | static bool containsNewLine(Reader::Location begin, Reader::Location e...
    function normalizeEOL (line 541) | static std::string normalizeEOL(Reader::Location begin, Reader::Locati...
    function Value (line 972) | Value& Reader::currentValue() { return *(nodes_.top()); }
    class OurFeatures (line 1095) | class OurFeatures {
    function OurFeatures (line 1120) | OurFeatures OurFeatures::all() { return OurFeatures(); }
    class OurReader (line 1126) | class OurReader {
      type StructuredError (line 1130) | struct StructuredError {
      type TokenType (line 1151) | enum TokenType {
      class Token (line 1168) | class Token {
      class ErrorInfo (line 1175) | class ErrorInfo {
    function Value (line 1935) | Value& OurReader::currentValue() { return *(nodes_.top()); }
    class OurCharReader (line 2053) | class OurCharReader : public CharReader {
      method OurCharReader (line 2057) | OurCharReader(
      method parse (line 2063) | virtual bool parse(
    function CharReader (line 2080) | CharReader* CharReaderBuilder::newCharReader() const
    function getValidReaderKeys (line 2094) | static void getValidReaderKeys(std::set<std::string>* valid_keys)
    function Value (line 2124) | Value& CharReaderBuilder::operator[](std::string key)
    function parseFromStream (line 2160) | bool parseFromStream(
    function Value (line 2228) | Value& ValueIteratorBase::deref() const {
    function Value (line 2280) | Value ValueIteratorBase::key() const {
    function UInt (line 2290) | UInt ValueIteratorBase::index() const {
    function ValueConstIterator (line 2334) | ValueConstIterator& ValueConstIterator::
    function ValueIterator (line 2359) | ValueIterator& ValueIterator::operator=(const SelfType& other) {
    function InRange (line 2435) | static inline bool InRange(double d, T min, U max) {
    function integerToDouble (line 2439) | static inline double integerToDouble(Json::UInt64 value) {
    function integerToDouble (line 2443) | static inline double integerToDouble(T value) {
    function InRange (line 2448) | static inline bool InRange(double d, T min, U max) {
    function decodePrefixedString (line 2501) | inline static void decodePrefixedString(
    function releaseStringValue (line 2515) | static inline void releaseStringValue(char* value) { free(value); }
    class JSON_API (line 2533) | class JSON_API
    function RuntimeError (line 2541) | class JSON_API RuntimeError : public Exception {
    function LogicError (line 2545) | class JSON_API LogicError : public Exception {
    function throwRuntimeError (line 2565) | void throwRuntimeError(std::string const& msg)
    function throwLogicError (line 2569) | void throwLogicError(std::string const& msg)
    function ArrayIndex (line 2674) | ArrayIndex Value::CZString::index() const { return index_; }
    function Value (line 2847) | Value& Value::operator=(Value other) {
    function ValueType (line 2869) | ValueType Value::type() const { return type_; }
    function LargestInt (line 3120) | LargestInt Value::asLargestInt() const {
    function LargestUInt (line 3128) | LargestUInt Value::asLargestUInt() const {
    function ArrayIndex (line 3232) | ArrayIndex Value::size() const {
    function Value (line 3298) | Value& Value::operator[](ArrayIndex index) {
    function Value (line 3314) | Value& Value::operator[](int index) {
    function Value (line 3321) | const Value& Value::operator[](ArrayIndex index) const {
    function Value (line 3334) | const Value& Value::operator[](int index) const {
    function Value (line 3352) | Value& Value::resolveReference(const char* key) {
    function Value (line 3371) | Value& Value::resolveReference(char const* key, char const* end)
    function Value (line 3390) | Value Value::get(ArrayIndex index, const Value& defaultValue) const {
    function Value (line 3397) | Value const* Value::find(char const* key, char const* end) const
    function Value (line 3408) | const Value& Value::operator[](const char* key) const
    function Value (line 3414) | Value const& Value::operator[](std::string const& key) const
    function Value (line 3421) | Value& Value::operator[](const char* key) {
    function Value (line 3425) | Value& Value::operator[](const std::string& key) {
    function Value (line 3429) | Value& Value::operator[](const StaticString& key) {
    function Value (line 3434) | Value& Value::operator[](const CppTL::ConstString& key) {
    function Value (line 3437) | Value const& Value::operator[](CppTL::ConstString const& key) const
    function Value (line 3445) | Value& Value::append(const Value& value) { return (*this)[size()] = va...
    function Value (line 3447) | Value Value::get(char const* key, char const* end, Value const& defaul...
    function Value (line 3452) | Value Value::get(char const* key, Value const& defaultValue) const
    function Value (line 3456) | Value Value::get(std::string const& key, Value const& defaultValue) const
    function Value (line 3483) | Value Value::removeMember(const char* key)
    function Value (line 3494) | Value Value::removeMember(const std::string& key)
    function Value (line 3523) | Value Value::get(const CppTL::ConstString& key,
    function IsIntegral (line 3591) | static bool IsIntegral(double d) {
    function Value (line 3861) | const Value& Path::resolve(const Value& root) const {
    function Value (line 3884) | Value Path::resolve(const Value& root, const Value& defaultValue) const {
    function Value (line 3903) | Value& Path::make(Value& root) const {
    function containsControlCharacter (line 3985) | static bool containsControlCharacter(const char* str) {
    function containsControlCharacter0 (line 3993) | static bool containsControlCharacter0(const char* str, unsigned len) {
    function valueToString (line 4003) | std::string valueToString(LargestInt value) {
    function valueToString (line 4016) | std::string valueToString(LargestUInt value) {
    function valueToString (line 4026) | std::string valueToString(Int value) {
    function valueToString (line 4030) | std::string valueToString(UInt value) {
    function valueToString (line 4036) | std::string valueToString(double value) {
    function valueToString (line 4073) | std::string valueToString(bool value) { return value ? "true" : "false...
    function valueToQuotedString (line 4075) | std::string valueToQuotedString(const char* value) {
    function valueToQuotedStringN (line 4152) | static std::string valueToQuotedStringN(const char* value, unsigned le...
    type CommentStyle (line 4715) | struct CommentStyle {
      type Enum (line 4717) | enum Enum {
    type BuiltStyledStreamWriter (line 4724) | struct BuiltStyledStreamWriter : public StreamWriter
    function StreamWriter (line 5011) | StreamWriter* StreamWriterBuilder::newStreamWriter() const
    function getValidWriterKeys (line 5040) | static void getValidWriterKeys(std::set<std::string>* valid_keys)
    function Value (line 5065) | Value& StreamWriterBuilder::operator[](std::string key)
    function writeString (line 5080) | std::string writeString(StreamWriter::Factory const& builder, Value co...

FILE: src/common/json.h
  function namespace (line 199) | namespace Json {
  function namespace (line 248) | namespace Json {
  function namespace (line 299) | namespace Json {
  function namespace (line 391) | namespace Json {
  function namespace (line 1168) | namespace std {
  function namespace (line 1219) | namespace Json {
  function namespace (line 1631) | namespace Json {

FILE: src/common/logger.cpp
  type Airwave (line 13) | namespace Airwave {
    function loggerInit (line 22) | bool loggerInit(const std::string& socketPath, const std::string& send...
    function loggerFree (line 48) | void loggerFree()
    function LogLevel (line 57) | LogLevel loggerLogLevel()
    function loggerSetLogLevel (line 63) | void loggerSetLogLevel(LogLevel level)
    function loggerSenderId (line 69) | std::string loggerSenderId()
    function loggerSetSenderId (line 75) | void loggerSetSenderId(const std::string& senderId)
    function loggerMessage (line 81) | void loggerMessage(LogLevel level, const char* format, ...)

FILE: src/common/logger.h
  function LogLevel (line 27) | enum class LogLevel {

FILE: src/common/moduleinfo.cpp
  function ModuleInfo (line 27) | ModuleInfo* ModuleInfo::instance()

FILE: src/common/moduleinfo.h
  function class (line 8) | class ModuleInfo {

FILE: src/common/protocol.h
  function Command (line 10) | enum class Command {

FILE: src/common/storage.cpp
  type Airwave (line 9) | namespace Airwave {
    function LogLevel (line 253) | LogLevel Storage::defaultLogLevel() const
    function LogLevel (line 680) | LogLevel Storage::Link::logLevel() const

FILE: src/common/storage.h
  function Prefix (line 26) | Prefix next() const;

FILE: src/common/vst24.h
  function namespace (line 9) | namespace Airwave {

FILE: src/common/vsteventkeeper.cpp
  type Airwave (line 7) | namespace Airwave {
    function VstEvents (line 50) | VstEvents* VstEventKeeper::events()

FILE: src/common/vsteventkeeper.h
  function namespace (line 7) | namespace Airwave {

FILE: src/host/host.cpp
  type Airwave (line 8) | namespace Airwave {
    function DWORD (line 700) | DWORD CALLBACK Host::audioThreadProc(void* param)
    function LRESULT (line 712) | LRESULT CALLBACK Host::windowProc(HWND hwnd, UINT message, WPARAM wPar...

FILE: src/host/host.h
  function namespace (line 15) | namespace Airwave {

FILE: src/host/main.cpp
  function main (line 11) | int __cdecl main(int argc, const char* argv[])

FILE: src/manager/core/application.cpp
  function LogSocket (line 29) | LogSocket* Application::logSocket()
  function Storage (line 35) | Storage* Application::storage() const
  function LinksModel (line 41) | LinksModel* Application::links() const
  function LoadersModel (line 47) | LoadersModel* Application::loaders() const
  function PrefixesModel (line 53) | PrefixesModel* Application::prefixes() const
  function QStringList (line 59) | QStringList Application::checkMissingBinaries(const QString& path) const

FILE: src/manager/core/application.h
  function namespace (line 17) | namespace Airwave {
  function class (line 22) | class Application : public SingleApplication {

FILE: src/manager/core/logsocket.cpp
  function QString (line 26) | QString LogSocket::id() const
  type sockaddr_un (line 42) | struct sockaddr_un

FILE: src/manager/core/logsocket.h
  function class (line 8) | class LogSocket : public QObject {

FILE: src/manager/core/singleapplication.cpp
  function QWidget (line 41) | QWidget* SingleApplication::activationWindow() const

FILE: src/manager/core/singleapplication.h
  function class (line 14) | class SingleApplication : public QApplication {

FILE: src/manager/forms/filedialog.cpp
  function QStringList (line 148) | QStringList FileDialog::nameFilters() const
  function QString (line 166) | QString FileDialog::rootDirectory() const
  function QString (line 185) | QString FileDialog::directory() const
  function QString (line 252) | QString FileDialog::selectedPath() const
  function QString (line 258) | QString FileDialog::selectedName() const
  function QString (line 268) | QString FileDialog::defaultSuffix() const

FILE: src/manager/forms/filedialog.h
  function class (line 18) | class FileDialog : public QDialog {

FILE: src/manager/forms/folderdialog.h
  function class (line 12) | class FolderDialog : public QDialog {

FILE: src/manager/forms/linkdialog.cpp
  function LinkItem (line 27) | LinkItem* LinkDialog::item() const
  function QString (line 316) | QString LinkDialog::currentPrefix() const
  function QString (line 330) | QString LinkDialog::getPluginPath() const

FILE: src/manager/forms/linkdialog.h
  function class (line 13) | class LinkDialog : public QDialog {

FILE: src/manager/forms/loaderdialog.cpp
  function LoaderItem (line 79) | LoaderItem* LoaderDialog::item() const

FILE: src/manager/forms/loaderdialog.h
  function class (line 12) | class LoaderDialog : public QDialog {

FILE: src/manager/forms/mainform.h
  function class (line 14) | class MainForm : public QMainWindow {

FILE: src/manager/forms/prefixdialog.cpp
  function PrefixItem (line 81) | PrefixItem* PrefixDialog::item() const

FILE: src/manager/forms/prefixdialog.h
  function class (line 12) | class PrefixDialog : public QDialog {

FILE: src/manager/forms/settingsdialog.h
  function class (line 18) | class SettingsDialog : public QDialog {

FILE: src/manager/main.cpp
  function main (line 6) | int main(int argc, char** argv)

FILE: src/manager/models/directorymodel.cpp
  function QString (line 21) | QString DirectoryItem::name() const
  function QString (line 27) | QString DirectoryItem::path() const
  function QString (line 33) | QString DirectoryItem::fullPath() const
  function i64 (line 39) | i64 DirectoryItem::size() const
  function QString (line 45) | QString DirectoryItem::humanReadableSize() const
  function QString (line 60) | QString DirectoryItem::type() const
  function QString (line 66) | QString DirectoryItem::getType() const
  function QVariant (line 106) | QVariant DirectoryModel::data(const QModelIndex& index, int role) const
  function QVariant (line 144) | QVariant DirectoryModel::headerData(int section, Qt::Orientation orienta...
  function QString (line 201) | QString DirectoryModel::directory() const
  function QStringList (line 218) | QStringList DirectoryModel::nameFilters() const

FILE: src/manager/models/directorymodel.h
  function class (line 10) | class DirectoryItem : public GenericTreeItem<DirectoryItem> {

FILE: src/manager/models/generictreemodel.h
  function childCount (line 32) | int childCount() const;
  function virtual (line 173) | virtual void detached() { }
  function virtual (line 183) | virtual void reattached() { }
  function virtual (line 194) | virtual void childInserted(Derived* item) { Q_UNUSED(item); }
  function virtual (line 205) | virtual void childRemoved(Derived* item) { Q_UNUSED(item); }

FILE: src/manager/models/linksmodel.cpp
  function QString (line 21) | QString LinkItem::name() const
  function QString (line 46) | QString LinkItem::location() const
  function QString (line 71) | QString LinkItem::prefix() const
  function QString (line 84) | QString LinkItem::loader() const
  function QString (line 97) | QString LinkItem::target() const
  function QString (line 110) | QString LinkItem::path() const
  function LogLevel (line 123) | LogLevel LinkItem::logLevel() const
  function QVariant (line 150) | QVariant LinksModel::data(const QModelIndex& index, int role) const
  function QVariant (line 237) | QVariant LinksModel::headerData(int section, Qt::Orientation orientation,
  function LinkItem (line 264) | LinkItem* LinksModel::createLink(const QString& name, const QString& loc...
  function QString (line 313) | QString LinksModel::logLevelString(LogLevel level) const

FILE: src/manager/models/linksmodel.h
  function QString (line 18) | QString name() const;

FILE: src/manager/models/loadersmodel.cpp
  function QString (line 14) | QString LoaderItem::name() const
  function QString (line 29) | QString LoaderItem::path() const
  function QVariant (line 63) | QVariant LoadersModel::data(const QModelIndex& index, int role) const
  function QVariant (line 82) | QVariant LoadersModel::headerData(int section, Qt::Orientation orientation,
  function LoaderItem (line 100) | LoaderItem* LoadersModel::createLoader(const QString& name, const QStrin...

FILE: src/manager/models/loadersmodel.h
  function QString (line 15) | QString name() const;

FILE: src/manager/models/prefixesmodel.cpp
  function QString (line 14) | QString PrefixItem::name() const
  function QString (line 29) | QString PrefixItem::path() const
  function QVariant (line 63) | QVariant PrefixesModel::data(const QModelIndex& index, int role) const
  function QVariant (line 82) | QVariant PrefixesModel::headerData(int section, Qt::Orientation orientat...
  function PrefixItem (line 100) | PrefixItem* PrefixesModel::createPrefix(const QString& name, const QStri...

FILE: src/manager/models/prefixesmodel.h
  function QString (line 15) | QString name() const;

FILE: src/manager/widgets/directoryview.h
  function class (line 8) | class DirectoryView : public GenericTreeView<DirectoryModel> {

FILE: src/manager/widgets/generictreeview.h
  type QList (line 12) | typedef QList<ItemType> ItemList;
  function isAutoClearSelection (line 22) | bool isAutoClearSelection() const;

FILE: src/manager/widgets/lineedit.cpp
  function QIcon (line 112) | QIcon LineEdit::buttonIcon() const
  function QString (line 118) | QString LineEdit::buttonToolTip() const
  function uint (line 136) | uint LineEdit::editTimeout() const
  function QString (line 277) | QString LineEdit::prefix() const
  function QColor (line 291) | QColor LineEdit::prefixColor() const
  function QString (line 304) | QString LineEdit::suffix() const
  function QColor (line 318) | QColor LineEdit::suffixColor() const

FILE: src/manager/widgets/lineedit.h
  function class (line 11) | class LineEdit: public QLineEdit {

FILE: src/manager/widgets/linksview.h
  function class (line 8) | class LinksView : public GenericTreeView<LinksModel> {

FILE: src/manager/widgets/loadersview.h
  function class (line 8) | class LoadersView : public GenericTreeView<LoadersModel> {

FILE: src/manager/widgets/logview.h
  function class (line 7) | class LogView : public QTextEdit {

FILE: src/manager/widgets/nofocusdelegate.cpp
  function QSize (line 22) | QSize NoFocusDelegate::sizeHint(const QStyleOptionViewItem& option,

FILE: src/manager/widgets/nofocusdelegate.h
  function class (line 7) | class NoFocusDelegate : public QStyledItemDelegate {

FILE: src/manager/widgets/prefixesview.h
  function class (line 8) | class PrefixesView : public GenericTreeView<PrefixesModel> {

FILE: src/manager/widgets/separatorlabel.h
  function class (line 10) | class SeparatorLabel : public QWidget {

FILE: src/plugin/main.cpp
  function signalHandler (line 23) | void signalHandler(int signum)
  function AEffect (line 34) | AEffect* VSTPluginMain(AudioMasterProc audioMasterProc)
  function AEffect (line 158) | AEffect* mainStub(AudioMasterProc audioMasterProc)

FILE: src/plugin/plugin.cpp
  type Airwave (line 14) | namespace Airwave {
    function AEffect (line 155) | AEffect* Plugin::effect()

FILE: src/plugin/plugin.h
  function namespace (line 16) | namespace Airwave {
Condensed preview — 85 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (489K chars).
[
  {
    "path": "CMakeLists.txt",
    "chars": 2097,
    "preview": "cmake_minimum_required(VERSION 2.8.11)\n\nset(PROJECT_NAME airwave)\nproject(${PROJECT_NAME})\n\n# Project version\nset(VERSIO"
  },
  {
    "path": "LICENSE",
    "chars": 1081,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Anton Kalmykov\n\nPermission is hereby granted, free of charge, to any person ob"
  },
  {
    "path": "README",
    "chars": 4203,
    "preview": "About\nAirwave is a wine based VST bridge, that allows for the use of Windows 32- and 64-bit VST 2.4 audio plugins with L"
  },
  {
    "path": "README.md",
    "chars": 7085,
    "preview": "## About\nAirwave is a [wine](https://www.winehq.org/) based VST bridge, that allows for the use of Windows 32- and 64-bi"
  },
  {
    "path": "cmake/FindLibDl.cmake",
    "chars": 851,
    "preview": "# - Find libdl\n# Find the native LIBDL includes and library\n#\n#  LIBDL_INCLUDE_DIR - where to find dlfcn.h, etc.\n#  LIBD"
  },
  {
    "path": "cmake/FindLibMagic.cmake",
    "chars": 2087,
    "preview": "# - Try to find libmagic header and library\n#\n# Usage of this module as follows:\n#\n#     find_package(LibMagic)\n#\n# Vari"
  },
  {
    "path": "config.h.in",
    "chars": 627,
    "preview": "// This file has been generated automatically by CMake. Do not edit it manually, as all\n// changes will be overwritten i"
  },
  {
    "path": "fix-xembed-wine-windows.patch",
    "chars": 1518,
    "preview": "diff -Naurb ./wine-1.7.52/dlls/winex11.drv/event.c ./wine-1.7.52-patched/dlls/winex11.drv/event.c\n--- ./wine-1.7.52/dlls"
  },
  {
    "path": "src/common/dataport.cpp",
    "chars": 2720,
    "preview": "#include \"dataport.h\"\n\n#include <cstring>\n#include <sys/ipc.h>\n#include <sys/shm.h>\n#include <sys/stat.h>\n#include \"comm"
  },
  {
    "path": "src/common/dataport.h",
    "chars": 823,
    "preview": "#ifndef COMMON_DATAPORT_H\n#define COMMON_DATAPORT_H\n\n#include \"common/event.h\"\n#include \"common/types.h\"\n\n\nnamespace Air"
  },
  {
    "path": "src/common/event.cpp",
    "chars": 936,
    "preview": "#include \"event.h\"\n\n#include <errno.h>\n#include <syscall.h>\n#include <time.h>\n#include <unistd.h>\n#include <linux/futex."
  },
  {
    "path": "src/common/event.h",
    "chars": 293,
    "preview": "#ifndef COMMON_EVENT_H\n#define COMMON_EVENT_H\n\n#include <atomic>\n\n#ifdef bool\n#undef bool\n#endif\n\n\nclass Event {\npublic:"
  },
  {
    "path": "src/common/filesystem.cpp",
    "chars": 2188,
    "preview": "#include \"filesystem.h\"\n\n#include <vector>\n#include <pwd.h>\n#include <unistd.h>\n#include <linux/limits.h>\n#include <sys/"
  },
  {
    "path": "src/common/filesystem.h",
    "chars": 561,
    "preview": "#ifndef COMMON_FILESYSTEM_H\n#define COMMON_FILESYSTEM_H\n\n#include <string>\n\n\nnamespace Airwave {\n\n\nclass FileSystem {\npu"
  },
  {
    "path": "src/common/json.cpp",
    "chars": 147458,
    "preview": "/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).\n/// It is intended to be used with #include \"json.h\"\n\n/"
  },
  {
    "path": "src/common/json.h",
    "chars": 65709,
    "preview": "/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).\n/// It is intended to be used with #include \"json.h\"\n\n/"
  },
  {
    "path": "src/common/logger.cpp",
    "chars": 1868,
    "preview": "#include \"logger.h\"\n\n#include <cstdarg>\n#include <cstring>\n#include <ctime>\n#include <unistd.h>\n#include <linux/un.h>\n#i"
  },
  {
    "path": "src/common/logger.h",
    "chars": 1019,
    "preview": "#ifndef COMMON_LOGGER_H\n#define COMMON_LOGGER_H\n\n#include <string>\n\n\n#define FLOOD(format, ...) \\\n\t\tAirwave::loggerMessa"
  },
  {
    "path": "src/common/moduleinfo.cpp",
    "chars": 777,
    "preview": "#include \"moduleinfo.h\"\n\n\nModuleInfo::ModuleInfo() :\n\tisInitialized_(false)\n{\n\tmagic_ = magic_open(MAGIC_NONE);\n\tif(!mag"
  },
  {
    "path": "src/common/moduleinfo.h",
    "chars": 496,
    "preview": "#ifndef COMMON_MODULEINFO_H\n#define COMMON_MODULEINFO_H\n\n#include <string>\n#include <magic.h>\n\n\nclass ModuleInfo {\npubli"
  },
  {
    "path": "src/common/protocol.h",
    "chars": 737,
    "preview": "#ifndef COMMON_PROTOCOL_H\n#define COMMON_PROTOCOL_H\n\n#include \"common/types.h\"\n\n\nnamespace Airwave {\n\n\nenum class Comman"
  },
  {
    "path": "src/common/storage.cpp",
    "chars": 12809,
    "preview": "#include \"storage.h\"\n\n#include <fstream>\n#include \"common/config.h\"\n#include \"common/filesystem.h\"\n#include \"common/json"
  },
  {
    "path": "src/common/storage.h",
    "chars": 3105,
    "preview": "#ifndef COMMON_STORAGE_H\n#define COMMON_STORAGE_H\n\n#include <map>\n#include <string>\n#include \"common/logger.h\"\n#include "
  },
  {
    "path": "src/common/types.h",
    "chars": 1838,
    "preview": "#ifndef COMMON_TYPES_H\n#define COMMON_TYPES_H\n\n#include <cstddef>\n#include <cstdint>\n#include <memory>\n#include <tuple>\n"
  },
  {
    "path": "src/common/vst24.h",
    "chars": 3793,
    "preview": "#ifndef COMMON_VST24_H\n#define COMMON_VST24_H\n\n#include <aeffect.h>\n#include <aeffectx.h>\n#include \"common/types.h\"\n\n\nna"
  },
  {
    "path": "src/common/vsteventkeeper.cpp",
    "chars": 962,
    "preview": "#include \"vsteventkeeper.h\"\n\n#include <algorithm>\n#include <cstdint>\n\n\nnamespace Airwave {\n\n\nVstEventKeeper::VstEventKee"
  },
  {
    "path": "src/common/vsteventkeeper.h",
    "chars": 370,
    "preview": "#ifndef COMMON_VSTEVENTSKEEPER_H\n#define COMMON_VSTEVENTSKEEPER_H\n\n#include <aeffectx.h>\n\n\nnamespace Airwave {\n\n\nclass V"
  },
  {
    "path": "src/host/CMakeLists.txt",
    "chars": 1635,
    "preview": "# Configure base name\nset(TARGET_NAME ${HOST_BASENAME})\n\nproject(${TARGET_NAME})\n\noption(DISABLE_64BIT  \"Disable buildin"
  },
  {
    "path": "src/host/host.cpp",
    "chars": 19230,
    "preview": "#include \"host.h\"\n\n#include <cstring>\n#include \"common/logger.h\"\n#include \"common/protocol.h\"\n\n\nnamespace Airwave {\n\n\nHo"
  },
  {
    "path": "src/host/host.h",
    "chars": 1699,
    "preview": "#ifndef HOST_HOST_H\n#define HOST_HOST_H\n\n#include <atomic>\n#include <string>\n#include <vector>\n#include <wine/windows/wi"
  },
  {
    "path": "src/host/main.cpp",
    "chars": 1388,
    "preview": "#include <cstdlib>\n#include \"host.h\"\n#include \"common/config.h\"\n#include \"common/filesystem.h\"\n#include \"common/logger.h"
  },
  {
    "path": "src/manager/CMakeLists.txt",
    "chars": 1908,
    "preview": "set(TARGET_NAME ${PROJECT_NAME}-manager)\n\nproject(${TARGET_NAME})\n\nfind_package(Qt5Widgets REQUIRED)\nfind_package(Qt5Net"
  },
  {
    "path": "src/manager/airwave-manager.desktop.in",
    "chars": 220,
    "preview": "[Desktop Entry]\nType=Application\nVersion=1.0\nName=Airwave manager\nComment=A tool for managing the Airwave VST bridge\nExe"
  },
  {
    "path": "src/manager/core/application.cpp",
    "chars": 1368,
    "preview": "#include <QDir>\n#include \"application.h\"\n#include \"common/config.h\"\n#include \"common/storage.h\"\n#include \"models/linksmo"
  },
  {
    "path": "src/manager/core/application.h",
    "chars": 829,
    "preview": "#ifndef CORE_APPLICATION_H\n#define CORE_APPLICATION_H\n\n#include \"core/logsocket.h\"\n#include \"core/singleapplication.h\"\n\n"
  },
  {
    "path": "src/manager/core/logsocket.cpp",
    "chars": 2006,
    "preview": "#include \"logsocket.h\"\n\n#include <cerrno>\n#include <cstring>\n#include <unistd.h>\n#include <linux/un.h>\n#include <sys/ioc"
  },
  {
    "path": "src/manager/core/logsocket.h",
    "chars": 497,
    "preview": "#ifndef CORE_LOGSOCKET_H\n#define CORE_LOGSOCKET_H\n\n#include <QSocketNotifier>\n#include <QString>\n\n\nclass LogSocket : pub"
  },
  {
    "path": "src/manager/core/singleapplication.cpp",
    "chars": 2380,
    "preview": "#include \"singleapplication.h\"\n\n#include <QLocalServer>\n#include <QLocalSocket>\n#include <QWidget>\n\n\nSingleApplication::"
  },
  {
    "path": "src/manager/core/singleapplication.h",
    "chars": 1062,
    "preview": "#ifndef CORE_SINGLEAPPLICATION_H\n#define CORE_SINGLEAPPLICATION_H\n\n#include <QApplication>\n\n#ifdef qApp\n#undef qApp\n#def"
  },
  {
    "path": "src/manager/forms/filedialog.cpp",
    "chars": 6974,
    "preview": "#include \"filedialog.h\"\n\n#include <QIcon>\n#include <QComboBox>\n#include <QGridLayout>\n#include <QHeaderView>\n#include <Q"
  },
  {
    "path": "src/manager/forms/filedialog.h",
    "chars": 1824,
    "preview": "#ifndef FORMS_FILEDIALOG_H\n#define FORMS_FILEDIALOG_H\n\n#include <QDialog>\n#include <QDir>\n\n\nclass QFileSystemModel;\nclas"
  },
  {
    "path": "src/manager/forms/folderdialog.cpp",
    "chars": 1178,
    "preview": "#include \"folderdialog.h\"\n\n#include <QDialogButtonBox>\n#include <QGridLayout>\n#include <QLabel>\n#include <QMessageBox>\n#"
  },
  {
    "path": "src/manager/forms/folderdialog.h",
    "chars": 436,
    "preview": "#ifndef FORMS_FOLDERDIALOG_H\n#define FORMS_FOLDERDIALOG_H\n\n#include <QDialog>\n\n\nclass QDialogButtonBox;\nclass DirectoryM"
  },
  {
    "path": "src/manager/forms/linkdialog.cpp",
    "chars": 9006,
    "preview": "#include \"linkdialog.h\"\n\n#include <QComboBox>\n#include <QDialogButtonBox>\n#include <QFile>\n#include <QGridLayout>\n#inclu"
  },
  {
    "path": "src/manager/forms/linkdialog.h",
    "chars": 742,
    "preview": "#ifndef FORMS_LINKEDITDIALOG_H\n#define FORMS_LINKEDITDIALOG_H\n\n#include <QDialog>\n\n\nclass QComboBox;\nclass QDialogButton"
  },
  {
    "path": "src/manager/forms/loaderdialog.cpp",
    "chars": 2852,
    "preview": "#include \"loaderdialog.h\"\n\n#include <QDialogButtonBox>\n#include <QGridLayout>\n#include <QIcon>\n#include <QLabel>\n#includ"
  },
  {
    "path": "src/manager/forms/loaderdialog.h",
    "chars": 517,
    "preview": "#ifndef FORMS_LOADERDIALOG_H\n#define FORMS_LOADERDIALOG_H\n\n#include <QDialog>\n\n\nclass QDialogButtonBox;\nclass LineEdit;\n"
  },
  {
    "path": "src/manager/forms/mainform.cpp",
    "chars": 9700,
    "preview": "#include \"mainform.h\"\n\n#include <QAction>\n#include <QDesktopServices>\n#include <QDir>\n#include <QFileInfo>\n#include <QHB"
  },
  {
    "path": "src/manager/forms/mainform.h",
    "chars": 967,
    "preview": "#ifndef FORMS_MAINFORM_H\n#define FORMS_MAINFORM_H\n\n#include <QMainWindow>\n\n\nclass QAction;\nclass QSplitter;\nclass LinksM"
  },
  {
    "path": "src/manager/forms/prefixdialog.cpp",
    "chars": 2850,
    "preview": "#include \"prefixdialog.h\"\n\n#include <QDialogButtonBox>\n#include <QGridLayout>\n#include <QIcon>\n#include <QLabel>\n#includ"
  },
  {
    "path": "src/manager/forms/prefixdialog.h",
    "chars": 517,
    "preview": "#ifndef FORMS_PREFIXDIALOG_H\n#define FORMS_PREFIXDIALOG_H\n\n#include <QDialog>\n\n\nclass QDialogButtonBox;\nclass LineEdit;\n"
  },
  {
    "path": "src/manager/forms/settingsdialog.cpp",
    "chars": 11590,
    "preview": "#include \"settingsdialog.h\"\n\n#include <QComboBox>\n#include <QDialogButtonBox>\n#include <QGridLayout>\n#include <QHBoxLayo"
  },
  {
    "path": "src/manager/forms/settingsdialog.h",
    "chars": 1087,
    "preview": "#ifndef FORMS_SETTINGSDIALOG_H\n#define FORMS_SETTINGSDIALOG_H\n\n#include <QDialog>\n\n\nclass QComboBox;\nclass QDialogButton"
  },
  {
    "path": "src/manager/main.cpp",
    "chars": 539,
    "preview": "#include \"common/config.h\"\n#include \"core/application.h\"\n#include \"forms/mainform.h\"\n\n\nint main(int argc, char** argv)\n{"
  },
  {
    "path": "src/manager/models/directorymodel.cpp",
    "chars": 5230,
    "preview": "#include \"directorymodel.h\"\n\n#include <QApplication>\n#include <QIcon>\n#include <QStyle>\n\n\nDirectoryItem::DirectoryItem(c"
  },
  {
    "path": "src/manager/models/directorymodel.h",
    "chars": 1750,
    "preview": "#ifndef MODELS_DIRECTORYMODEL_H\n#define MODELS_DIRECTORYMODEL_H\n\n#include <QDir>\n#include <QFileSystemWatcher>\n#include "
  },
  {
    "path": "src/manager/models/generictreemodel.h",
    "chars": 19893,
    "preview": "#ifndef MODELS_GENERICTREEMODEL_H\n#define MODELS_GENERICTREEMODEL_H\n\n#include <QAbstractItemModel>\n\n\ntemplate<typename T"
  },
  {
    "path": "src/manager/models/linksmodel.cpp",
    "chars": 6083,
    "preview": "#include \"linksmodel.h\"\n\n#include <QDir>\n#include <QIcon>\n#include \"core/application.h\"\n\n\nLinkItem::LinkItem(Storage::Li"
  },
  {
    "path": "src/manager/models/linksmodel.h",
    "chars": 1577,
    "preview": "#ifndef MODELS_LINKSMODEL_H\n#define MODELS_LINKSMODEL_H\n\n#include \"common/logger.h\"\n#include \"common/moduleinfo.h\"\n#incl"
  },
  {
    "path": "src/manager/models/loadersmodel.cpp",
    "chars": 2124,
    "preview": "#include \"loadersmodel.h\"\n\n#include <QIcon>\n#include \"core/application.h\"\n#include \"models/linksmodel.h\"\n\n\nLoaderItem::L"
  },
  {
    "path": "src/manager/models/loadersmodel.h",
    "chars": 969,
    "preview": "#ifndef MODELS_LOADERSMODEL_H\n#define MODELS_LOADERSMODEL_H\n\n#include \"generictreemodel.h\"\n#include \"common/storage.h\"\n\n"
  },
  {
    "path": "src/manager/models/prefixesmodel.cpp",
    "chars": 2132,
    "preview": "#include \"prefixesmodel.h\"\n\n#include <QIcon>\n#include \"core/application.h\"\n#include \"models/linksmodel.h\"\n\n\nPrefixItem::"
  },
  {
    "path": "src/manager/models/prefixesmodel.h",
    "chars": 969,
    "preview": "#ifndef MODELS_PREFIXMODEL_H\n#define MODELS_PREFIXMODEL_H\n\n#include \"generictreemodel.h\"\n#include \"common/storage.h\"\n\n\nu"
  },
  {
    "path": "src/manager/resources/resources.qrc",
    "chars": 907,
    "preview": "<RCC>\n    <qresource prefix=\"/\">\n        <file>airwave-manager.png</file>\n        <file>create_link.png</file>\n        <"
  },
  {
    "path": "src/manager/widgets/directoryview.cpp",
    "chars": 1292,
    "preview": "#include \"directoryview.h\"\n\n#include <QHeaderView>\n#include \"nofocusdelegate.h\"\n\n\nDirectoryView::DirectoryView(QWidget* "
  },
  {
    "path": "src/manager/widgets/directoryview.h",
    "chars": 824,
    "preview": "#ifndef WIDGETS_DIRECTORYVIEW_H\n#define WIDGETS_DIRECTORYVIEW_H\n\n#include \"models/directorymodel.h\"\n#include \"widgets/ge"
  },
  {
    "path": "src/manager/widgets/generictreeview.h",
    "chars": 7238,
    "preview": "#ifndef WIDGETS_GENERICTREEVIEW_H\n#define WIDGETS_GENERICTREEVIEW_H\n\n#include <QMouseEvent>\n#include <QTreeView>\n\n\ntempl"
  },
  {
    "path": "src/manager/widgets/lineedit.cpp",
    "chars": 5398,
    "preview": "#include <QApplication>\n#include <QMouseEvent>\n#include <QPainter>\n#include <QStyle>\n#include <QStyleOptionFrameV2>\n#inc"
  },
  {
    "path": "src/manager/widgets/lineedit.h",
    "chars": 1683,
    "preview": "#ifndef WIDGETS_LINEEDIT_H\n#define WIDGETS_LINEEDIT_H\n\n#include <QLineEdit>\n#include <QTimer>\n\n\nclass QToolButton;\n\n\ncla"
  },
  {
    "path": "src/manager/widgets/linksview.cpp",
    "chars": 1361,
    "preview": "#include \"linksview.h\"\n\n#include <QHeaderView>\n#include \"widgets/nofocusdelegate.h\"\n\n\nLinksView::LinksView(QWidget* pare"
  },
  {
    "path": "src/manager/widgets/linksview.h",
    "chars": 783,
    "preview": "#ifndef WIDGETS_LINKSVIEW_H\n#define WIDGETS_LINKSVIEW_H\n\n#include \"models/linksmodel.h\"\n#include \"widgets/generictreevie"
  },
  {
    "path": "src/manager/widgets/loadersview.cpp",
    "chars": 1154,
    "preview": "#include \"loadersview.h\"\n\n#include <QHeaderView>\n#include \"nofocusdelegate.h\"\n\n\nLoadersView::LoadersView(QWidget* parent"
  },
  {
    "path": "src/manager/widgets/loadersview.h",
    "chars": 688,
    "preview": "#ifndef WIDGETS_LOADERSVIEW_H\n#define WIDGETS_LOADERSVIEW_H\n\n#include \"generictreeview.h\"\n#include \"models/loadersmodel."
  },
  {
    "path": "src/manager/widgets/logview.cpp",
    "chars": 1629,
    "preview": "#include <QScrollBar>\n#include <QStringBuilder>\n#include <QTime>\n#include \"logview.h\"\n#include \"common/config.h\"\n\n\nLogVi"
  },
  {
    "path": "src/manager/widgets/logview.h",
    "chars": 485,
    "preview": "#ifndef WIDGETS_LOGVIEW_H\n#define WIDGETS_LOGVIEW_H\n\n#include <QTextEdit>\n\n\nclass LogView : public QTextEdit {\n\tQ_OBJECT"
  },
  {
    "path": "src/manager/widgets/nofocusdelegate.cpp",
    "chars": 754,
    "preview": "#include \"nofocusdelegate.h\"\r\n\r\n\r\nNoFocusDelegate::NoFocusDelegate(QWidget* parent) :\r\n\tQStyledItemDelegate(parent),\r\n\te"
  },
  {
    "path": "src/manager/widgets/nofocusdelegate.h",
    "chars": 556,
    "preview": "#ifndef WIDGETS_NOFOCUSDELEGATE_H\r\n#define WIDGETS_NOFOCUSDELEGATE_H\r\n\r\n#include <QStyledItemDelegate>\r\n\r\n\r\nclass NoFocu"
  },
  {
    "path": "src/manager/widgets/prefixesview.cpp",
    "chars": 1163,
    "preview": "#include \"prefixesview.h\"\n\n#include <QHeaderView>\n#include \"nofocusdelegate.h\"\n\n\nPrefixesView::PrefixesView(QWidget* par"
  },
  {
    "path": "src/manager/widgets/prefixesview.h",
    "chars": 696,
    "preview": "#ifndef WIDGETS_PREFIXESVIEW_H\n#define WIDGETS_PREFIXESVIEW_H\n\n#include \"generictreeview.h\"\n#include \"models/prefixesmod"
  },
  {
    "path": "src/manager/widgets/separatorlabel.cpp",
    "chars": 579,
    "preview": "#include \"separatorlabel.h\"\n\n#include <QFrame>\n#include <QHBoxLayout>\n#include <QLabel>\n\n\nSeparatorLabel::SeparatorLabel"
  },
  {
    "path": "src/manager/widgets/separatorlabel.h",
    "chars": 305,
    "preview": "#ifndef WIDGET_SEPARATORLABEL_H_\n#define WIDGET_SEPARATORLABEL_H_\n\n#include <QWidget>\n\n\nclass QLabel;\n\n\nclass SeparatorL"
  },
  {
    "path": "src/plugin/CMakeLists.txt",
    "chars": 1189,
    "preview": "set(TARGET_NAME ${PLUGIN_BASENAME})\n\nproject(${TARGET_NAME})\n\nfind_package(LibDl REQUIRED)\nfind_package(LibMagic REQUIRE"
  },
  {
    "path": "src/plugin/main.cpp",
    "chars": 4133,
    "preview": "#include <string>\n#include <dlfcn.h>\n#include <signal.h>\n#include \"plugin.h\"\n#include \"common/config.h\"\n#include \"common"
  },
  {
    "path": "src/plugin/plugin.cpp",
    "chars": 21700,
    "preview": "#include \"plugin.h\"\n\n#include <cstring>\n#include <unistd.h>\n#include <sys/wait.h>\n#include \"common/logger.h\"\n#include \"c"
  },
  {
    "path": "src/plugin/plugin.h",
    "chars": 2611,
    "preview": "#ifndef PLUGIN_PLUGIN_H\n#define PLUGIN_PLUGIN_H\n\n#include <atomic>\n#include <mutex>\n#include <string>\n#include <thread>\n"
  }
]

About this extraction

This page contains the full source code of the psycha0s/airwave GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 85 files (440.3 KB), approximately 115.0k tokens, and a symbol index with 231 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!