diff --git a/BSUtils.cmake b/BSUtils.cmake deleted file mode 100644 index 8d94ed69c..000000000 --- a/BSUtils.cmake +++ /dev/null @@ -1,52 +0,0 @@ -# Fix XCode includes to ignore warnings on system includes -function(target_include_directories_system _target) - if(XCODE) - foreach(_arg ${ARGN}) - if("${_arg}" STREQUAL "PRIVATE" OR "${_arg}" STREQUAL "PUBLIC" OR "${_arg}" STREQUAL "INTERFACE") - set(_scope ${_arg}) - else() - target_compile_options(${_target} ${_scope} -isystem${_arg}) - endif() - endforeach() - else() - target_include_directories(${_target} SYSTEM ${_scope} ${ARGN}) - endif() -endfunction() - - -# Install bundles into obs plugin directory -macro(install_obs_plugin_bundle target target-bundle-name) - if(APPLE) - set(_bit_suffix "") - elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) - set(_bit_suffix "64bit/") - else() - set(_bit_suffix "32bit/") - endif() - - set_target_properties(${target} PROPERTIES - PREFIX "") - - install(TARGETS ${target} - BUNDLE DESTINATION "${OBS_PLUGIN_DESTINATION}") - - add_custom_command(TARGET ${target} POST_BUILD - COMMAND "${CMAKE_COMMAND}" -E copy_directory - "$/../../../${target-bundle-name}" - "${OBS_OUTPUT_DIR}/$/obs-plugins/${_bit_suffix}/${target-bundle-name}" - VERBATIM) - - if(DEFINED ENV{obsInstallerTempDir}) - add_custom_command(TARGET ${target} POST_BUILD - COMMAND "${CMAKE_COMMAND}" -E copy_directory - "$/../../../${target-bundle-name}" - "$ENV{obsInstallerTempDir}/${OBS_PLUGIN_DESTINATION}/${target-bundle-name}" - VERBATIM) - endif() - -endmacro() - -macro (set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE) - set_property(TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} - ${XCODE_VALUE}) -endmacro (set_xcode_property) diff --git a/CMakeLists.txt b/CMakeLists.txt index 273bbe3f8..5ace088dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,263 +1,116 @@ -#cmake_minimum_required(VERSION 3.0) cmake_minimum_required(VERSION 2.8.12) -project(cef-isolation) +project(obs-browser) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}") set(CMAKE_INCLUDE_CURRENT_DIR TRUE) include_directories(SYSTEM "${CMAKE_SOURCE_DIR}/UI/obs-frontend-api") +include_directories("${CMAKE_CURRENT_SOURCE_DIR}") +include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps") -include(BSUtils) +find_package(CEF QUIET) -find_package(LibObs REQUIRED) -find_package(CEF REQUIRED) - -if(MSVC) - option(USE_STATIC_CRT "Use static CRT" ON) - - if(USE_STATIC_CRT) - string(REPLACE "/MD" "/MT" - "CMAKE_C_FLAGS" - "${CMAKE_C_FLAGS}") - - string(REPLACE "/MD" "/MT" - "CMAKE_CXX_FLAGS" - "${CMAKE_CXX_FLAGS}") - - string(TOUPPER "${CMAKE_CONFIGURATION_TYPES}" UPPER_CONFIG_TYPES) - foreach(CONFIG_TYPE ${UPPER_CONFIG_TYPES}) - string(REPLACE "/MD" "/MT" - "CMAKE_C_FLAGS_${CONFIG_TYPE}" - "${CMAKE_C_FLAGS_${CONFIG_TYPE}}") - - string(REPLACE "/MD" "/MT" - "CMAKE_CXX_FLAGS_${CONFIG_TYPE}" - "${CMAKE_CXX_FLAGS_${CONFIG_TYPE}}") - endforeach() - endif() -endif() - -if(APPLE) - find_library(COCOA_FRAMEWORK Cocoa) - find_library(APPKIT_FRAMEWORK AppKit) - find_library(IOSURFACE_FRAMEWORK IOSurface) -endif(APPLE) - -if (NOT APPLE) - # This is needed to load the libraries from a - # separate directory - add_library(obs-browser-facade MODULE - obs-browser-facade/main.c) - target_link_libraries(obs-browser-facade - libobs) +if(NOT CEF_FOUND) + message(STATUS "CEF Not found -- obs-browser plugin disabled.") + return() endif() -set(obs-browser_SOURCES - obs-browser/main.cpp - obs-browser/main-source.cpp - shared/browser-source.cpp - shared/base64.cpp - shared/util.cpp) - -set(obs-browser_HEADERS - shared/browser-manager.hpp - shared/browser-source.hpp - shared/browser-listener.hpp - shared/browser-settings.hpp - shared/browser-types.h - shared/base64.hpp - shared/browser-types.h - shared/browser-version.h - shared/util.hpp) - -if (APPLE) - list(APPEND obs-browser_SOURCES - shared-apple/browser-bridges.mm - obs-browser/apple/browser-source-mac.mm - obs-browser/apple/browser-manager-mac.mm - obs-browser/apple/browser-source-listener-mac.mm - obs-browser/apple/cef-isolation-service-manager.mm - obs-browser/apple/cef-isolation-service.mm - obs-browser/apple/client-connection-delegate.mm - obs-browser/apple/graphics-helpers.c) +option(EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED "Enable shared texture support for the browser plugin (Win32)" OFF) +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/browser-config.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/browser-config.h") - list(APPEND obs-browser_HEADERS - shared-apple/cef-logging.h - shared-apple/cef-isolation.h - shared-apple/browser-bridges.h - obs-browser/apple/browser-source-mac.h - obs-browser/apple/browser-manager-mac.h - obs-browser/apple/browser-source-listener-mac.h - obs-browser/apple/cef-isolation-service.h - obs-browser/apple/cef-isolation-service-manager.h - obs-browser/apple/client-connection-delegate.h - obs-browser/apple/graphics-helpers.h - obs-browser/apple/texture-ref.hpp) +include_directories("${CMAKE_CURRENT_BINARY_DIR}") +include_directories("${CEF_ROOT_DIR}") -else (APPLE) - - list(APPEND obs-browser_SOURCES - shared/browser-client.cpp - shared/browser-task.cpp - shared/browser-app.cpp - obs-browser/browser-source-listener-base.cpp - obs-browser/browser-manager-base.cpp - obs-browser/browser-render-handler.cpp - obs-browser/browser-source-base.cpp - obs-browser/browser-load-handler.cpp - obs-browser/browser-obs-bridge-base.cpp - shared/browser-scheme.cpp - fmt/format.cc) - - list(APPEND obs-browser_HEADERS - shared/browser-client.hpp - shared/browser-task.hpp - shared/browser-app.hpp - obs-browser/browser-source-listener-base.hpp - obs-browser/browser-manager-base.hpp - obs-browser/browser-render-handler.hpp - obs-browser/browser-source-base.hpp - obs-browser/browser-load-handler.hpp - obs-browser/browser-obs-bridge-base.hpp - shared/browser-scheme.hpp - fmt/format.h) - -endif(APPLE) +# ---------------------------------------------------------------------------- set(obs-browser_LIBRARIES + libobs obs-frontend-api - ${OBS_JANSSON_IMPORT}) - -if (APPLE) - list(APPEND obs-browser_LIBRARIES - ${IOSURFACE_FRAMEWORK}) -endif(APPLE) - - -add_library(obs-browser MODULE - ${obs-browser_SOURCES} - ${obs-browser_HEADERS}) - - -target_include_directories(obs-browser PRIVATE - "obs-browser" - "shared") - -target_include_directories(obs-browser PUBLIC - ${OBS_JANSSON_INCLUDE_DIRS}) - -if (APPLE) - target_include_directories(obs-browser PUBLIC - "shared-apple") -else (APPLE) - target_include_directories_system(obs-browser PUBLIC ${CEF_ROOT_DIR}) -endif(APPLE) - - -if (APPLE) - set_xcode_property(obs-browser CLANG_CXX_LIBRARY "libc++") -endif(APPLE) - -if (NOT APPLE) - list(APPEND obs-browser_LIBRARIES - ${CEF_LIBRARIES}) - if (WIN32) - list(APPEND obs-browser_LIBRARIES - w32-pthreads) - endif(WIN32) -else(NOT APPLE) - list(APPEND obs-browser_LIBRARIES - ${COCOA_FRAMEWORK} - ${APPKIT_FRAMEWORK} - ${IOSURFACE_FRAMEWORK}) -endif(NOT APPLE) - -target_link_libraries(obs-browser - ${obs-browser_LIBRARIES}) - -if(APPLE) - set(cef-isolation_SOURCES - cef-isolation/main.mm - cef-isolation/cef-isolated-client.mm - cef-isolation/browser-obs-bridge-mac.mm - cef-isolation/browser-handle.mm - cef-isolation/browser-render-handler.mm - cef-isolation/browser-texture-mac.mm - cef-isolation/service-connection-delegate.mm - shared/browser-client.cpp - shared/browser-task.cpp - shared/browser-app.cpp - shared/browser-scheme.cpp - shared/base64.cpp - obs-browser/browser-load-handler.cpp - fmt/format.cc) + ) - set(cef-isolation_HEADERS - shared-apple/cef-logging.h - shared-apple/cef-isolation.h - cef-isolation/cef-isolated-client.h - cef-isolation/browser-handle.h - cef-isolation/browser-render-handler.hpp - cef-isolation/browser-texture-mac.h - cef-isolation/service-connection-delegate.h - cef-isolation/browser-obs-bridge-mac.hpp - shared/browser-texture.hpp - shared/browser-client.hpp - shared/browser-task.hpp - shared/browser-app.hpp - shared/base64.hpp - obs-browser/browser-load-handler.hpp - shared/browser-scheme.hpp - shared/browser-types.h - shared/browser-obs-bridge.hpp - shared-apple/browser-bridges.h) +list(APPEND obs-browser_LIBRARIES + ${CEF_LIBRARIES}) - add_executable(cef-isolation - ${cef-isolation_SOURCES} - ${cef-isolation_HEADERS}) +if(MSVC) + string(REPLACE "/MD" "/MT" + "CMAKE_C_FLAGS" + "${CMAKE_C_FLAGS}") + + string(REPLACE "/MD" "/MT" + "CMAKE_CXX_FLAGS" + "${CMAKE_CXX_FLAGS}") + + string(TOUPPER "${CMAKE_CONFIGURATION_TYPES}" UPPER_CONFIG_TYPES) + foreach(CONFIG_TYPE ${UPPER_CONFIG_TYPES}) + string(REPLACE "/MD" "/MT" + "CMAKE_C_FLAGS_${CONFIG_TYPE}" + "${CMAKE_C_FLAGS_${CONFIG_TYPE}}") + + string(REPLACE "/MD" "/MT" + "CMAKE_CXX_FLAGS_${CONFIG_TYPE}" + "${CMAKE_CXX_FLAGS_${CONFIG_TYPE}}") + endforeach() +endif() - set(MACOSX_DEPLOYMENT_TARGET "10.8") +set(obs-browser_SOURCES + obs-browser-source.cpp + obs-browser-plugin.cpp + browser-scheme.cpp + browser-client.cpp + browser-app.cpp + deps/json11/json11.cpp + deps/base64/base64.cpp + deps/wide-string.cpp + ) +set(obs-browser_HEADERS + obs-browser-source.hpp + browser-scheme.hpp + browser-client.hpp + browser-app.hpp + browser-version.h + deps/json11/json11.hpp + deps/base64/base64.hpp + deps/wide-string.hpp + cef-headers.hpp + ) - if (XCODE) - set_xcode_property(cef-isolation - CLANG_CXX_LIBRARY "libc++") - endif(XCODE) +add_library(obs-browser MODULE + ${obs-browser_SOURCES} + ${obs-browser_HEADERS} + ) - target_include_directories(cef-isolation PRIVATE - "cef-isolation" - "shared" - "shared-apple") - - target_include_directories_system(cef-isolation - PUBLIC - ${CEF_INCLUDE_DIR} - ${OBS_JANSSON_INCLUDE_DIRS}) - - target_link_libraries(cef-isolation - ${CEF_LIBRARIES} - ${OBS_JANSSON_IMPORT} - ${APPKIT_FRAMEWORK} - ${IOSURFACE_FRAMEWORK}) +target_link_libraries(obs-browser + ${obs-browser_LIBRARIES} + ) -endif(APPLE) +# ---------------------------------------------------------------------------- set(cef-bootstrap_SOURCES - cef-bootstrap/main.cpp - shared/browser-app.cpp - fmt/format.cc) - + cef-bootstrap/cef-bootstrap-main.cpp + browser-app.cpp + deps/json11/json11.cpp + ) set(cef-bootstrap_HEADERS - shared/browser-app.hpp - fmt/format.h) + cef-bootstrap/cef-bootstrap-main.cpp + browser-app.hpp + deps/json11/json11.hpp + cef-headers.hpp + ) -add_executable(cef-bootstrap - ${cef-bootstrap_SOURCES} - ${cef-bootstrap_HEADERS}) +add_executable(cef-bootstrap + ${cef-bootstrap_SOURCES} + ${cef-bootstrap_HEADERS} + ) +target_link_libraries(cef-bootstrap + ${CEF_LIBRARIES} + ) if (APPLE) - set_target_properties(cef-bootstrap PROPERTIES - COMPILE_FLAGS "-mmacosx-version-min=10.8") + set_target_properties(cef-bootstrap PROPERTIES + COMPILE_FLAGS "-mmacosx-version-min=10.8") endif(APPLE) if (WIN32) @@ -268,68 +121,9 @@ if (APPLE AND XCODE) set_xcode_property(cef-bootstrap CLANG_CXX_LIBRARY "libc++") endif(APPLE AND XCODE) -target_include_directories(cef-bootstrap PRIVATE "shared") -target_include_directories_system(cef-bootstrap - PUBLIC - ${CEF_ROOT_DIR} - ${OBS_JANSSON_INCLUDE_DIRS}) - -target_link_libraries(cef-bootstrap - ${CEF_LIBRARIES} - ${OBS_JANSSON_IMPORT}) - -if (APPLE) - - set_target_properties(cef-isolation PROPERTIES - OUTPUT_NAME "CEF" - MACOSX_BUNDLE TRUE - BUILD_WITH_INSTALL_RPATH TRUE - INSTALL_RPATH "@executable_path/.." - MACOSX_BUNDLE_BUNDLE_NAME "CEF Helper" - MACOSX_BUNDLE_GUI_IDENTIFIER "org.catchexception.cef.cef-isolation") - - set_target_properties(cef-bootstrap PROPERTIES - OUTPUT_NAME "CEF Helper" - MACOSX_BUNDLE TRUE - BUILD_WITH_INSTALL_RPATH TRUE - INSTALL_RPATH "@executable_path/../../../.." - MACOSX_BUNDLE_BUNDLE_NAME "CEF Helper" - MACOSX_BUNDLE_GUI_IDENTIFIER "org.catchexception.cef.cef-bootstrap") - - - add_custom_command(TARGET obs-browser POST_BUILD - COMMAND install_name_tool -change "@executable_path/Chromium Embedded Framework" "@rpath/CEF.app/Contents/Frameworks/Chromium Embedded Framework.framework/Chromium Embedded Framework" "$" - ) - - add_custom_command(TARGET cef-isolation - # Disable taskbar visibility - COMMAND defaults write "$/../Info.plist" "LSUIElement" 1 - ) - - add_custom_command(TARGET cef-bootstrap POST_BUILD - # Remember if you change this but don't cause a recompile it will not rename it successfully - COMMAND install_name_tool -change "@executable_path/Chromium Embedded Framework" "@rpath/Chromium Embedded Framework.framework/Chromium Embedded Framework" "$" - - # Disable taskbar visibility - COMMAND defaults write "$/../Info.plist" "LSUIElement" 1 - ) - - add_custom_command(TARGET cef-isolation POST_BUILD - # Remember if you change this but don't cause a recompile in the shared object it will not rename it successfully - COMMAND install_name_tool -change "@executable_path/Chromium Embedded Framework" "@rpath/Chromium Embedded Framework.framework/Chromium Embedded Framework" "$" +# ---------------------------------------------------------------------------- - # Make a Frameworks directory - COMMAND mkdir -p "$/../Frameworks" - - # Copy the CEF and support frameworks - COMMAND cp -Rf "${CEF_ROOT_DIR}/Release/Chromium Embedded Framework.framework" "$/../Frameworks/" - - # Setup the helper apps - COMMAND rm -rf "$/../Frameworks/CEF Helper.app" - COMMAND cp -Rf "$/../../../CEF Helper.app" "$/../Frameworks" - ) - -else(APPLE) +if (WIN32) math(EXPR BITS "8*${CMAKE_SIZEOF_VOID_P}") add_custom_command(TARGET obs-browser POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory @@ -356,13 +150,11 @@ else(APPLE) COMMAND ${CMAKE_COMMAND} -E copy "${CEF_ROOT_DIR}/Release/snapshot_blob.bin" "${CMAKE_BINARY_DIR}/rundir/$/obs-plugins/${BITS}bit/" + COMMAND ${CMAKE_COMMAND} -E copy + "${CEF_ROOT_DIR}/Release/v8_context_snapshot.bin" + "${CMAKE_BINARY_DIR}/rundir/$/obs-plugins/${BITS}bit/" ) -endif(APPLE) +endif() -if(APPLE) - install_obs_plugin_with_data(obs-browser data) - install_obs_plugin_bundle(cef-isolation "CEF.app") -else(APPLE) - install_obs_plugin_with_data(obs-browser data) - install_obs_plugin(cef-bootstrap) -endif(APPLE) +install_obs_plugin_with_data(obs-browser data) +install_obs_plugin(cef-bootstrap) diff --git a/FindCEF.cmake b/FindCEF.cmake index 2fd7b97c3..2c8c3cfd7 100644 --- a/FindCEF.cmake +++ b/FindCEF.cmake @@ -2,7 +2,7 @@ include(FindPackageHandleStandardArgs) SET(CEF_ROOT_DIR "" CACHE PATH "Path to a CEF distributed build") -message("Looking for Chromium Embedded Framework in ${CEF_ROOT_DIR}") +message(STATUS "Looking for Chromium Embedded Framework in ${CEF_ROOT_DIR}") find_path(CEF_INCLUDE_DIR "include/cef_version.h" HINTS ${CEF_ROOT_DIR}) @@ -24,13 +24,17 @@ find_library(CEFWRAPPER_LIBRARY_DEBUG NAMES cef_dll_wrapper libcef_dll_wrapper PATHS ${CEF_ROOT_DIR}/build/libcef_dll/Debug ${CEF_ROOT_DIR}/build/libcef_dll_wrapper/Debug) -if (NOT CEF_LIBRARY) - message(FATAL_ERROR "Could not find the CEF shared library" ) -endif (NOT CEF_LIBRARY) +if(NOT CEF_LIBRARY) + message(WARNING "Could not find the CEF shared library" ) + set(CEF_FOUND FALSE) + return() +endif() -if (NOT CEFWRAPPER_LIBRARY) - message(FATAL_ERROR "Could not find the CEF wrapper library" ) -endif (NOT CEFWRAPPER_LIBRARY) +if(NOT CEFWRAPPER_LIBRARY) + message(WARNING "Could not find the CEF wrapper library" ) + set(CEF_FOUND FALSE) + return() +endif() set(CEF_LIBRARIES optimized ${CEFWRAPPER_LIBRARY} @@ -42,8 +46,7 @@ if (CEF_LIBRARY_DEBUG AND CEFWRAPPER_LIBRARY_DEBUG) debug ${CEF_LIBRARY_DEBUG}) endif() -find_package_handle_standard_args(CEF DEFAULT_MSG CEF_LIBRARY +find_package_handle_standard_args(CEF DEFAULT_MSG CEF_LIBRARY CEFWRAPPER_LIBRARY CEF_INCLUDE_DIR) - -mark_as_advanced(CEF_LIBRARY CEF_WRAPPER_LIBRARY CEF_LIBRARIES +mark_as_advanced(CEF_LIBRARY CEF_WRAPPER_LIBRARY CEF_LIBRARIES CEF_INCLUDE_DIR) diff --git a/shared/browser-app.cpp b/browser-app.cpp similarity index 53% rename from shared/browser-app.cpp rename to browser-app.cpp index 0e5bce9ec..2d140341d 100644 --- a/shared/browser-app.cpp +++ b/browser-app.cpp @@ -1,5 +1,6 @@ /****************************************************************************** Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -16,20 +17,10 @@ ******************************************************************************/ #include "browser-app.hpp" - -#include -#include -#include -#include - -#include "fmt/format.h" -#include "include/cef_browser.h" -#include "include/cef_command_line.h" -#include "include/wrapper/cef_helpers.h" #include "browser-version.h" +#include -BrowserApp::BrowserApp(){ -} +using namespace json11; CefRefPtr BrowserApp::GetRenderProcessHandler() { @@ -40,65 +31,73 @@ void BrowserApp::OnRegisterCustomSchemes( CefRawPtr registrar) { #if CHROME_VERSION_BUILD >= 3029 - registrar->AddCustomScheme("http", true, false, false, false, true, false); + registrar->AddCustomScheme("http", true, false, false, false, true, + false); #else registrar->AddCustomScheme("http", true, false, false, false, true); #endif } void BrowserApp::OnBeforeCommandLineProcessing( - const CefString& process_type, - CefRefPtr command_line) + const CefString &, + CefRefPtr command_line) { - bool enableGPU = command_line->HasSwitch("enable-gpu"); + if (!shared_texture_available) { + bool enableGPU = command_line->HasSwitch("enable-gpu"); + CefString type = command_line->GetSwitchValue("type"); - CefString type = command_line->GetSwitchValue("type"); + if (!enableGPU && type.empty()) { + command_line->AppendSwitch("disable-gpu"); + command_line->AppendSwitch("disable-gpu-compositing"); + } - if (!enableGPU && type.empty()) - { - command_line->AppendSwitch("disable-gpu"); - command_line->AppendSwitch("disable-gpu-compositing"); } - command_line->AppendSwitch("enable-begin-frame-scheduling"); + command_line->AppendSwitch("enable-begin-frame-scheduling"); command_line->AppendSwitch("enable-system-flash"); } -void BrowserApp::OnContextCreated(CefRefPtr browser, - CefRefPtr frame, +void BrowserApp::OnContextCreated(CefRefPtr, + CefRefPtr, CefRefPtr context) { CefRefPtr globalObj = context->GetGlobal(); CefRefPtr obsStudioObj = CefV8Value::CreateObject(0, 0); - globalObj->SetValue("obsstudio", obsStudioObj, V8_PROPERTY_ATTRIBUTE_NONE); - - CefRefPtr pluginVersion = CefV8Value::CreateString(OBS_BROWSER_VERSION); - obsStudioObj->SetValue("pluginVersion", pluginVersion, V8_PROPERTY_ATTRIBUTE_NONE); - - CefRefPtr func = CefV8Value::CreateFunction("getCurrentScene", this); - obsStudioObj->SetValue("getCurrentScene", func, V8_PROPERTY_ATTRIBUTE_NONE); - - CefRefPtr getStatus = CefV8Value::CreateFunction("getStatus", this); - obsStudioObj->SetValue("getStatus", getStatus, V8_PROPERTY_ATTRIBUTE_NONE); + globalObj->SetValue("obsstudio", + obsStudioObj, V8_PROPERTY_ATTRIBUTE_NONE); + + CefRefPtr pluginVersion = + CefV8Value::CreateString(OBS_BROWSER_VERSION_STRING); + obsStudioObj->SetValue("pluginVersion", + pluginVersion, V8_PROPERTY_ATTRIBUTE_NONE); + + CefRefPtr func = + CefV8Value::CreateFunction("getCurrentScene", this); + obsStudioObj->SetValue("getCurrentScene", + func, V8_PROPERTY_ATTRIBUTE_NONE); + + CefRefPtr getStatus = + CefV8Value::CreateFunction("getStatus", this); + obsStudioObj->SetValue("getStatus", + getStatus, V8_PROPERTY_ATTRIBUTE_NONE); } void BrowserApp::ExecuteJSFunction(CefRefPtr browser, const char *functionName, CefV8ValueList arguments) { - CefRefPtr context = browser->GetMainFrame()->GetV8Context(); + CefRefPtr context = + browser->GetMainFrame()->GetV8Context(); context->Enter(); - - CefRefPtr globalObj = context->GetGlobal(); + CefRefPtr globalObj = context->GetGlobal(); CefRefPtr obsStudioObj = globalObj->GetValue("obsstudio"); - CefRefPtr jsFunction = obsStudioObj->GetValue(functionName); - if (jsFunction && jsFunction->IsFunction()) { + + if (jsFunction && jsFunction->IsFunction()) jsFunction->ExecuteFunction(NULL, arguments); - } context->Exit(); } @@ -116,135 +115,128 @@ bool BrowserApp::OnProcessMessageReceived(CefRefPtr browser, arguments.push_back(CefV8Value::CreateBool(args->GetBool(0))); ExecuteJSFunction(browser, "onVisibilityChange", arguments); - return true; - } - else if (message->GetName() == "Active") { + + } else if (message->GetName() == "Active") { CefV8ValueList arguments; arguments.push_back(CefV8Value::CreateBool(args->GetBool(0))); ExecuteJSFunction(browser, "onActiveChange", arguments); - return true; - } - else if (message->GetName() == "DispatchJSEvent") { - CefRefPtr context = browser->GetMainFrame()->GetV8Context(); + + } else if (message->GetName() == "DispatchJSEvent") { + CefRefPtr context = + browser->GetMainFrame()->GetV8Context(); context->Enter(); CefRefPtr globalObj = context->GetGlobal(); - // Build up a new json object to store the CustomEvent data in. - json_t *json = json_object(); - - if (args->GetSize() > 1) { - json_error_t error; - - json_object_set_new(json, "detail", json_loads(args->GetString(1).ToString().c_str(), 0, &error)); - } + Json::object json; + if (args->GetSize() > 1) + json["detail"] = args->GetString(1).ToString(); + std::string jsonString = Json(json).dump(); + std::string script; - char *jsonString = json_dumps(json, 0); - - std::string script = fmt::format( - "new CustomEvent('{}', {});", - args->GetString(0).ToString(), - jsonString); - - free(jsonString); + script += "new CustomEvent('"; + script += args->GetString(0).ToString(); + script += "', "; + script += jsonString; + script += ");"; CefRefPtr returnValue; CefRefPtr exception; - // Create the CustomEvent object - // We have to use eval to invoke the new operator - context->Eval(script, browser->GetMainFrame()->GetURL(), 0, returnValue, exception); + /* Create the CustomEvent object + * We have to use eval to invoke the new operator */ + context->Eval(script, browser->GetMainFrame()->GetURL(), + 0, returnValue, exception); CefV8ValueList arguments; arguments.push_back(returnValue); - CefRefPtr dispatchEvent = globalObj->GetValue("dispatchEvent"); + CefRefPtr dispatchEvent = + globalObj->GetValue("dispatchEvent"); dispatchEvent->ExecuteFunction(NULL, arguments); context->Exit(); - return true; - } - else if (message->GetName() == "executeCallback") - { - CefRefPtr context = browser->GetMainFrame()->GetV8Context(); + } else if (message->GetName() == "executeCallback") { + CefRefPtr context = + browser->GetMainFrame()->GetV8Context(); CefRefPtr retval; CefRefPtr exception; - + context->Enter(); CefRefPtr arguments = message->GetArgumentList(); int callbackID = arguments->GetInt(0); CefString jsonString = arguments->GetString(1); - std::string script = fmt::format( - "JSON.parse('{}');", - arguments->GetString(1).ToString(), - jsonString.ToString().c_str()); + std::string script; + script += "JSON.parse('"; + script += arguments->GetString(1).ToString(); + script += "');"; CefRefPtr callback = callbackMap[callbackID]; CefV8ValueList args; - context->Eval(script, browser->GetMainFrame()->GetURL(), 0, retval, exception); + context->Eval(script, browser->GetMainFrame()->GetURL(), + 0, retval, exception); args.push_back(retval); callback->ExecuteFunction(NULL, args); - + context->Exit(); callbackMap.erase(callbackID); - - return true; + } else { + return false; } - return false; + return true; } -// CefV8Handler::Execute -bool BrowserApp::Execute(const CefString& name, - CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - CefString& exception) +bool BrowserApp::Execute(const CefString &name, + CefRefPtr, + const CefV8ValueList &arguments, + CefRefPtr &, + CefString &) { - if (name == "getCurrentScene") - { + if (name == "getCurrentScene") { if (arguments.size() == 1 && arguments[0]->IsFunction()) { callbackId++; callbackMap[callbackId] = arguments[0]; } - CefRefPtr msg = CefProcessMessage::Create("getCurrentScene"); + CefRefPtr msg = + CefProcessMessage::Create("getCurrentScene"); CefRefPtr args = msg->GetArgumentList(); args->SetInt(0, callbackId); - CefRefPtr browser = - CefV8Context::GetCurrentContext()->GetBrowser(); + CefRefPtr browser = + CefV8Context::GetCurrentContext()->GetBrowser(); browser->SendProcessMessage(PID_BROWSER, msg); - return true; - } - else if (name == "getStatus") - { + } else if (name == "getStatus") { if (arguments.size() == 1 && arguments[0]->IsFunction()) { callbackId++; callbackMap[callbackId] = arguments[0]; } - CefRefPtr msg = CefProcessMessage::Create("getStatus"); + CefRefPtr msg = + CefProcessMessage::Create("getStatus"); CefRefPtr args = msg->GetArgumentList(); args->SetInt(0, callbackId); - CefRefPtr browser = CefV8Context::GetCurrentContext()->GetBrowser(); + CefRefPtr browser = + CefV8Context::GetCurrentContext()->GetBrowser(); browser->SendProcessMessage(PID_BROWSER, msg); - return true; + } else { + /* Function does not exist. */ + return false; } - // Function does not exist. - return false; + return true; } diff --git a/shared/browser-app.hpp b/browser-app.hpp similarity index 57% rename from shared/browser-app.hpp rename to browser-app.hpp index cbe0c208a..fd2252630 100644 --- a/shared/browser-app.hpp +++ b/browser-app.hpp @@ -1,5 +1,6 @@ /****************************************************************************** Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -17,49 +18,47 @@ #pragma once -#include "include/cef_app.h" -#include +#include +#include "cef-headers.hpp" class BrowserApp : public CefApp, - public CefRenderProcessHandler, - public CefV8Handler -{ + public CefRenderProcessHandler, + public CefV8Handler { -public: - BrowserApp(); + void ExecuteJSFunction(CefRefPtr browser, + const char *functionName, + CefV8ValueList arguments); + + typedef std::map> CallbackMap; + + bool shared_texture_available; + CallbackMap callbackMap; + int callbackId; public: - virtual CefRefPtr GetRenderProcessHandler() OVERRIDE; + inline BrowserApp(bool shared_texture_available_ = false) + : shared_texture_available(shared_texture_available_) + { + } + + virtual CefRefPtr GetRenderProcessHandler() override; virtual void OnRegisterCustomSchemes( - CefRawPtr registrar) OVERRIDE; + CefRawPtr registrar) override; virtual void OnBeforeCommandLineProcessing( - const CefString& process_type, - CefRefPtr command_line) OVERRIDE; - + const CefString &process_type, + CefRefPtr command_line) override; virtual void OnContextCreated(CefRefPtr browser, - CefRefPtr frame, - CefRefPtr context) OVERRIDE; - + CefRefPtr frame, + CefRefPtr context) override; virtual bool OnProcessMessageReceived( - CefRefPtr browser, - CefProcessId source_process, - CefRefPtr message) OVERRIDE; - -public: /* CefV8Handler */ - virtual bool Execute(const CefString& name, + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override; + virtual bool Execute(const CefString &name, CefRefPtr object, - const CefV8ValueList& arguments, - CefRefPtr& retval, - CefString& exception) OVERRIDE; - -private: - virtual void ExecuteJSFunction(CefRefPtr browser, - const char *functionName, - CefV8ValueList arguments); - - typedef std::map> CallbackMap; - int callbackId; - CallbackMap callbackMap; + const CefV8ValueList &arguments, + CefRefPtr &retval, + CefString &exception) override; IMPLEMENT_REFCOUNTING(BrowserApp); }; diff --git a/browser-client.cpp b/browser-client.cpp new file mode 100644 index 000000000..5521f4465 --- /dev/null +++ b/browser-client.cpp @@ -0,0 +1,253 @@ +/****************************************************************************** + Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + ******************************************************************************/ + +#include "browser-client.hpp" +#include "obs-browser-source.hpp" +#include "base64/base64.hpp" +#include "json11/json11.hpp" +#include + +using namespace json11; + +BrowserClient::~BrowserClient() +{ +#if EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED + obs_enter_graphics(); + gs_texture_destroy(texture); + obs_leave_graphics(); +#endif +} + +CefRefPtr BrowserClient::GetLoadHandler() +{ + return this; +} + +CefRefPtr BrowserClient::GetRenderHandler() +{ + return this; +} + +CefRefPtr BrowserClient::GetDisplayHandler() +{ + return this; +} + +CefRefPtr BrowserClient::GetLifeSpanHandler() +{ + return this; +} + +CefRefPtr BrowserClient::GetContextMenuHandler() +{ + return this; +} + +bool BrowserClient::OnBeforePopup( + CefRefPtr, + CefRefPtr, + const CefString &, + const CefString &, + WindowOpenDisposition, + bool, + const CefPopupFeatures &, + CefWindowInfo &, + CefRefPtr &, + CefBrowserSettings&, + bool *) +{ + /* block popups */ + return true; +} + +void BrowserClient::OnBeforeContextMenu( + CefRefPtr, + CefRefPtr, + CefRefPtr, + CefRefPtr model) +{ + /* remove all context menu contributions */ + model->Clear(); +} + +bool BrowserClient::OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId, + CefRefPtr message) +{ + const std::string &name = message->GetName(); + Json json; + + if (name == "getCurrentScene") { + json = Json::object { + {"name", obs_source_get_name(bs->source)}, + {"width", (int)obs_source_get_width(bs->source)}, + {"height", (int)obs_source_get_height(bs->source)} + }; + + } else if (name == "getStatus") { + json = Json::object { + {"recording", obs_frontend_recording_active()}, + {"streaming", obs_frontend_streaming_active()}, + {"replaybuffer", obs_frontend_replay_buffer_active()} + }; + + } else { + return false; + } + + CefRefPtr msg = + CefProcessMessage::Create("executeCallback"); + + CefRefPtr args = msg->GetArgumentList(); + args->SetInt(0, message->GetArgumentList()->GetInt(0)); + args->SetString(1, json.dump()); + + browser->SendProcessMessage(PID_RENDERER, msg); + + return true; +} + +bool BrowserClient::GetViewRect( + CefRefPtr, + CefRect &rect) +{ + rect.Set(0, 0, bs->width, bs->height); + return true; +} + +void BrowserClient::OnPaint( + CefRefPtr, + PaintElementType type, + const RectList &, + const void *buffer, + int width, + int height) +{ + if (type != PET_VIEW) { + return; + } + +#if EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED + if (sharing_available) { + return; + } +#endif + + if (bs->width != width || bs->height != height) { + obs_enter_graphics(); + bs->DestroyTextures(); + obs_leave_graphics(); + } + + if (!bs->texture && width && height) { + obs_enter_graphics(); + bs->texture = gs_texture_create( + width, height, GS_RGBA, 1, + (const uint8_t **)&buffer, + GS_DYNAMIC); + bs->width = width; + bs->height = height; + obs_leave_graphics(); + } else { + obs_enter_graphics(); + gs_texture_set_image(bs->texture, + (const uint8_t *)buffer, + width * 4, false); + obs_leave_graphics(); + } +} + +#if EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED +void BrowserClient::OnAcceleratedPaint( + CefRefPtr, + PaintElementType type, + const RectList &, + void *shared_handle, + uint64) +{ + if (shared_handle != last_handle) { + obs_enter_graphics(); + gs_texture_destroy(texture); + gs_texture_destroy(bs->texture); + bs->texture = nullptr; + texture = nullptr; + + texture = gs_texture_open_shared( + (uint32_t)(uintptr_t)shared_handle); + + uint32_t cx = gs_texture_get_width(texture); + uint32_t cy = gs_texture_get_height(texture); + gs_color_format format = gs_texture_get_color_format(texture); + + bs->texture = gs_texture_create(cx, cy, format, 1, nullptr, 0); + obs_leave_graphics(); + + last_handle = shared_handle; + } + + if (texture && bs->texture) { + obs_enter_graphics(); + gs_copy_texture(bs->texture, texture); + obs_leave_graphics(); + } +} +#endif + +void BrowserClient::OnLoadEnd( + CefRefPtr, + CefRefPtr frame, + int) +{ + if (frame->IsMain()) { + std::string base64EncodedCSS = base64_encode(bs->css); + + std::string href; + href += "data:text/css;charset=utf-8;base64,"; + href += base64EncodedCSS; + + std::string script; + script += "var link = document.createElement('link');"; + script += "link.setAttribute('rel', 'stylesheet');"; + script += "link.setAttribute('type', 'text/css');"; + script += "link.setAttribute('href', '" + href + "');"; + script += "document.getElementsByTagName('head')[0].appendChild(link);"; + + frame->ExecuteJavaScript(script, href, 0); + } +} + +bool BrowserClient::OnConsoleMessage(CefRefPtr, +#if CHROME_VERSION_BUILD >= 3282 + cef_log_severity_t level, +#endif + const CefString &message, + const CefString &source, + int line) +{ +#if CHROME_VERSION_BUILD >= 3282 + if (level < LOGSEVERITY_ERROR) + return false; +#endif + + blog(LOG_INFO, "obs-browser: %s (source: %s:%d)", + message.ToString().c_str(), + source.ToString().c_str(), + line); + return false; +} diff --git a/browser-client.hpp b/browser-client.hpp new file mode 100644 index 000000000..176044821 --- /dev/null +++ b/browser-client.hpp @@ -0,0 +1,123 @@ +/****************************************************************************** + Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + ******************************************************************************/ + +#pragma once + +#include +#include "cef-headers.hpp" +#include "browser-config.h" + +struct BrowserSource; + +class BrowserClient : public CefClient, + public CefDisplayHandler, + public CefLifeSpanHandler, + public CefContextMenuHandler, + public CefRenderHandler, + public CefLoadHandler { + +#if EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED + gs_texture_t *texture = nullptr; + void *last_handle = INVALID_HANDLE_VALUE; +#endif + bool sharing_available = false; + +public: + BrowserSource *bs; + CefRect popupRect; + CefRect originalPopupRect; + + inline BrowserClient(BrowserSource *bs_, bool sharing_avail) + : bs(bs_) + { + sharing_available = sharing_avail; + } + + virtual ~BrowserClient(); + + /* CefClient */ + virtual CefRefPtr GetLoadHandler() override; + virtual CefRefPtr GetRenderHandler() override; + virtual CefRefPtr GetDisplayHandler() override; + virtual CefRefPtr GetLifeSpanHandler() override; + virtual CefRefPtr GetContextMenuHandler() + override; + + virtual bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override; + + /* CefDisplayHandler */ + virtual bool OnConsoleMessage(CefRefPtr browser, +#if CHROME_VERSION_BUILD >= 3282 + cef_log_severity_t level, +#endif + const CefString &message, + const CefString &source, + int line) override; + + /* CefLifeSpanHandler */ + virtual bool OnBeforePopup( + CefRefPtr browser, + CefRefPtr frame, + const CefString &target_url, + const CefString &target_frame_name, + WindowOpenDisposition target_disposition, + bool user_gesture, + const CefPopupFeatures &popupFeatures, + CefWindowInfo &windowInfo, + CefRefPtr &client, + CefBrowserSettings &settings, + bool *no_javascript_access) override; + + /* CefContextMenuHandler */ + virtual void OnBeforeContextMenu( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr params, + CefRefPtr model) override; + + /* CefRenderHandler */ + virtual bool GetViewRect( + CefRefPtr browser, + CefRect &rect) override; + virtual void OnPaint( + CefRefPtr browser, + PaintElementType type, + const RectList &dirtyRects, + const void *buffer, + int width, + int height) override; +#if EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED + virtual void OnAcceleratedPaint( + CefRefPtr browser, + PaintElementType type, + const RectList &dirtyRects, + void *shared_handle, + uint64 sync_key) override; +#endif + + /* CefLoadHandler */ + virtual void OnLoadEnd( + CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override; + + IMPLEMENT_REFCOUNTING(BrowserClient); +}; diff --git a/browser-config.h.in b/browser-config.h.in new file mode 100644 index 000000000..ef4e7ed59 --- /dev/null +++ b/browser-config.h.in @@ -0,0 +1,24 @@ +#pragma once + +#ifndef ON +#define ON true +#endif + +#ifndef OFF +#define OFF false +#endif + +#ifndef TRUE +#define TRUE true +#endif + +#ifndef FALSE +#define FALSE false +#endif + +#ifdef _WIN32 +#define EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED \ + @EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED@ +#else +#define EXPERIMENTAL_SHARED_TEXTURE_SUPPORT_ENABLED false +#endif diff --git a/browser-scheme.cpp b/browser-scheme.cpp new file mode 100644 index 000000000..eeb565404 --- /dev/null +++ b/browser-scheme.cpp @@ -0,0 +1,130 @@ +/****************************************************************************** + Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + ******************************************************************************/ + +#include "browser-scheme.hpp" +#include "wide-string.hpp" + +/* ------------------------------------------------------------------------- */ + +CefRefPtr BrowserSchemeHandlerFactory::Create( + CefRefPtr browser, + CefRefPtr, + const CefString &, + CefRefPtr request) +{ + if (!browser || !request) + return nullptr; + + return CefRefPtr(new BrowserSchemeHandler()); +} + +/* ------------------------------------------------------------------------- */ + +bool BrowserSchemeHandler::ProcessRequest( + CefRefPtr request, + CefRefPtr callback) +{ + CefURLParts parts; + CefParseURL(request->GetURL(), parts); + + std::string path = CefString(&parts.path); + + path = CefURIDecode(path, true, cef_uri_unescape_rule_t::UU_SPACES); + path = CefURIDecode(path, true, cef_uri_unescape_rule_t::UU_URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS); + +#ifdef WIN32 + inputStream.open(to_wide(path.erase(0,1)), std::ifstream::binary); +#else + inputStream.open(path, std::ifstream::binary); +#endif + + /* Set fileName for use in GetResponseHeaders */ + fileName = path; + + if (!inputStream.is_open()) { + callback->Cancel(); + return false; + } + + inputStream.seekg(0, std::ifstream::end); + length = remaining = inputStream.tellg(); + inputStream.seekg(0, std::ifstream::beg); + callback->Continue(); + return true; +} + +void BrowserSchemeHandler::GetResponseHeaders( + CefRefPtr response, + int64 &response_length, + CefString &redirectUrl) +{ + if (!response) { + response_length = -1; + redirectUrl = ""; + return; + } + + std::string fileExtension = + fileName.substr(fileName.find_last_of(".") + 1); + + for (char &ch : fileExtension) + ch = (char)tolower(ch); + if (fileExtension.compare("woff2") == 0) + fileExtension = "woff"; + + response->SetStatus(200); + response->SetMimeType(CefGetMimeType(fileExtension)); + response->SetStatusText("OK"); + response_length = length; + redirectUrl = ""; +} + +bool BrowserSchemeHandler::ReadResponse( + void *data_out, + int bytes_to_read, + int &bytes_read, + CefRefPtr) +{ + if (!data_out || !inputStream.is_open()) { + bytes_read = 0; + inputStream.close(); + return false; + } + + if (isComplete) { + bytes_read = 0; + return false; + } + + inputStream.read((char *)data_out, bytes_to_read); + bytes_read = (int)inputStream.gcount(); + remaining -= bytes_read; + + if (remaining == 0) { + isComplete = true; + inputStream.close(); + } + + return true; +} + +void BrowserSchemeHandler::Cancel() +{ + if (inputStream.is_open()) + inputStream.close(); +} diff --git a/shared/browser-scheme.hpp b/browser-scheme.hpp similarity index 64% rename from shared/browser-scheme.hpp rename to browser-scheme.hpp index 1e819266b..bef1123a1 100644 --- a/shared/browser-scheme.hpp +++ b/browser-scheme.hpp @@ -1,5 +1,6 @@ /****************************************************************************** Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -17,46 +18,42 @@ #pragma once -#include +#include "cef-headers.hpp" +#include #include -#include - class BrowserSchemeHandlerFactory : public CefSchemeHandlerFactory { - public: - BrowserSchemeHandlerFactory(); - -public: // CefSchemeHandlerFactory overrides virtual CefRefPtr Create( CefRefPtr browser, - CefRefPtr frame, const CefString& scheme_name, - CefRefPtr request); + CefRefPtr, + const CefString &, + CefRefPtr request) override; -public: IMPLEMENT_REFCOUNTING(BrowserSchemeHandlerFactory); - }; class BrowserSchemeHandler : public CefResourceHandler { -public: - BrowserSchemeHandler(); - virtual bool ProcessRequest(CefRefPtr request, - CefRefPtr callback); - virtual void GetResponseHeaders(CefRefPtr response, - int64& response_length, CefString& redirectUrl); - virtual bool ReadResponse(void* data_out, int bytes_to_read, - int& bytes_read, CefRefPtr callback); - virtual void Cancel(); - - -private: std::string fileName; std::ifstream inputStream; - bool isComplete; - int64 length; - int64 remaining; + bool isComplete = false; + int64 length = 0; + int64 remaining = 0; public: + virtual bool ProcessRequest( + CefRefPtr request, + CefRefPtr callback) override; + virtual void GetResponseHeaders( + CefRefPtr response, + int64 &response_length, + CefString &redirectUrl) override; + virtual bool ReadResponse( + void *data_out, + int bytes_to_read, + int &bytes_read, + CefRefPtr callback) override; + virtual void Cancel() override; + IMPLEMENT_REFCOUNTING(BrowserSchemeHandler); }; diff --git a/browser-version.h b/browser-version.h new file mode 100644 index 000000000..c72e26429 --- /dev/null +++ b/browser-version.h @@ -0,0 +1,25 @@ +#pragma once + +#define OBS_BROWSER_VERSION_MAJOR 2 +#define OBS_BROWSER_VERSION_MINOR 0 +#define OBS_BROWSER_VERSION_PATCH 0 + +#ifndef MAKE_SEMANTIC_VERSION +#define MAKE_SEMANTIC_VERSION(major, minor, patch) \ + ((major << 24) | \ + (minor << 16) | \ + patch ) +#endif + +#define OBS_BROWSER_VERSION_INT \ + MAKE_SEMANTIC_VERSION(OBS_BROWSER_VERSION_MAJOR, \ + OBS_BROWSER_VERSION_MINOR, \ + OBS_BROWSER_VERSION_PATCH) + +#define OBS_BROWSER_MACRO_STR_(x) #x +#define OBS_BROWSER_MACRO_STR(x) OBS_BROWSER_MACRO_STR_(x) + +#define OBS_BROWSER_VERSION_STRING \ + OBS_BROWSER_MACRO_STR(OBS_BROWSER_VERSION_MAJOR) "." \ + OBS_BROWSER_MACRO_STR(OBS_BROWSER_VERSION_MINOR) "." \ + OBS_BROWSER_MACRO_STR(OBS_BROWSER_VERSION_PATCH) diff --git a/cef-bootstrap/main.cpp b/cef-bootstrap/cef-bootstrap-main.cpp similarity index 81% rename from cef-bootstrap/main.cpp rename to cef-bootstrap/cef-bootstrap-main.cpp index c0eb55804..d14003a6e 100644 --- a/cef-bootstrap/main.cpp +++ b/cef-bootstrap/cef-bootstrap-main.cpp @@ -1,5 +1,6 @@ /****************************************************************************** Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -15,20 +16,19 @@ along with this program. If not, see . ******************************************************************************/ -#include - +#include "cef-headers.hpp" #include "browser-app.hpp" #ifdef _WIN32 -int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPSTR lpCmdLine, int nCmdShow) +int CALLBACK WinMain(HINSTANCE, HINSTANCE, + LPSTR, int) { - CefMainArgs mainArgs(NULL); + CefMainArgs mainArgs(nullptr); #else int main(int argc, char *argv[]) { CefMainArgs mainArgs(argc, argv); #endif CefRefPtr mainApp(new BrowserApp()); - return CefExecuteProcess(mainArgs, mainApp.get(), NULL); + return CefExecuteProcess(mainArgs, mainApp.get(), NULL); } diff --git a/shared/browser-types.h b/cef-headers.hpp similarity index 58% rename from shared/browser-types.h rename to cef-headers.hpp index 46697cd88..d8a3cddb4 100644 --- a/shared/browser-types.h +++ b/cef-headers.hpp @@ -1,5 +1,6 @@ /****************************************************************************** Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -17,12 +18,26 @@ #pragma once -#ifndef __APPLE__ -#include +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable : 4100) +#else +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wunused-parameter" +# pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif -#ifdef __APPLE__ -typedef int BrowserSurfaceHandle; +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +# pragma warning(pop) #else -typedef struct gs_texture *BrowserSurfaceHandle; +# pragma GCC diagnostic pop #endif diff --git a/cef-isolation/browser-handle.h b/cef-isolation/browser-handle.h deleted file mode 100644 index 21d7564cc..000000000 --- a/cef-isolation/browser-handle.h +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#pragma once - -#include -#include - -#include - -#include "cef-isolation.h" -#include "browser-texture.hpp" - -class BrowserTexture; -class BrowserHandle; - -typedef std::shared_ptr SharedBrowserHandle; - -typedef int BrowserSurfaceHandle; - -class BrowserHandle { -public: - BrowserHandle(int width, int height, - id cefIsolationService); - -public: - bool RenderToAvailableTexture(int width, int height, const void *data); -public: - int GetWidth() const; - int GetHeight() const; - - void Shutdown(); - - void SetBrowser(CefRefPtr browser); - CefRefPtr GetBrowser(); - -private: - CefRefPtr browser; - - const int width; - const int height; - - // This should be abstracted away so that both OSX and other platforms - // can use this class - id cefIsolationService; - - std::unique_ptr browserTexture; -}; diff --git a/cef-isolation/browser-handle.mm b/cef-isolation/browser-handle.mm deleted file mode 100644 index cd3d71cea..000000000 --- a/cef-isolation/browser-handle.mm +++ /dev/null @@ -1,91 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#include "browser-texture.hpp" -#include "browser-handle.h" - -BrowserHandle::BrowserHandle(int width, int height, - id cefIsolationService) -: width(width), height(height), cefIsolationService(cefIsolationService) -{} - -void BrowserHandle::SetBrowser(CefRefPtr browser) -{ - this->browser = browser; -} - -CefRefPtr BrowserHandle::GetBrowser() -{ - return browser; -} - -void BrowserHandle::Shutdown() -{ - if (browser == nullptr) { - return; - } - - browser->GetHost()->CloseBrowser(true); -} - -int BrowserHandle::GetWidth() const -{ - return width; -} - -int BrowserHandle::GetHeight() const -{ - return height; -} - -bool BrowserHandle::RenderToAvailableTexture(int width, int height, - const void *data) -{ - if (browser == nullptr) { - return false; - } - - bool needsOnDraw = false; - if (browserTexture == nullptr) { - int surfaceHandle = 0; - if ([cefIsolationService createSurface: browser->GetIdentifier() - width: width height: height - surfaceHandle: &surfaceHandle]) - { - std::unique_ptr newTexture( - new BrowserTexture(width, height, - surfaceHandle)); - - browserTexture = std::move(newTexture); - - needsOnDraw = true; - } - } - - if (browserTexture != nullptr) { - browserTexture->Upload(data); - - if (needsOnDraw) { - [cefIsolationService onDraw: browser->GetIdentifier() - width: width height:height - surfaceHandle: - browserTexture->GetHandle()]; - } - } - - return true; -} diff --git a/cef-isolation/browser-obs-bridge-mac.hpp b/cef-isolation/browser-obs-bridge-mac.hpp deleted file mode 100644 index 7eb0812bf..000000000 --- a/cef-isolation/browser-obs-bridge-mac.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "cef-isolation.h" -#include "browser-obs-bridge.hpp" - -class BrowserOBSBridgeMac : public BrowserOBSBridge -{ -public: - BrowserOBSBridgeMac(id cefIsolationService); - - const char* GetCurrentSceneJSONData() override; - const char* GetStatus() override; - -private: - id cefIsolationService; -}; diff --git a/cef-isolation/browser-obs-bridge-mac.mm b/cef-isolation/browser-obs-bridge-mac.mm deleted file mode 100644 index 4b31b57e9..000000000 --- a/cef-isolation/browser-obs-bridge-mac.mm +++ /dev/null @@ -1,15 +0,0 @@ -#include "browser-obs-bridge-mac.hpp" - -BrowserOBSBridgeMac::BrowserOBSBridgeMac(id cefIsolationService) -: cefIsolationService(cefIsolationService) -{} - -const char* BrowserOBSBridgeMac::GetCurrentSceneJSONData() -{ - return [cefIsolationService getCurrentSceneJSONData]; -} - -const char* BrowserOBSBridgeMac::GetStatus() -{ - return [cefIsolationService getStatus]; -} diff --git a/cef-isolation/browser-render-handler.mm b/cef-isolation/browser-render-handler.mm deleted file mode 100644 index 32c2da902..000000000 --- a/cef-isolation/browser-render-handler.mm +++ /dev/null @@ -1,51 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - - -#import "cef-logging.h" - -#include "browser-render-handler.hpp" -#include "browser-handle.h" - -BrowserRenderHandler::BrowserRenderHandler( - std::shared_ptr &browserHandle) -: browserHandle(browserHandle) -{ -} - -bool BrowserRenderHandler::GetViewRect(CefRefPtr browser, - CefRect &rect) -{ - (void)(browser); - - rect.Set(0, 0, browserHandle->GetWidth(), browserHandle->GetHeight()); - return true; -} - - - -void BrowserRenderHandler::OnPaint( - CefRefPtr browser, PaintElementType type, - const RectList &dirtyRects, const void *data, int width, - int height) -{ - (void)(browser); - (void)(type); - (void)(dirtyRects); - - browserHandle->RenderToAvailableTexture(width, height, data); -} diff --git a/cef-isolation/browser-texture-mac.h b/cef-isolation/browser-texture-mac.h deleted file mode 100644 index 54d27ec14..000000000 --- a/cef-isolation/browser-texture-mac.h +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#pragma once - -#include "browser-texture.hpp" - -class BrowserTexture::Impl { -public: - Impl(int width, int height, BrowserSurfaceHandle surfaceHandle); - ~Impl(); - - int GetWidth() const; - int GetHeight() const; - BrowserSurfaceHandle GetHandle() const; - bool Upload(const void *data); - -private: - const int width; - const int height; - const BrowserSurfaceHandle surfaceHandle; - IOSurfaceRef ioSurfaceRef; -}; diff --git a/cef-isolation/browser-texture-mac.mm b/cef-isolation/browser-texture-mac.mm deleted file mode 100644 index 8eca05512..000000000 --- a/cef-isolation/browser-texture-mac.mm +++ /dev/null @@ -1,94 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#import -#import -#import - -#include "cef-logging.h" - -#include "browser-texture-mac.h" - -BrowserTexture::BrowserTexture(const int width, const int height, - const BrowserSurfaceHandle surfaceHandle) -: pimpl(new Impl(width, height, surfaceHandle)) -{} - -BrowserTexture::~BrowserTexture() -{} - -int BrowserTexture::GetWidth() const -{ - return pimpl->GetWidth(); -} - -int BrowserTexture::GetHeight() const -{ - return pimpl->GetHeight(); -} - -BrowserSurfaceHandle BrowserTexture::GetHandle() const -{ - return pimpl->GetHandle(); -} - -bool BrowserTexture::Upload(const void *data) -{ - return pimpl->Upload(data); -} - -BrowserTexture::Impl::Impl(int width, int height, - BrowserSurfaceHandle surfaceHandle) -: width(width), height(height), surfaceHandle(surfaceHandle) -{ - ioSurfaceRef = IOSurfaceLookup(surfaceHandle); - IOSurfaceIncrementUseCount(ioSurfaceRef); -} - -BrowserTexture::Impl::~Impl() -{ - IOSurfaceDecrementUseCount(ioSurfaceRef); - CFRelease(ioSurfaceRef); -} - -int BrowserTexture::Impl::GetWidth() const -{ - return width; -} - -int BrowserTexture::Impl::GetHeight() const -{ - return height; -} - -BrowserSurfaceHandle BrowserTexture::Impl::GetHandle() const -{ - return surfaceHandle; -} - -bool BrowserTexture::Impl::Upload(const void *data) -{ - if (ioSurfaceRef) { - IOSurfaceLock(ioSurfaceRef, 0, nullptr); - void *surfaceData = IOSurfaceGetBaseAddress(ioSurfaceRef); - memcpy(surfaceData, data, width * height * 4); - IOSurfaceUnlock(ioSurfaceRef, 0, nullptr); - return true; - } - return false; - -} diff --git a/cef-isolation/cef-isolated-client.h b/cef-isolation/cef-isolated-client.h deleted file mode 100644 index 39e2b4749..000000000 --- a/cef-isolation/cef-isolated-client.h +++ /dev/null @@ -1,29 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#pragma once - -#include - -#import "cef-isolation.h" -#include "browser-handle.h" - -@interface CEFIsolatedClient : NSObject { - id _server; - std::map > map; -} -@end diff --git a/cef-isolation/cef-isolated-client.mm b/cef-isolation/cef-isolated-client.mm deleted file mode 100644 index eaf2a811d..000000000 --- a/cef-isolation/cef-isolated-client.mm +++ /dev/null @@ -1,380 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#import -#import - -#include -#include -#include - -// shared apple -#import "cef-isolation.h" -#import "cef-logging.h" -#import "browser-bridges.h" - -// shared -#include "browser-task.hpp" -#include "browser-client.hpp" - -#include "browser-handle.h" -#include "browser-render-handler.hpp" -#include "obs-browser/browser-load-handler.hpp" - -#import "cef-isolated-client.h" - -#import "browser-obs-bridge-mac.hpp" - -@implementation CEFIsolatedClient - -- (id)init -{ - if (self = [super init]) { - _server = nil; - } - return self; -} - -- (oneway void)registerServer:(id)server -{ - CEFLogDebug(@"Registered server"); - _server = server; -} - -void sync_on_cef_ui(dispatch_block_t block) -{ - if ([NSThread isMainThread]) { - block(); - } else { - dispatch_sync(dispatch_get_main_queue(), block); - } -} - -- (void)update:(CefRefPtr)browser -{ - browser->GetHost()->WasResized(); -} - -- (int)createBrowser:(BrowserSettingsBridge *)browserSettings -{ - __block CefRefPtr browser; - - __block std::shared_ptr browserHandle( - new BrowserHandle(browserSettings.width, - browserSettings.height, _server)); - - BrowserOBSBridge *browserOBSBridge = new BrowserOBSBridgeMac(_server); - - sync_on_cef_ui(^{ - - CefRefPtr browserRenderHandler = - new BrowserRenderHandler(browserHandle); - - CefRefPtr loadHandler = - new BrowserLoadHandler(std::string([browserSettings.css UTF8String])); - - CefRefPtr browserClient = - new BrowserClient(browserRenderHandler.get(),loadHandler, browserOBSBridge); - - CefWindowInfo windowInfo; - windowInfo.view = nullptr; - windowInfo.parent_view = nullptr; -#if CHROME_VERSION_BUILD < 3071 - windowInfo.transparent_painting_enabled = true; -#endif - windowInfo.width = browserSettings.width; - windowInfo.height = browserSettings.height; - windowInfo.windowless_rendering_enabled = true; - - - CefBrowserSettings cefBrowserSettings; - cefBrowserSettings.windowless_frame_rate = browserSettings.fps; - - //TODO Switch to using async browser creation - // Less chance of freezes here taking the whole - // process down - browser = CefBrowserHost::CreateBrowserSync(windowInfo, - browserClient.get(), - [browserSettings.url UTF8String], - cefBrowserSettings, nil); - }); - - if (browser != nil) { - browserHandle->SetBrowser(browser.get()); - map[browser->GetIdentifier()] = browserHandle; - return browser->GetIdentifier(); - } else { - return 0; - } -} - -- (oneway void)tickBrowser: (const int)browserIdentifier { - (void)browserIdentifier; - // Not implemented -} - -typedef void(^event_block_t)(std::shared_ptr); - -- (void)sendEvent:(const int)browserIdentifier - event:(event_block_t)event -{ - if (map.count(browserIdentifier) == 1) { - SharedBrowserHandle browserHandle = - map[browserIdentifier]; - sync_on_cef_ui(^{ - event(browserHandle); - }); - } -} - -- (void)sendEventToAllBrowsers:(event_block_t)event -{ - for (auto& x: map) { - SharedBrowserHandle browserHandle = x.second; - sync_on_cef_ui(^{ - event(browserHandle); - }); - } -} - -- (void)sendMouseClick:(const int)browserIdentifier - event:(ObsMouseEventBridge *)event type:(const int)type - mouseUp:(BOOL)mouseUp clickCount:(const int)clickCount -{ - [self sendEvent:browserIdentifier - event:^(SharedBrowserHandle browserHandle) - { - CefMouseEvent mouseEvent; - mouseEvent.x = event.x; - mouseEvent.y = event.y; - mouseEvent.modifiers = event.modifiers; - CefRefPtr host = - browserHandle->GetBrowser()->GetHost(); - - CefBrowserHost::MouseButtonType buttonType = - (CefBrowserHost::MouseButtonType)type; - - host->SendMouseClickEvent(mouseEvent, buttonType, - mouseUp, clickCount); - }]; -} - - -- (oneway void)sendMouseMove:(const int)browserIdentifier - event:(ObsMouseEventBridge *)event mouseLeave:(BOOL)mouseLeave -{ - [self sendEvent:browserIdentifier - event:^(SharedBrowserHandle browserHandle) - { - CefMouseEvent mouseEvent; - mouseEvent.x = event.x; - mouseEvent.y = event.y; - mouseEvent.modifiers = event.modifiers; - - CefRefPtr host = - browserHandle->GetBrowser()->GetHost(); - host->SendMouseMoveEvent(mouseEvent, mouseLeave); - }]; -} - -- (void)sendMouseWheel:(const int)browserIdentifier - event:(ObsMouseEventBridge *)event xDelta:(int)xDelta - yDelta:(int)yDelta -{ - [self sendEvent:browserIdentifier - event:^(SharedBrowserHandle browserHandle) - { - CefMouseEvent mouseEvent; - mouseEvent.x = event.x; - mouseEvent.y = event.y; - mouseEvent.modifiers = event.modifiers; - - CefRefPtr host = - browserHandle->GetBrowser()->GetHost(); - host->SendMouseWheelEvent(mouseEvent, xDelta, yDelta); - }]; -} - -- (oneway void)sendFocus:(const int)browserIdentifier focus:(BOOL)focus -{ - [self sendEvent:browserIdentifier - event:^(SharedBrowserHandle browserHandle) - { - CefRefPtr host = - browserHandle->GetBrowser()->GetHost(); - host->SendFocusEvent(focus); - [[host->GetWindowHandle() window] - makeFirstResponder: host->GetWindowHandle()]; - }]; -} - -enum AppleVirtualKey { - kVK_Return = 0x24, - kVK_Command = 0x37, - kVK_Shift = 0x38, - kVK_Option = 0x3A, - kVK_Control = 0x3B, -}; - -void getUnmodifiedCharacter(ObsKeyEventBridge *event, UniChar &character) -{ - @autoreleasepool { - CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, - event.nativeVirtualKey, false); - - NSEvent *e = [NSEvent eventWithCGEvent: cgEvent]; - NSString *s = [e charactersIgnoringModifiers]; - if (s && s.length) - character = [s characterAtIndex: 0]; - - CFRelease(cgEvent); - } -} - -- (void)sendKeyClick:(const int)browserIdentifier - event:(bycopy ObsKeyEventBridge *)event keyUp:(BOOL)keyUp -{ - [self sendEvent:browserIdentifier - event:^(SharedBrowserHandle browserHandle) - { - CefRefPtr host = - browserHandle->GetBrowser()->GetHost(); - - - - NSEvent *nsEvent = - [NSEvent keyEventWithType: keyUp ? NSKeyUp : NSKeyDown - location: NSMakePoint(0,0) - modifierFlags: [event nativeModifiers] - timestamp: 0 - windowNumber: 0 - context: nil - characters: [event text] - charactersIgnoringModifiers: nil - isARepeat: false - keyCode: event.nativeVirtualKey]; - - - CefKeyEvent keyEvent; - keyEvent.modifiers = [event modifiers]; - - keyEvent.native_key_code = event.nativeVirtualKey; - - if (event.text.length) { - keyEvent.character = - [event.text characterAtIndex: 0]; - - getUnmodifiedCharacter(event, - keyEvent.unmodified_character); - } - - - if (keyUp) { - keyEvent.type = KEYEVENT_KEYUP; - host->SendKeyEvent(keyEvent); - } else { - // Somehow return is not handled correctly - if ([event nativeVirtualKey] == kVK_Return) { - keyEvent.type = KEYEVENT_CHAR; - host->SendKeyEvent(keyEvent); - return; - } - - host->SendKeyEvent(keyEvent); - } - }]; -} - -- (void)executeVisiblityJSCallback:(const int)browserIdentifier visible:(BOOL)visible -{ - [self sendEvent:browserIdentifier - event:^(SharedBrowserHandle browserHandle) - { - CefRefPtr browser = browserHandle->GetBrowser(); - - CefRefPtr msg = CefProcessMessage::Create("Visibility"); - CefRefPtr args = msg->GetArgumentList(); - args->SetBool(0, visible); - browser->SendProcessMessage(PID_RENDERER, msg); - }]; -} - -- (void)executeActiveJSCallback:(const int)browserIdentifier active:(BOOL)active -{ - [self sendEvent:browserIdentifier - event:^(SharedBrowserHandle browserHandle) - { - CefRefPtr browser = browserHandle->GetBrowser(); - - CefRefPtr msg = CefProcessMessage::Create("Active"); - CefRefPtr args = msg->GetArgumentList(); - args->SetBool(0, active); - browser->SendProcessMessage(PID_RENDERER, msg); - }]; -} - -- (void)executeSceneChangeJSCallback:(const char *)name -{ - [self sendEventToAllBrowsers:^(SharedBrowserHandle browserHandle) - { - CefRefPtr browser = browserHandle->GetBrowser(); - - CefRefPtr msg = CefProcessMessage::Create("SceneChange"); - CefRefPtr args = msg->GetArgumentList(); - args->SetString(0, name); - browser->SendProcessMessage(PID_RENDERER, msg); - }]; -} - -- (void)refreshPageNoCache:(const int)browserIdentifier -{ - [self sendEvent:browserIdentifier - event:^(SharedBrowserHandle browserHandle) - { - CefRefPtr browser = browserHandle->GetBrowser(); - - browser->ReloadIgnoreCache(); - }]; -} - --(void)dispatchJSEvent:(const char *)eventName data:(const char *)jsonString -{ - [self sendEventToAllBrowsers:^(SharedBrowserHandle browserHandle) - { - CefRefPtr browser = browserHandle->GetBrowser(); - - CefRefPtr msg = CefProcessMessage::Create("DispatchJSEvent"); - CefRefPtr args = msg->GetArgumentList(); - args->SetString(0, eventName); - args->SetString(1, jsonString); - - browser->SendProcessMessage(PID_RENDERER, msg); - }]; -} - -- (void)destroyBrowser:(const int)browserIdentifier { - if (map.count(browserIdentifier) == 1) { - std::shared_ptr browserHandle = - map[browserIdentifier]; - sync_on_cef_ui(^{ - browserHandle->Shutdown(); - }); - map.erase(browserIdentifier); - } -} - -@end diff --git a/cef-isolation/main.mm b/cef-isolation/main.mm deleted file mode 100644 index 4f1723287..000000000 --- a/cef-isolation/main.mm +++ /dev/null @@ -1,123 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#import - -#include - -#include -#include - -#import "cef-logging.h" -#import "cef-isolation.h" - -#import "cef-isolated-client.h" -#include "browser-app.hpp" -#include "browser-scheme.hpp" - -#include "objc/runtime.h" - -#import "service-connection-delegate.h" - -void processTerminatedEvent(CFFileDescriptorRef fdref, - CFOptionFlags callBackTypes, void* info) -{ - (void)callBackTypes; - (void)info; - - CFFileDescriptorInvalidate(fdref); - CFRelease(fdref); - CEFLogError(@"Parent process died, exiting isolated CEF process."); - exit(EXIT_SUCCESS); -} - - -void hookParentDeath() -{ - int fd = kqueue(); - struct kevent kev; - EV_SET(&kev, getppid(), EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, - 0, NULL); - kevent(fd, &kev, 1, NULL, 0, NULL); - CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, - fd, true, processTerminatedEvent, NULL); - CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack); - CFRunLoopSourceRef source = - CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, - fdref, 0); - CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode); - CFRelease(source); -} - -int main (int argc, const char * argv[]) -{ - - hookParentDeath(); - - @autoreleasepool { - if (argc != 2) { - CEFLogError(@"Invalid arguments send to client"); - return -1; - } - - NSString *uniqueClientName = - [NSString stringWithUTF8String: argv[1]]; - - CEFLogDebug(@"Process created with argument: %@", - uniqueClientName); - - - CefMainArgs mainArgs; - CefSettings settings; - - settings.log_severity = LOGSEVERITY_DEFAULT; - settings.windowless_rendering_enabled = true; - - CefRefPtr app(new BrowserApp()); - - CEFLogDebug(@"Initializing CEF Runtime"); - if (CefInitialize(mainArgs, settings, app, nullptr) != 1) { - CEFLogError(@"Could not initialize CEF Runtime"); - } - - ServiceConnectionDelegate *delegate = - [[[ServiceConnectionDelegate alloc] - initWithUniqueName: uniqueClientName] - autorelease]; - - - // Eventually move this to NSThread alloc/init so we can - // attach lifetime observers before it starts - [NSThread detachNewThreadSelector: - @selector(createConnectionThread) - toTarget: delegate withObject: nil]; - - CefRefPtr factory = - CefRefPtr( - new BrowserSchemeHandlerFactory()); - - CefRegisterSchemeHandlerFactory("http", "absolute", factory); - - CefRunMessageLoop(); - - CefShutdown(); - - [delegate shutdown]; - } - - return 0; -} diff --git a/cef-isolation/service-connection-delegate.h b/cef-isolation/service-connection-delegate.h deleted file mode 100644 index 4417823d1..000000000 --- a/cef-isolation/service-connection-delegate.h +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#pragma once - -class CEFisolationService; - -@interface ServiceConnectionDelegate : NSObject -{ - id _cefIsolationService; - NSString *uniqueClientName; - NSConditionLock *lock; - BOOL shutdown; - NSThread *connectionThread; -} - -@property (readonly) id cefIsolationService; - -- (ServiceConnectionDelegate *)initWithUniqueName: (NSString *)name; -- (void)createConnectionThread; -- (void)shutdown; - -@end diff --git a/cef-isolation/service-connection-delegate.mm b/cef-isolation/service-connection-delegate.mm deleted file mode 100644 index 0e868e40a..000000000 --- a/cef-isolation/service-connection-delegate.mm +++ /dev/null @@ -1,124 +0,0 @@ -/****************************************************************************** - Copyright (C) 2014 by John R. Bradley - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - ******************************************************************************/ - -#import "cef-logging.h" - -#import "cef-isolation.h" -#import "cef-isolated-client.h" -#import "service-connection-delegate.h" - - - -@implementation ServiceConnectionDelegate - -#define T_START 0 -#define T_FINISHED 1 - -@synthesize cefIsolationService = _cefIsolationService; - - -- (ServiceConnectionDelegate *)initWithUniqueName: (NSString *)name -{ - self = [super init]; - if (self) { - lock = [[[NSConditionLock alloc] initWithCondition: T_START] - autorelease]; - uniqueClientName = name; - } - return self; -} - -- (void)createConnectionThread -{ - [[NSThread currentThread] setName: @"CEF Service IO Thread"]; - - @autoreleasepool { - - CEFLogDebug(@"Connecting to host process"); - - [lock lockWhenCondition: T_START]; - - NSRunLoop *threadRunLoop = [NSRunLoop currentRunLoop]; - connectionThread = [NSThread currentThread]; - - NSConnection *connection = - [[[NSConnection alloc] init] autorelease]; - - - CEFIsolatedClient *cefIsolatedClient = - [[[CEFIsolatedClient alloc] init] autorelease]; - - while(nil == _cefIsolationService) - { - // This connection should be moved to its own thread - // so that calls from OBS are not delayed by - // CEF tasks in the message loop. - NSConnection *connection = [NSConnection - connectionWithRegisteredName: - uniqueClientName - host: nil]; - - [connection setRootObject: cefIsolatedClient]; - CEFLogDebug(@"Checking for host process connection..."); - _cefIsolationService = (id)[connection rootProxy]; - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate - dateWithTimeIntervalSinceNow:.1]]; - } - - CEFLogDebug(@"Connected to host process and fetched proxy service"); - CEFLogDebug(@"Attempting to register client with service"); - [_cefIsolationService registerClient: cefIsolatedClient]; - - [connection addRunLoop: threadRunLoop]; - - BOOL threadAlive = YES; - while (threadAlive) { - @autoreleasepool { - [threadRunLoop runMode:NSDefaultRunLoopMode - beforeDate: - [NSDate distantFuture]]; - threadAlive = !shutdown; - } - } - - // invalidate connection and proxy objects - [connection invalidate]; - } - - connectionThread = nil; - - [lock unlockWithCondition: T_FINISHED]; -} - -// internally only called by shutdown as a means to wake up runloop -- (void)shutdownThread -{ - shutdown = YES; -} - -- (void)shutdown -{ - [self performSelector:@selector(shutdownThread) - onThread:connectionThread withObject:nil - waitUntilDone:NO]; - - // wait for thread to finish - [lock lockWhenCondition: T_FINISHED]; - [lock unlockWithCondition: T_START]; -} - -@end diff --git a/cef-isolation/service-connection.delegate.mm b/cef-isolation/service-connection.delegate.mm deleted file mode 100644 index e69de29bb..000000000 diff --git a/shared/base64.cpp b/deps/base64/base64.cpp similarity index 94% rename from shared/base64.cpp rename to deps/base64/base64.cpp index 4a21c230f..2c09150fd 100644 --- a/shared/base64.cpp +++ b/deps/base64/base64.cpp @@ -82,7 +82,7 @@ std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_ } std::string base64_decode(std::string const& encoded_string) { - int in_len = encoded_string.size(); + int in_len = (int)encoded_string.size(); int i = 0; int j = 0; int in_ = 0; @@ -93,7 +93,7 @@ std::string base64_decode(std::string const& encoded_string) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0; i <4; i++) - char_array_4[i] = base64_chars.find(char_array_4[i]); + char_array_4[i] = (unsigned char)base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); @@ -110,7 +110,7 @@ std::string base64_decode(std::string const& encoded_string) { char_array_4[j] = 0; for (j = 0; j <4; j++) - char_array_4[j] = base64_chars.find(char_array_4[j]); + char_array_4[j] = (unsigned char)base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); diff --git a/deps/base64/base64.hpp b/deps/base64/base64.hpp new file mode 100644 index 000000000..aaa738069 --- /dev/null +++ b/deps/base64/base64.hpp @@ -0,0 +1,14 @@ +#include + +std::string base64_encode(unsigned char const*, unsigned int len); +std::string base64_decode(std::string const& s); + +static inline std::string base64_encode(const char *str, unsigned int len) +{ + return base64_encode((unsigned const char *)str, len); +} + +static inline std::string base64_encode(const std::string &str) +{ + return base64_encode(str.c_str(), (unsigned int)str.size()); +} diff --git a/deps/json11/LICENSE.txt b/deps/json11/LICENSE.txt new file mode 100644 index 000000000..691742e9e --- /dev/null +++ b/deps/json11/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2013 Dropbox, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/deps/json11/json11.cpp b/deps/json11/json11.cpp new file mode 100644 index 000000000..9647846b6 --- /dev/null +++ b/deps/json11/json11.cpp @@ -0,0 +1,788 @@ +/* Copyright (c) 2013 Dropbox, Inc. + * + * 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. + */ + +#include "json11.hpp" +#include +#include +#include +#include +#include + +namespace json11 { + +static const int max_depth = 200; + +using std::string; +using std::vector; +using std::map; +using std::make_shared; +using std::initializer_list; +using std::move; + +/* Helper for representing null - just a do-nothing struct, plus comparison + * operators so the helpers in JsonValue work. We can't use nullptr_t because + * it may not be orderable. + */ +struct NullStruct { + bool operator==(NullStruct) const { return true; } + bool operator<(NullStruct) const { return false; } +}; + +/* * * * * * * * * * * * * * * * * * * * + * Serialization + */ + +static void dump(NullStruct, string &out) { + out += "null"; +} + +static void dump(double value, string &out) { + if (std::isfinite(value)) { + char buf[32]; + snprintf(buf, sizeof buf, "%.17g", value); + out += buf; + } else { + out += "null"; + } +} + +static void dump(int value, string &out) { + char buf[32]; + snprintf(buf, sizeof buf, "%d", value); + out += buf; +} + +static void dump(bool value, string &out) { + out += value ? "true" : "false"; +} + +static void dump(const string &value, string &out) { + out += '"'; + for (size_t i = 0; i < value.length(); i++) { + const char ch = value[i]; + if (ch == '\\') { + out += "\\\\"; + } else if (ch == '"') { + out += "\\\""; + } else if (ch == '\b') { + out += "\\b"; + } else if (ch == '\f') { + out += "\\f"; + } else if (ch == '\n') { + out += "\\n"; + } else if (ch == '\r') { + out += "\\r"; + } else if (ch == '\t') { + out += "\\t"; + } else if (static_cast(ch) <= 0x1f) { + char buf[8]; + snprintf(buf, sizeof buf, "\\u%04x", ch); + out += buf; + } else if (static_cast(ch) == 0xe2 && static_cast(value[i+1]) == 0x80 + && static_cast(value[i+2]) == 0xa8) { + out += "\\u2028"; + i += 2; + } else if (static_cast(ch) == 0xe2 && static_cast(value[i+1]) == 0x80 + && static_cast(value[i+2]) == 0xa9) { + out += "\\u2029"; + i += 2; + } else { + out += ch; + } + } + out += '"'; +} + +static void dump(const Json::array &values, string &out) { + bool first = true; + out += "["; + for (const auto &value : values) { + if (!first) + out += ", "; + value.dump(out); + first = false; + } + out += "]"; +} + +static void dump(const Json::object &values, string &out) { + bool first = true; + out += "{"; + for (const auto &kv : values) { + if (!first) + out += ", "; + dump(kv.first, out); + out += ": "; + kv.second.dump(out); + first = false; + } + out += "}"; +} + +void Json::dump(string &out) const { + m_ptr->dump(out); +} + +/* * * * * * * * * * * * * * * * * * * * + * Value wrappers + */ + +template +class Value : public JsonValue { +protected: + + // Constructors + explicit Value(const T &value) : m_value(value) {} + explicit Value(T &&value) : m_value(move(value)) {} + + // Get type tag + Json::Type type() const override { + return tag; + } + + // Comparisons + bool equals(const JsonValue * other) const override { + return m_value == static_cast *>(other)->m_value; + } + bool less(const JsonValue * other) const override { + return m_value < static_cast *>(other)->m_value; + } + + const T m_value; + void dump(string &out) const override { json11::dump(m_value, out); } +}; + +class JsonDouble final : public Value { + double number_value() const override { return m_value; } + int int_value() const override { return static_cast(m_value); } + bool equals(const JsonValue * other) const override { return m_value == other->number_value(); } + bool less(const JsonValue * other) const override { return m_value < other->number_value(); } +public: + explicit JsonDouble(double value) : Value(value) {} +}; + +class JsonInt final : public Value { + double number_value() const override { return m_value; } + int int_value() const override { return m_value; } + bool equals(const JsonValue * other) const override { return m_value == other->number_value(); } + bool less(const JsonValue * other) const override { return m_value < other->number_value(); } +public: + explicit JsonInt(int value) : Value(value) {} +}; + +class JsonBoolean final : public Value { + bool bool_value() const override { return m_value; } +public: + explicit JsonBoolean(bool value) : Value(value) {} +}; + +class JsonString final : public Value { + const string &string_value() const override { return m_value; } +public: + explicit JsonString(const string &value) : Value(value) {} + explicit JsonString(string &&value) : Value(move(value)) {} +}; + +class JsonArray final : public Value { + const Json::array &array_items() const override { return m_value; } + const Json & operator[](size_t i) const override; +public: + explicit JsonArray(const Json::array &value) : Value(value) {} + explicit JsonArray(Json::array &&value) : Value(move(value)) {} +}; + +class JsonObject final : public Value { + const Json::object &object_items() const override { return m_value; } + const Json & operator[](const string &key) const override; +public: + explicit JsonObject(const Json::object &value) : Value(value) {} + explicit JsonObject(Json::object &&value) : Value(move(value)) {} +}; + +class JsonNull final : public Value { +public: + JsonNull() : Value({}) {} +}; + +/* * * * * * * * * * * * * * * * * * * * + * Static globals - static-init-safe + */ +struct Statics { + const std::shared_ptr null = make_shared(); + const std::shared_ptr t = make_shared(true); + const std::shared_ptr f = make_shared(false); + const string empty_string; + const vector empty_vector; + const map empty_map; + Statics() {} +}; + +static const Statics & statics() { + static const Statics s {}; + return s; +} + +static const Json & static_null() { + // This has to be separate, not in Statics, because Json() accesses statics().null. + static const Json json_null; + return json_null; +} + +/* * * * * * * * * * * * * * * * * * * * + * Constructors + */ + +Json::Json() noexcept : m_ptr(statics().null) {} +Json::Json(std::nullptr_t) noexcept : m_ptr(statics().null) {} +Json::Json(double value) : m_ptr(make_shared(value)) {} +Json::Json(int value) : m_ptr(make_shared(value)) {} +Json::Json(bool value) : m_ptr(value ? statics().t : statics().f) {} +Json::Json(const string &value) : m_ptr(make_shared(value)) {} +Json::Json(string &&value) : m_ptr(make_shared(move(value))) {} +Json::Json(const char * value) : m_ptr(make_shared(value)) {} +Json::Json(const Json::array &values) : m_ptr(make_shared(values)) {} +Json::Json(Json::array &&values) : m_ptr(make_shared(move(values))) {} +Json::Json(const Json::object &values) : m_ptr(make_shared(values)) {} +Json::Json(Json::object &&values) : m_ptr(make_shared(move(values))) {} + +/* * * * * * * * * * * * * * * * * * * * + * Accessors + */ + +Json::Type Json::type() const { return m_ptr->type(); } +double Json::number_value() const { return m_ptr->number_value(); } +int Json::int_value() const { return m_ptr->int_value(); } +bool Json::bool_value() const { return m_ptr->bool_value(); } +const string & Json::string_value() const { return m_ptr->string_value(); } +const vector & Json::array_items() const { return m_ptr->array_items(); } +const map & Json::object_items() const { return m_ptr->object_items(); } +const Json & Json::operator[] (size_t i) const { return (*m_ptr)[i]; } +const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key]; } + +double JsonValue::number_value() const { return 0; } +int JsonValue::int_value() const { return 0; } +bool JsonValue::bool_value() const { return false; } +const string & JsonValue::string_value() const { return statics().empty_string; } +const vector & JsonValue::array_items() const { return statics().empty_vector; } +const map & JsonValue::object_items() const { return statics().empty_map; } +const Json & JsonValue::operator[] (size_t) const { return static_null(); } +const Json & JsonValue::operator[] (const string &) const { return static_null(); } + +const Json & JsonObject::operator[] (const string &key) const { + auto iter = m_value.find(key); + return (iter == m_value.end()) ? static_null() : iter->second; +} +const Json & JsonArray::operator[] (size_t i) const { + if (i >= m_value.size()) return static_null(); + else return m_value[i]; +} + +/* * * * * * * * * * * * * * * * * * * * + * Comparison + */ + +bool Json::operator== (const Json &other) const { + if (m_ptr == other.m_ptr) + return true; + if (m_ptr->type() != other.m_ptr->type()) + return false; + + return m_ptr->equals(other.m_ptr.get()); +} + +bool Json::operator< (const Json &other) const { + if (m_ptr == other.m_ptr) + return false; + if (m_ptr->type() != other.m_ptr->type()) + return m_ptr->type() < other.m_ptr->type(); + + return m_ptr->less(other.m_ptr.get()); +} + +/* * * * * * * * * * * * * * * * * * * * + * Parsing + */ + +/* esc(c) + * + * Format char c suitable for printing in an error message. + */ +static inline string esc(char c) { + char buf[12]; + if (static_cast(c) >= 0x20 && static_cast(c) <= 0x7f) { + snprintf(buf, sizeof buf, "'%c' (%d)", c, c); + } else { + snprintf(buf, sizeof buf, "(%d)", c); + } + return string(buf); +} + +static inline bool in_range(long x, long lower, long upper) { + return (x >= lower && x <= upper); +} + +namespace { +/* JsonParser + * + * Object that tracks all state of an in-progress parse. + */ +struct JsonParser final { + + /* State + */ + const string &str; + size_t i; + string &err; + bool failed; + const JsonParse strategy; + + /* fail(msg, err_ret = Json()) + * + * Mark this parse as failed. + */ + Json fail(string &&msg) { + return fail(move(msg), Json()); + } + + template + T fail(string &&msg, const T err_ret) { + if (!failed) + err = std::move(msg); + failed = true; + return err_ret; + } + + /* consume_whitespace() + * + * Advance until the current character is non-whitespace. + */ + void consume_whitespace() { + while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t') + i++; + } + + /* consume_comment() + * + * Advance comments (c-style inline and multiline). + */ + bool consume_comment() { + bool comment_found = false; + if (str[i] == '/') { + i++; + if (i == str.size()) + return fail("unexpected end of input after start of comment", false); + if (str[i] == '/') { // inline comment + i++; + // advance until next line, or end of input + while (i < str.size() && str[i] != '\n') { + i++; + } + comment_found = true; + } + else if (str[i] == '*') { // multiline comment + i++; + if (i > str.size()-2) + return fail("unexpected end of input inside multi-line comment", false); + // advance until closing tokens + while (!(str[i] == '*' && str[i+1] == '/')) { + i++; + if (i > str.size()-2) + return fail( + "unexpected end of input inside multi-line comment", false); + } + i += 2; + comment_found = true; + } + else + return fail("malformed comment", false); + } + return comment_found; + } + + /* consume_garbage() + * + * Advance until the current character is non-whitespace and non-comment. + */ + void consume_garbage() { + consume_whitespace(); + if(strategy == JsonParse::COMMENTS) { + bool comment_found = false; + do { + comment_found = consume_comment(); + if (failed) return; + consume_whitespace(); + } + while(comment_found); + } + } + + /* get_next_token() + * + * Return the next non-whitespace character. If the end of the input is reached, + * flag an error and return 0. + */ + char get_next_token() { + consume_garbage(); + if (failed) return (char)0; + if (i == str.size()) + return fail("unexpected end of input", (char)0); + + return str[i++]; + } + + /* encode_utf8(pt, out) + * + * Encode pt as UTF-8 and add it to out. + */ + void encode_utf8(long pt, string & out) { + if (pt < 0) + return; + + if (pt < 0x80) { + out += static_cast(pt); + } else if (pt < 0x800) { + out += static_cast((pt >> 6) | 0xC0); + out += static_cast((pt & 0x3F) | 0x80); + } else if (pt < 0x10000) { + out += static_cast((pt >> 12) | 0xE0); + out += static_cast(((pt >> 6) & 0x3F) | 0x80); + out += static_cast((pt & 0x3F) | 0x80); + } else { + out += static_cast((pt >> 18) | 0xF0); + out += static_cast(((pt >> 12) & 0x3F) | 0x80); + out += static_cast(((pt >> 6) & 0x3F) | 0x80); + out += static_cast((pt & 0x3F) | 0x80); + } + } + + /* parse_string() + * + * Parse a string, starting at the current position. + */ + string parse_string() { + string out; + long last_escaped_codepoint = -1; + while (true) { + if (i == str.size()) + return fail("unexpected end of input in string", ""); + + char ch = str[i++]; + + if (ch == '"') { + encode_utf8(last_escaped_codepoint, out); + return out; + } + + if (in_range(ch, 0, 0x1f)) + return fail("unescaped " + esc(ch) + " in string", ""); + + // The usual case: non-escaped characters + if (ch != '\\') { + encode_utf8(last_escaped_codepoint, out); + last_escaped_codepoint = -1; + out += ch; + continue; + } + + // Handle escapes + if (i == str.size()) + return fail("unexpected end of input in string", ""); + + ch = str[i++]; + + if (ch == 'u') { + // Extract 4-byte escape sequence + string esc = str.substr(i, 4); + // Explicitly check length of the substring. The following loop + // relies on std::string returning the terminating NUL when + // accessing str[length]. Checking here reduces brittleness. + if (esc.length() < 4) { + return fail("bad \\u escape: " + esc, ""); + } + for (size_t j = 0; j < 4; j++) { + if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F') + && !in_range(esc[j], '0', '9')) + return fail("bad \\u escape: " + esc, ""); + } + + long codepoint = strtol(esc.data(), nullptr, 16); + + // JSON specifies that characters outside the BMP shall be encoded as a pair + // of 4-hex-digit \u escapes encoding their surrogate pair components. Check + // whether we're in the middle of such a beast: the previous codepoint was an + // escaped lead (high) surrogate, and this is a trail (low) surrogate. + if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF) + && in_range(codepoint, 0xDC00, 0xDFFF)) { + // Reassemble the two surrogate pairs into one astral-plane character, per + // the UTF-16 algorithm. + encode_utf8((((last_escaped_codepoint - 0xD800) << 10) + | (codepoint - 0xDC00)) + 0x10000, out); + last_escaped_codepoint = -1; + } else { + encode_utf8(last_escaped_codepoint, out); + last_escaped_codepoint = codepoint; + } + + i += 4; + continue; + } + + encode_utf8(last_escaped_codepoint, out); + last_escaped_codepoint = -1; + + if (ch == 'b') { + out += '\b'; + } else if (ch == 'f') { + out += '\f'; + } else if (ch == 'n') { + out += '\n'; + } else if (ch == 'r') { + out += '\r'; + } else if (ch == 't') { + out += '\t'; + } else if (ch == '"' || ch == '\\' || ch == '/') { + out += ch; + } else { + return fail("invalid escape character " + esc(ch), ""); + } + } + } + + /* parse_number() + * + * Parse a double. + */ + Json parse_number() { + size_t start_pos = i; + + if (str[i] == '-') + i++; + + // Integer part + if (str[i] == '0') { + i++; + if (in_range(str[i], '0', '9')) + return fail("leading 0s not permitted in numbers"); + } else if (in_range(str[i], '1', '9')) { + i++; + while (in_range(str[i], '0', '9')) + i++; + } else { + return fail("invalid " + esc(str[i]) + " in number"); + } + + if (str[i] != '.' && str[i] != 'e' && str[i] != 'E' + && (i - start_pos) <= static_cast(std::numeric_limits::digits10)) { + return std::atoi(str.c_str() + start_pos); + } + + // Decimal part + if (str[i] == '.') { + i++; + if (!in_range(str[i], '0', '9')) + return fail("at least one digit required in fractional part"); + + while (in_range(str[i], '0', '9')) + i++; + } + + // Exponent part + if (str[i] == 'e' || str[i] == 'E') { + i++; + + if (str[i] == '+' || str[i] == '-') + i++; + + if (!in_range(str[i], '0', '9')) + return fail("at least one digit required in exponent"); + + while (in_range(str[i], '0', '9')) + i++; + } + + return std::strtod(str.c_str() + start_pos, nullptr); + } + + /* expect(str, res) + * + * Expect that 'str' starts at the character that was just read. If it does, advance + * the input and return res. If not, flag an error. + */ + Json expect(const string &expected, Json res) { + assert(i != 0); + i--; + if (str.compare(i, expected.length(), expected) == 0) { + i += expected.length(); + return res; + } else { + return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length())); + } + } + + /* parse_json() + * + * Parse a JSON object. + */ + Json parse_json(int depth) { + if (depth > max_depth) { + return fail("exceeded maximum nesting depth"); + } + + char ch = get_next_token(); + if (failed) + return Json(); + + if (ch == '-' || (ch >= '0' && ch <= '9')) { + i--; + return parse_number(); + } + + if (ch == 't') + return expect("true", true); + + if (ch == 'f') + return expect("false", false); + + if (ch == 'n') + return expect("null", Json()); + + if (ch == '"') + return parse_string(); + + if (ch == '{') { + map data; + ch = get_next_token(); + if (ch == '}') + return data; + + while (1) { + if (ch != '"') + return fail("expected '\"' in object, got " + esc(ch)); + + string key = parse_string(); + if (failed) + return Json(); + + ch = get_next_token(); + if (ch != ':') + return fail("expected ':' in object, got " + esc(ch)); + + data[std::move(key)] = parse_json(depth + 1); + if (failed) + return Json(); + + ch = get_next_token(); + if (ch == '}') + break; + if (ch != ',') + return fail("expected ',' in object, got " + esc(ch)); + + ch = get_next_token(); + } + return data; + } + + if (ch == '[') { + vector data; + ch = get_next_token(); + if (ch == ']') + return data; + + while (1) { + i--; + data.push_back(parse_json(depth + 1)); + if (failed) + return Json(); + + ch = get_next_token(); + if (ch == ']') + break; + if (ch != ',') + return fail("expected ',' in list, got " + esc(ch)); + + ch = get_next_token(); + (void)ch; + } + return data; + } + + return fail("expected value, got " + esc(ch)); + } +}; +}//namespace { + +Json Json::parse(const string &in, string &err, JsonParse strategy) { + JsonParser parser { in, 0, err, false, strategy }; + Json result = parser.parse_json(0); + + // Check for any trailing garbage + parser.consume_garbage(); + if (parser.failed) + return Json(); + if (parser.i != in.size()) + return parser.fail("unexpected trailing " + esc(in[parser.i])); + + return result; +} + +// Documented in json11.hpp +vector Json::parse_multi(const string &in, + std::string::size_type &parser_stop_pos, + string &err, + JsonParse strategy) { + JsonParser parser { in, 0, err, false, strategy }; + parser_stop_pos = 0; + vector json_vec; + while (parser.i != in.size() && !parser.failed) { + json_vec.push_back(parser.parse_json(0)); + if (parser.failed) + break; + + // Check for another object + parser.consume_garbage(); + if (parser.failed) + break; + parser_stop_pos = parser.i; + } + return json_vec; +} + +/* * * * * * * * * * * * * * * * * * * * + * Shape-checking + */ + +bool Json::has_shape(const shape & types, string & err) const { + if (!is_object()) { + err = "expected JSON object, got " + dump(); + return false; + } + + for (auto & item : types) { + if ((*this)[item.first].type() != item.second) { + err = "bad type for " + item.first + " in " + dump(); + return false; + } + } + + return true; +} + +} // namespace json11 diff --git a/deps/json11/json11.hpp b/deps/json11/json11.hpp new file mode 100644 index 000000000..0c47d0509 --- /dev/null +++ b/deps/json11/json11.hpp @@ -0,0 +1,232 @@ +/* json11 + * + * json11 is a tiny JSON library for C++11, providing JSON parsing and serialization. + * + * The core object provided by the library is json11::Json. A Json object represents any JSON + * value: null, bool, number (int or double), string (std::string), array (std::vector), or + * object (std::map). + * + * Json objects act like values: they can be assigned, copied, moved, compared for equality or + * order, etc. There are also helper methods Json::dump, to serialize a Json to a string, and + * Json::parse (static) to parse a std::string as a Json object. + * + * Internally, the various types of Json object are represented by the JsonValue class + * hierarchy. + * + * A note on numbers - JSON specifies the syntax of number formatting but not its semantics, + * so some JSON implementations distinguish between integers and floating-point numbers, while + * some don't. In json11, we choose the latter. Because some JSON implementations (namely + * Javascript itself) treat all numbers as the same type, distinguishing the two leads + * to JSON that will be *silently* changed by a round-trip through those implementations. + * Dangerous! To avoid that risk, json11 stores all numbers as double internally, but also + * provides integer helpers. + * + * Fortunately, double-precision IEEE754 ('double') can precisely store any integer in the + * range +/-2^53, which includes every 'int' on most systems. (Timestamps often use int64 + * or long long to avoid the Y2038K problem; a double storing microseconds since some epoch + * will be exact for +/- 275 years.) + */ + +/* Copyright (c) 2013 Dropbox, Inc. + * + * 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. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#ifdef _MSC_VER + #if _MSC_VER <= 1800 // VS 2013 + #ifndef noexcept + #define noexcept throw() + #endif + + #ifndef snprintf + #define snprintf _snprintf_s + #endif + #endif +#endif + +namespace json11 { + +enum JsonParse { + STANDARD, COMMENTS +}; + +class JsonValue; + +class Json final { +public: + // Types + enum Type { + NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT + }; + + // Array and object typedefs + typedef std::vector array; + typedef std::map object; + + // Constructors for the various types of JSON value. + Json() noexcept; // NUL + Json(std::nullptr_t) noexcept; // NUL + Json(double value); // NUMBER + Json(int value); // NUMBER + Json(bool value); // BOOL + Json(const std::string &value); // STRING + Json(std::string &&value); // STRING + Json(const char * value); // STRING + Json(const array &values); // ARRAY + Json(array &&values); // ARRAY + Json(const object &values); // OBJECT + Json(object &&values); // OBJECT + + // Implicit constructor: anything with a to_json() function. + template + Json(const T & t) : Json(t.to_json()) {} + + // Implicit constructor: map-like objects (std::map, std::unordered_map, etc) + template ().begin()->first)>::value + && std::is_constructible().begin()->second)>::value, + int>::type = 0> + Json(const M & m) : Json(object(m.begin(), m.end())) {} + + // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc) + template ().begin())>::value, + int>::type = 0> + Json(const V & v) : Json(array(v.begin(), v.end())) {} + + // This prevents Json(some_pointer) from accidentally producing a bool. Use + // Json(bool(some_pointer)) if that behavior is desired. + Json(void *) = delete; + + // Accessors + Type type() const; + + bool is_null() const { return type() == NUL; } + bool is_number() const { return type() == NUMBER; } + bool is_bool() const { return type() == BOOL; } + bool is_string() const { return type() == STRING; } + bool is_array() const { return type() == ARRAY; } + bool is_object() const { return type() == OBJECT; } + + // Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not + // distinguish between integer and non-integer numbers - number_value() and int_value() + // can both be applied to a NUMBER-typed object. + double number_value() const; + int int_value() const; + + // Return the enclosed value if this is a boolean, false otherwise. + bool bool_value() const; + // Return the enclosed string if this is a string, "" otherwise. + const std::string &string_value() const; + // Return the enclosed std::vector if this is an array, or an empty vector otherwise. + const array &array_items() const; + // Return the enclosed std::map if this is an object, or an empty map otherwise. + const object &object_items() const; + + // Return a reference to arr[i] if this is an array, Json() otherwise. + const Json & operator[](size_t i) const; + // Return a reference to obj[key] if this is an object, Json() otherwise. + const Json & operator[](const std::string &key) const; + + // Serialize. + void dump(std::string &out) const; + std::string dump() const { + std::string out; + dump(out); + return out; + } + + // Parse. If parse fails, return Json() and assign an error message to err. + static Json parse(const std::string & in, + std::string & err, + JsonParse strategy = JsonParse::STANDARD); + static Json parse(const char * in, + std::string & err, + JsonParse strategy = JsonParse::STANDARD) { + if (in) { + return parse(std::string(in), err, strategy); + } else { + err = "null input"; + return nullptr; + } + } + // Parse multiple objects, concatenated or separated by whitespace + static std::vector parse_multi( + const std::string & in, + std::string::size_type & parser_stop_pos, + std::string & err, + JsonParse strategy = JsonParse::STANDARD); + + static inline std::vector parse_multi( + const std::string & in, + std::string & err, + JsonParse strategy = JsonParse::STANDARD) { + std::string::size_type parser_stop_pos; + return parse_multi(in, parser_stop_pos, err, strategy); + } + + bool operator== (const Json &rhs) const; + bool operator< (const Json &rhs) const; + bool operator!= (const Json &rhs) const { return !(*this == rhs); } + bool operator<= (const Json &rhs) const { return !(rhs < *this); } + bool operator> (const Json &rhs) const { return (rhs < *this); } + bool operator>= (const Json &rhs) const { return !(*this < rhs); } + + /* has_shape(types, err) + * + * Return true if this is a JSON object and, for each item in types, has a field of + * the given type. If not, return false and set err to a descriptive message. + */ + typedef std::initializer_list> shape; + bool has_shape(const shape & types, std::string & err) const; + +private: + std::shared_ptr m_ptr; +}; + +// Internal class hierarchy - JsonValue objects are not exposed to users of this API. +class JsonValue { +protected: + friend class Json; + friend class JsonInt; + friend class JsonDouble; + virtual Json::Type type() const = 0; + virtual bool equals(const JsonValue * other) const = 0; + virtual bool less(const JsonValue * other) const = 0; + virtual void dump(std::string &out) const = 0; + virtual double number_value() const; + virtual int int_value() const; + virtual bool bool_value() const; + virtual const std::string &string_value() const; + virtual const Json::array &array_items() const; + virtual const Json &operator[](size_t i) const; + virtual const Json::object &object_items() const; + virtual const Json &operator[](const std::string &key) const; + virtual ~JsonValue() {} +}; + +} // namespace json11 diff --git a/cef-isolation/browser-render-handler.hpp b/deps/wide-string.cpp similarity index 52% rename from cef-isolation/browser-render-handler.hpp rename to deps/wide-string.cpp index 6fcc1aa5b..b1dc20de7 100644 --- a/cef-isolation/browser-render-handler.hpp +++ b/deps/wide-string.cpp @@ -1,5 +1,5 @@ /****************************************************************************** - Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -15,31 +15,40 @@ along with this program. If not, see . ******************************************************************************/ -#pragma once +#include "wide-string.hpp" +#include -#include +using namespace std; -class BrowserHandle; - -class BrowserRenderHandler : public CefRenderHandler +wstring to_wide(const char *utf8) { -public: + if (!utf8 || !*utf8) + return wstring(); + + size_t isize = strlen(utf8); + size_t osize = os_utf8_to_wcs(utf8, isize, nullptr, 0); - BrowserRenderHandler(std::shared_ptr &browserHandle); + if (!osize) + return wstring(); -public: /* CefRenderHandler overrides */ + wstring wide; + wide.resize(osize); + os_utf8_to_wcs(utf8, isize, &wide[0], osize); + return wide; +} - virtual bool GetViewRect(CefRefPtr browser, CefRect &rect) - OVERRIDE; +wstring to_wide(const std::string &utf8) +{ + if (utf8.empty()) + return wstring(); - virtual void OnPaint(CefRefPtr browser, - PaintElementType type, const RectList &dirtyRects, - const void *buffer, int width, int height) OVERRIDE; + size_t osize = os_utf8_to_wcs(utf8.c_str(), utf8.size(), nullptr, 0); -private: - std::shared_ptr browserHandle; + if (!osize) + return wstring(); -public: - IMPLEMENT_REFCOUNTING(BrowserRenderHandler); - -}; + wstring wide; + wide.resize(osize); + os_utf8_to_wcs(utf8.c_str(), utf8.size(), &wide[0], osize); + return wide; +} diff --git a/shared/browser-settings.hpp b/deps/wide-string.hpp similarity index 81% rename from shared/browser-settings.hpp rename to deps/wide-string.hpp index b590ea50c..9f4ca2003 100644 --- a/shared/browser-settings.hpp +++ b/deps/wide-string.hpp @@ -1,5 +1,5 @@ /****************************************************************************** - Copyright (C) 2014 by John R. Bradley + Copyright (C) 2018 by Hugh Bailey ("Jim") This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -16,13 +16,8 @@ ******************************************************************************/ #pragma once - + #include -struct BrowserSettings { - std::string url; - std::string css; - unsigned int width; - unsigned int height; - unsigned int fps; -}; +extern std::wstring to_wide(const char *utf8); +extern std::wstring to_wide(const std::string &utf8); diff --git a/fmt/format.cc b/fmt/format.cc deleted file mode 100644 index ae5d11034..000000000 --- a/fmt/format.cc +++ /dev/null @@ -1,935 +0,0 @@ -/* - Formatting library for C++ - - Copyright (c) 2012 - 2016, Victor Zverovich - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "format.h" - -#include - -#include -#include -#include -#include -#include -#include // for std::ptrdiff_t - -#if defined(_WIN32) && defined(__MINGW32__) -# include -#endif - -#if FMT_USE_WINDOWS_H -# if defined(NOMINMAX) || defined(FMT_WIN_MINMAX) -# include -# else -# define NOMINMAX -# include -# undef NOMINMAX -# endif -#endif - -using fmt::internal::Arg; - -#if FMT_EXCEPTIONS -# define FMT_TRY try -# define FMT_CATCH(x) catch (x) -#else -# define FMT_TRY if (true) -# define FMT_CATCH(x) if (false) -#endif - -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4127) // conditional expression is constant -# pragma warning(disable: 4702) // unreachable code -// Disable deprecation warning for strerror. The latter is not called but -// MSVC fails to detect it. -# pragma warning(disable: 4996) -#endif - -// Dummy implementations of strerror_r and strerror_s called if corresponding -// system functions are not available. -static inline fmt::internal::Null<> strerror_r(int, char *, ...) { - return fmt::internal::Null<>(); -} -static inline fmt::internal::Null<> strerror_s(char *, std::size_t, ...) { - return fmt::internal::Null<>(); -} - -namespace fmt { -namespace { - -#ifndef _MSC_VER -# define FMT_SNPRINTF snprintf -#else // _MSC_VER -inline int fmt_snprintf(char *buffer, size_t size, const char *format, ...) { - va_list args; - va_start(args, format); - int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args); - va_end(args); - return result; -} -# define FMT_SNPRINTF fmt_snprintf -#endif // _MSC_VER - -#if defined(_WIN32) && defined(__MINGW32__) && !defined(__NO_ISOCEXT) -# define FMT_SWPRINTF snwprintf -#else -# define FMT_SWPRINTF swprintf -#endif // defined(_WIN32) && defined(__MINGW32__) && !defined(__NO_ISOCEXT) - -// Checks if a value fits in int - used to avoid warnings about comparing -// signed and unsigned integers. -template -struct IntChecker { - template - static bool fits_in_int(T value) { - unsigned max = INT_MAX; - return value <= max; - } - static bool fits_in_int(bool) { return true; } -}; - -template <> -struct IntChecker { - template - static bool fits_in_int(T value) { - return value >= INT_MIN && value <= INT_MAX; - } - static bool fits_in_int(int) { return true; } -}; - -const char RESET_COLOR[] = "\x1b[0m"; - -typedef void (*FormatFunc)(Writer &, int, StringRef); - -// Portable thread-safe version of strerror. -// Sets buffer to point to a string describing the error code. -// This can be either a pointer to a string stored in buffer, -// or a pointer to some static immutable string. -// Returns one of the following values: -// 0 - success -// ERANGE - buffer is not large enough to store the error message -// other - failure -// Buffer should be at least of size 1. -int safe_strerror( - int error_code, char *&buffer, std::size_t buffer_size) FMT_NOEXCEPT { - FMT_ASSERT(buffer != 0 && buffer_size != 0, "invalid buffer"); - - class StrError { - private: - int error_code_; - char *&buffer_; - std::size_t buffer_size_; - - // A noop assignment operator to avoid bogus warnings. - void operator=(const StrError &) {} - - // Handle the result of XSI-compliant version of strerror_r. - int handle(int result) { - // glibc versions before 2.13 return result in errno. - return result == -1 ? errno : result; - } - - // Handle the result of GNU-specific version of strerror_r. - int handle(char *message) { - // If the buffer is full then the message is probably truncated. - if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1) - return ERANGE; - buffer_ = message; - return 0; - } - - // Handle the case when strerror_r is not available. - int handle(internal::Null<>) { - return fallback(strerror_s(buffer_, buffer_size_, error_code_)); - } - - // Fallback to strerror_s when strerror_r is not available. - int fallback(int result) { - // If the buffer is full then the message is probably truncated. - return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? - ERANGE : result; - } - - // Fallback to strerror if strerror_r and strerror_s are not available. - int fallback(internal::Null<>) { - errno = 0; - buffer_ = strerror(error_code_); - return errno; - } - - public: - StrError(int err_code, char *&buf, std::size_t buf_size) - : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {} - - int run() { - strerror_r(0, 0, ""); // Suppress a warning about unused strerror_r. - return handle(strerror_r(error_code_, buffer_, buffer_size_)); - } - }; - return StrError(error_code, buffer, buffer_size).run(); -} - -void format_error_code(Writer &out, int error_code, - StringRef message) FMT_NOEXCEPT { - // Report error code making sure that the output fits into - // INLINE_BUFFER_SIZE to avoid dynamic memory allocation and potential - // bad_alloc. - out.clear(); - static const char SEP[] = ": "; - static const char ERROR_STR[] = "error "; - // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. - std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; - typedef internal::IntTraits::MainType MainType; - MainType abs_value = static_cast(error_code); - if (internal::is_negative(error_code)) { - abs_value = 0 - abs_value; - ++error_code_size; - } - error_code_size += internal::count_digits(abs_value); - if (message.size() <= internal::INLINE_BUFFER_SIZE - error_code_size) - out << message << SEP; - out << ERROR_STR << error_code; - assert(out.size() <= internal::INLINE_BUFFER_SIZE); -} - -void report_error(FormatFunc func, int error_code, - StringRef message) FMT_NOEXCEPT { - MemoryWriter full_message; - func(full_message, error_code, message); - // Use Writer::data instead of Writer::c_str to avoid potential memory - // allocation. - std::fwrite(full_message.data(), full_message.size(), 1, stderr); - std::fputc('\n', stderr); -} - -// IsZeroInt::visit(arg) returns true iff arg is a zero integer. -class IsZeroInt : public ArgVisitor { - public: - template - bool visit_any_int(T value) { return value == 0; } -}; - -// Checks if an argument is a valid printf width specifier and sets -// left alignment if it is negative. -class WidthHandler : public ArgVisitor { - private: - FormatSpec &spec_; - - FMT_DISALLOW_COPY_AND_ASSIGN(WidthHandler); - - public: - explicit WidthHandler(FormatSpec &spec) : spec_(spec) {} - - void report_unhandled_arg() { - FMT_THROW(FormatError("width is not integer")); - } - - template - unsigned visit_any_int(T value) { - typedef typename internal::IntTraits::MainType UnsignedType; - UnsignedType width = static_cast(value); - if (internal::is_negative(value)) { - spec_.align_ = ALIGN_LEFT; - width = 0 - width; - } - if (width > INT_MAX) - FMT_THROW(FormatError("number is too big")); - return static_cast(width); - } -}; - -class PrecisionHandler : public ArgVisitor { - public: - void report_unhandled_arg() { - FMT_THROW(FormatError("precision is not integer")); - } - - template - int visit_any_int(T value) { - if (!IntChecker::is_signed>::fits_in_int(value)) - FMT_THROW(FormatError("number is too big")); - return static_cast(value); - } -}; - -template -struct is_same { - enum { value = 0 }; -}; - -template -struct is_same { - enum { value = 1 }; -}; - -// An argument visitor that converts an integer argument to T for printf, -// if T is an integral type. If T is void, the argument is converted to -// corresponding signed or unsigned type depending on the type specifier: -// 'd' and 'i' - signed, other - unsigned) -template -class ArgConverter : public ArgVisitor, void> { - private: - internal::Arg &arg_; - wchar_t type_; - - FMT_DISALLOW_COPY_AND_ASSIGN(ArgConverter); - - public: - ArgConverter(internal::Arg &arg, wchar_t type) - : arg_(arg), type_(type) {} - - void visit_bool(bool value) { - if (type_ != 's') - visit_any_int(value); - } - - template - void visit_any_int(U value) { - bool is_signed = type_ == 'd' || type_ == 'i'; - using internal::Arg; - typedef typename internal::Conditional< - is_same::value, U, T>::type TargetType; - if (sizeof(TargetType) <= sizeof(int)) { - // Extra casts are used to silence warnings. - if (is_signed) { - arg_.type = Arg::INT; - arg_.int_value = static_cast(static_cast(value)); - } else { - arg_.type = Arg::UINT; - typedef typename internal::MakeUnsigned::Type Unsigned; - arg_.uint_value = static_cast(static_cast(value)); - } - } else { - if (is_signed) { - arg_.type = Arg::LONG_LONG; - // glibc's printf doesn't sign extend arguments of smaller types: - // std::printf("%lld", -42); // prints "4294967254" - // but we don't have to do the same because it's a UB. - arg_.long_long_value = static_cast(value); - } else { - arg_.type = Arg::ULONG_LONG; - arg_.ulong_long_value = - static_cast::Type>(value); - } - } - } -}; - -// Converts an integer argument to char for printf. -class CharConverter : public ArgVisitor { - private: - internal::Arg &arg_; - - FMT_DISALLOW_COPY_AND_ASSIGN(CharConverter); - - public: - explicit CharConverter(internal::Arg &arg) : arg_(arg) {} - - template - void visit_any_int(T value) { - arg_.type = internal::Arg::CHAR; - arg_.int_value = static_cast(value); - } -}; -} // namespace - -namespace internal { - -template -class PrintfArgFormatter : - public ArgFormatterBase, Char> { - - void write_null_pointer() { - this->spec().type_ = 0; - this->write("(nil)"); - } - - typedef ArgFormatterBase, Char> Base; - - public: - PrintfArgFormatter(BasicWriter &w, FormatSpec &s) - : ArgFormatterBase, Char>(w, s) {} - - void visit_bool(bool value) { - FormatSpec &fmt_spec = this->spec(); - if (fmt_spec.type_ != 's') - return this->visit_any_int(value); - fmt_spec.type_ = 0; - this->write(value); - } - - void visit_char(int value) { - const FormatSpec &fmt_spec = this->spec(); - BasicWriter &w = this->writer(); - if (fmt_spec.type_ && fmt_spec.type_ != 'c') - w.write_int(value, fmt_spec); - typedef typename BasicWriter::CharPtr CharPtr; - CharPtr out = CharPtr(); - if (fmt_spec.width_ > 1) { - Char fill = ' '; - out = w.grow_buffer(fmt_spec.width_); - if (fmt_spec.align_ != ALIGN_LEFT) { - std::fill_n(out, fmt_spec.width_ - 1, fill); - out += fmt_spec.width_ - 1; - } else { - std::fill_n(out + 1, fmt_spec.width_ - 1, fill); - } - } else { - out = w.grow_buffer(1); - } - *out = static_cast(value); - } - - void visit_cstring(const char *value) { - if (value) - Base::visit_cstring(value); - else if (this->spec().type_ == 'p') - write_null_pointer(); - else - this->write("(null)"); - } - - void visit_pointer(const void *value) { - if (value) - return Base::visit_pointer(value); - this->spec().type_ = 0; - write_null_pointer(); - } - - void visit_custom(Arg::CustomValue c) { - BasicFormatter formatter(ArgList(), this->writer()); - const Char format_str[] = {'}', 0}; - const Char *format = format_str; - c.format(&formatter, c.value, &format); - } -}; -} // namespace internal -} // namespace fmt - -FMT_FUNC void fmt::SystemError::init( - int err_code, CStringRef format_str, ArgList args) { - error_code_ = err_code; - MemoryWriter w; - internal::format_system_error(w, err_code, format(format_str, args)); - std::runtime_error &base = *this; - base = std::runtime_error(w.str()); -} - -template -int fmt::internal::CharTraits::format_float( - char *buffer, std::size_t size, const char *format, - unsigned width, int precision, T value) { - if (width == 0) { - return precision < 0 ? - FMT_SNPRINTF(buffer, size, format, value) : - FMT_SNPRINTF(buffer, size, format, precision, value); - } - return precision < 0 ? - FMT_SNPRINTF(buffer, size, format, width, value) : - FMT_SNPRINTF(buffer, size, format, width, precision, value); -} - -template -int fmt::internal::CharTraits::format_float( - wchar_t *buffer, std::size_t size, const wchar_t *format, - unsigned width, int precision, T value) { - if (width == 0) { - return precision < 0 ? - FMT_SWPRINTF(buffer, size, format, value) : - FMT_SWPRINTF(buffer, size, format, precision, value); - } - return precision < 0 ? - FMT_SWPRINTF(buffer, size, format, width, value) : - FMT_SWPRINTF(buffer, size, format, width, precision, value); -} - -template -const char fmt::internal::BasicData::DIGITS[] = - "0001020304050607080910111213141516171819" - "2021222324252627282930313233343536373839" - "4041424344454647484950515253545556575859" - "6061626364656667686970717273747576777879" - "8081828384858687888990919293949596979899"; - -#define FMT_POWERS_OF_10(factor) \ - factor * 10, \ - factor * 100, \ - factor * 1000, \ - factor * 10000, \ - factor * 100000, \ - factor * 1000000, \ - factor * 10000000, \ - factor * 100000000, \ - factor * 1000000000 - -template -const uint32_t fmt::internal::BasicData::POWERS_OF_10_32[] = { - 0, FMT_POWERS_OF_10(1) -}; - -template -const uint64_t fmt::internal::BasicData::POWERS_OF_10_64[] = { - 0, - FMT_POWERS_OF_10(1), - FMT_POWERS_OF_10(fmt::ULongLong(1000000000)), - // Multiply several constants instead of using a single long long constant - // to avoid warnings about C++98 not supporting long long. - fmt::ULongLong(1000000000) * fmt::ULongLong(1000000000) * 10 -}; - -FMT_FUNC void fmt::internal::report_unknown_type(char code, const char *type) { - (void)type; - if (std::isprint(static_cast(code))) { - FMT_THROW(fmt::FormatError( - fmt::format("unknown format code '{}' for {}", code, type))); - } - FMT_THROW(fmt::FormatError( - fmt::format("unknown format code '\\x{:02x}' for {}", - static_cast(code), type))); -} - -#if FMT_USE_WINDOWS_H - -FMT_FUNC fmt::internal::UTF8ToUTF16::UTF8ToUTF16(fmt::StringRef s) { - static const char ERROR_MSG[] = "cannot convert string from UTF-8 to UTF-16"; - if (s.size() > INT_MAX) - FMT_THROW(WindowsError(ERROR_INVALID_PARAMETER, ERROR_MSG)); - int s_size = static_cast(s.size()); - int length = MultiByteToWideChar( - CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, 0, 0); - if (length == 0) - FMT_THROW(WindowsError(GetLastError(), ERROR_MSG)); - buffer_.resize(length + 1); - length = MultiByteToWideChar( - CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size, &buffer_[0], length); - if (length == 0) - FMT_THROW(WindowsError(GetLastError(), ERROR_MSG)); - buffer_[length] = 0; -} - -FMT_FUNC fmt::internal::UTF16ToUTF8::UTF16ToUTF8(fmt::WStringRef s) { - if (int error_code = convert(s)) { - FMT_THROW(WindowsError(error_code, - "cannot convert string from UTF-16 to UTF-8")); - } -} - -FMT_FUNC int fmt::internal::UTF16ToUTF8::convert(fmt::WStringRef s) { - if (s.size() > INT_MAX) - return ERROR_INVALID_PARAMETER; - int s_size = static_cast(s.size()); - int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, 0, 0, 0, 0); - if (length == 0) - return GetLastError(); - buffer_.resize(length + 1); - length = WideCharToMultiByte( - CP_UTF8, 0, s.data(), s_size, &buffer_[0], length, 0, 0); - if (length == 0) - return GetLastError(); - buffer_[length] = 0; - return 0; -} - -FMT_FUNC void fmt::WindowsError::init( - int err_code, CStringRef format_str, ArgList args) { - error_code_ = err_code; - MemoryWriter w; - internal::format_windows_error(w, err_code, format(format_str, args)); - std::runtime_error &base = *this; - base = std::runtime_error(w.str()); -} - -FMT_FUNC void fmt::internal::format_windows_error( - fmt::Writer &out, int error_code, - fmt::StringRef message) FMT_NOEXCEPT { - FMT_TRY { - MemoryBuffer buffer; - buffer.resize(INLINE_BUFFER_SIZE); - for (;;) { - wchar_t *system_message = &buffer[0]; - int result = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - 0, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - system_message, static_cast(buffer.size()), 0); - if (result != 0) { - UTF16ToUTF8 utf8_message; - if (utf8_message.convert(system_message) == ERROR_SUCCESS) { - out << message << ": " << utf8_message; - return; - } - break; - } - if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) - break; // Can't get error message, report error code instead. - buffer.resize(buffer.size() * 2); - } - } FMT_CATCH(...) {} - fmt::format_error_code(out, error_code, message); // 'fmt::' is for bcc32. -} - -#endif // FMT_USE_WINDOWS_H - -FMT_FUNC void fmt::internal::format_system_error( - fmt::Writer &out, int error_code, - fmt::StringRef message) FMT_NOEXCEPT { - FMT_TRY { - MemoryBuffer buffer; - buffer.resize(INLINE_BUFFER_SIZE); - for (;;) { - char *system_message = &buffer[0]; - int result = safe_strerror(error_code, system_message, buffer.size()); - if (result == 0) { - out << message << ": " << system_message; - return; - } - if (result != ERANGE) - break; // Can't get error message, report error code instead. - buffer.resize(buffer.size() * 2); - } - } FMT_CATCH(...) {} - fmt::format_error_code(out, error_code, message); // 'fmt::' is for bcc32. -} - -template -void fmt::internal::ArgMap::init(const ArgList &args) { - if (!map_.empty()) - return; - typedef internal::NamedArg NamedArg; - const NamedArg *named_arg = 0; - bool use_values = - args.type(ArgList::MAX_PACKED_ARGS - 1) == internal::Arg::NONE; - if (use_values) { - for (unsigned i = 0;/*nothing*/; ++i) { - internal::Arg::Type arg_type = args.type(i); - switch (arg_type) { - case internal::Arg::NONE: - return; - case internal::Arg::NAMED_ARG: - named_arg = static_cast(args.values_[i].pointer); - map_.push_back(Pair(named_arg->name, *named_arg)); - break; - default: - /*nothing*/; - } - } - return; - } - for (unsigned i = 0; i != ArgList::MAX_PACKED_ARGS; ++i) { - internal::Arg::Type arg_type = args.type(i); - if (arg_type == internal::Arg::NAMED_ARG) { - named_arg = static_cast(args.args_[i].pointer); - map_.push_back(Pair(named_arg->name, *named_arg)); - } - } - for (unsigned i = ArgList::MAX_PACKED_ARGS;/*nothing*/; ++i) { - switch (args.args_[i].type) { - case internal::Arg::NONE: - return; - case internal::Arg::NAMED_ARG: - named_arg = static_cast(args.args_[i].pointer); - map_.push_back(Pair(named_arg->name, *named_arg)); - break; - default: - /*nothing*/; - } - } -} - -template -void fmt::internal::FixedBuffer::grow(std::size_t) { - FMT_THROW(std::runtime_error("buffer overflow")); -} - -FMT_FUNC Arg fmt::internal::FormatterBase::do_get_arg( - unsigned arg_index, const char *&error) { - Arg arg = args_[arg_index]; - switch (arg.type) { - case Arg::NONE: - error = "argument index out of range"; - break; - case Arg::NAMED_ARG: - arg = *static_cast(arg.pointer); - break; - default: - /*nothing*/; - } - return arg; -} - -template -void fmt::internal::PrintfFormatter::parse_flags( - FormatSpec &spec, const Char *&s) { - for (;;) { - switch (*s++) { - case '-': - spec.align_ = ALIGN_LEFT; - break; - case '+': - spec.flags_ |= SIGN_FLAG | PLUS_FLAG; - break; - case '0': - spec.fill_ = '0'; - break; - case ' ': - spec.flags_ |= SIGN_FLAG; - break; - case '#': - spec.flags_ |= HASH_FLAG; - break; - default: - --s; - return; - } - } -} - -template -Arg fmt::internal::PrintfFormatter::get_arg( - const Char *s, unsigned arg_index) { - (void)s; - const char *error = 0; - Arg arg = arg_index == UINT_MAX ? - next_arg(error) : FormatterBase::get_arg(arg_index - 1, error); - if (error) - FMT_THROW(FormatError(!*s ? "invalid format string" : error)); - return arg; -} - -template -unsigned fmt::internal::PrintfFormatter::parse_header( - const Char *&s, FormatSpec &spec) { - unsigned arg_index = UINT_MAX; - Char c = *s; - if (c >= '0' && c <= '9') { - // Parse an argument index (if followed by '$') or a width possibly - // preceded with '0' flag(s). - unsigned value = parse_nonnegative_int(s); - if (*s == '$') { // value is an argument index - ++s; - arg_index = value; - } else { - if (c == '0') - spec.fill_ = '0'; - if (value != 0) { - // Nonzero value means that we parsed width and don't need to - // parse it or flags again, so return now. - spec.width_ = value; - return arg_index; - } - } - } - parse_flags(spec, s); - // Parse width. - if (*s >= '0' && *s <= '9') { - spec.width_ = parse_nonnegative_int(s); - } else if (*s == '*') { - ++s; - spec.width_ = WidthHandler(spec).visit(get_arg(s)); - } - return arg_index; -} - -template -void fmt::internal::PrintfFormatter::format( - BasicWriter &writer, BasicCStringRef format_str) { - const Char *start = format_str.c_str(); - const Char *s = start; - while (*s) { - Char c = *s++; - if (c != '%') continue; - if (*s == c) { - write(writer, start, s); - start = ++s; - continue; - } - write(writer, start, s - 1); - - FormatSpec spec; - spec.align_ = ALIGN_RIGHT; - - // Parse argument index, flags and width. - unsigned arg_index = parse_header(s, spec); - - // Parse precision. - if (*s == '.') { - ++s; - if ('0' <= *s && *s <= '9') { - spec.precision_ = static_cast(parse_nonnegative_int(s)); - } else if (*s == '*') { - ++s; - spec.precision_ = PrecisionHandler().visit(get_arg(s)); - } - } - - Arg arg = get_arg(s, arg_index); - if (spec.flag(HASH_FLAG) && IsZeroInt().visit(arg)) - spec.flags_ &= ~to_unsigned(HASH_FLAG); - if (spec.fill_ == '0') { - if (arg.type <= Arg::LAST_NUMERIC_TYPE) - spec.align_ = ALIGN_NUMERIC; - else - spec.fill_ = ' '; // Ignore '0' flag for non-numeric types. - } - - // Parse length and convert the argument to the required type. - switch (*s++) { - case 'h': - if (*s == 'h') - ArgConverter(arg, *++s).visit(arg); - else - ArgConverter(arg, *s).visit(arg); - break; - case 'l': - if (*s == 'l') - ArgConverter(arg, *++s).visit(arg); - else - ArgConverter(arg, *s).visit(arg); - break; - case 'j': - ArgConverter(arg, *s).visit(arg); - break; - case 'z': - ArgConverter(arg, *s).visit(arg); - break; - case 't': - ArgConverter(arg, *s).visit(arg); - break; - case 'L': - // printf produces garbage when 'L' is omitted for long double, no - // need to do the same. - break; - default: - --s; - ArgConverter(arg, *s).visit(arg); - } - - // Parse type. - if (!*s) - FMT_THROW(FormatError("invalid format string")); - spec.type_ = static_cast(*s++); - if (arg.type <= Arg::LAST_INTEGER_TYPE) { - // Normalize type. - switch (spec.type_) { - case 'i': case 'u': - spec.type_ = 'd'; - break; - case 'c': - // TODO: handle wchar_t - CharConverter(arg).visit(arg); - break; - } - } - - start = s; - - // Format argument. - internal::PrintfArgFormatter(writer, spec).visit(arg); - } - write(writer, start, s); -} - -FMT_FUNC void fmt::report_system_error( - int error_code, fmt::StringRef message) FMT_NOEXCEPT { - // 'fmt::' is for bcc32. - fmt::report_error(internal::format_system_error, error_code, message); -} - -#if FMT_USE_WINDOWS_H -FMT_FUNC void fmt::report_windows_error( - int error_code, fmt::StringRef message) FMT_NOEXCEPT { - // 'fmt::' is for bcc32. - fmt::report_error(internal::format_windows_error, error_code, message); -} -#endif - -FMT_FUNC void fmt::print(std::FILE *f, CStringRef format_str, ArgList args) { - MemoryWriter w; - w.write(format_str, args); - std::fwrite(w.data(), 1, w.size(), f); -} - -FMT_FUNC void fmt::print(CStringRef format_str, ArgList args) { - print(stdout, format_str, args); -} - -FMT_FUNC void fmt::print_colored(Color c, CStringRef format, ArgList args) { - char escape[] = "\x1b[30m"; - escape[3] = static_cast('0' + c); - std::fputs(escape, stdout); - print(format, args); - std::fputs(RESET_COLOR, stdout); -} - -FMT_FUNC int fmt::fprintf(std::FILE *f, CStringRef format, ArgList args) { - MemoryWriter w; - printf(w, format, args); - std::size_t size = w.size(); - return std::fwrite(w.data(), 1, size, f) < size ? -1 : static_cast(size); -} - -#ifndef FMT_HEADER_ONLY - -template struct fmt::internal::BasicData; - -// Explicit instantiations for char. - -template void fmt::internal::FixedBuffer::grow(std::size_t); - -template void fmt::internal::ArgMap::init(const fmt::ArgList &args); - -template void fmt::internal::PrintfFormatter::format( - BasicWriter &writer, CStringRef format); - -template int fmt::internal::CharTraits::format_float( - char *buffer, std::size_t size, const char *format, - unsigned width, int precision, double value); - -template int fmt::internal::CharTraits::format_float( - char *buffer, std::size_t size, const char *format, - unsigned width, int precision, long double value); - -// Explicit instantiations for wchar_t. - -template void fmt::internal::FixedBuffer::grow(std::size_t); - -template void fmt::internal::ArgMap::init(const fmt::ArgList &args); - -template void fmt::internal::PrintfFormatter::format( - BasicWriter &writer, WCStringRef format); - -template int fmt::internal::CharTraits::format_float( - wchar_t *buffer, std::size_t size, const wchar_t *format, - unsigned width, int precision, double value); - -template int fmt::internal::CharTraits::format_float( - wchar_t *buffer, std::size_t size, const wchar_t *format, - unsigned width, int precision, long double value); - -#endif // FMT_HEADER_ONLY - -#ifdef _MSC_VER -# pragma warning(pop) -#endif diff --git a/fmt/format.h b/fmt/format.h deleted file mode 100644 index 5013b8108..000000000 --- a/fmt/format.h +++ /dev/null @@ -1,3832 +0,0 @@ -/* - Formatting library for C++ - - Copyright (c) 2012 - 2016, Victor Zverovich - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FMT_FORMAT_H_ -#define FMT_FORMAT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _SECURE_SCL -# define FMT_SECURE_SCL _SECURE_SCL -#else -# define FMT_SECURE_SCL 0 -#endif - -#if FMT_SECURE_SCL -# include -#endif - -#if defined(_MSC_VER) && _MSC_VER <= 1500 -typedef unsigned __int32 uint32_t; -typedef unsigned __int64 uint64_t; -typedef __int64 intmax_t; -#else -#include -#endif - -#if !defined(FMT_HEADER_ONLY) && defined(_WIN32) -# ifdef FMT_EXPORT -# define FMT_API __declspec(dllexport) -# elif defined(FMT_SHARED) -# define FMT_API __declspec(dllimport) -# endif -#endif -#ifndef FMT_API -# define FMT_API -#endif - -#ifdef __GNUC__ -# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -# define FMT_GCC_EXTENSION __extension__ -# if FMT_GCC_VERSION >= 406 -# pragma GCC diagnostic push -// Disable the warning about "long long" which is sometimes reported even -// when using __extension__. -# pragma GCC diagnostic ignored "-Wlong-long" -// Disable the warning about declaration shadowing because it affects too -// many valid cases. -# pragma GCC diagnostic ignored "-Wshadow" -// Disable the warning about implicit conversions that may change the sign of -// an integer; silencing it otherwise would require many explicit casts. -# pragma GCC diagnostic ignored "-Wsign-conversion" -# endif -# if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ -# define FMT_HAS_GXX_CXX11 1 -# endif -#else -# define FMT_GCC_EXTENSION -#endif - -#if defined(__INTEL_COMPILER) -# define FMT_ICC_VERSION __INTEL_COMPILER -#elif defined(__ICL) -# define FMT_ICC_VERSION __ICL -#endif - -#if defined(__clang__) && !defined(FMT_ICC_VERSION) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdocumentation" -#endif - -#ifdef __GNUC_LIBSTD__ -# define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) -#endif - -#ifdef __has_feature -# define FMT_HAS_FEATURE(x) __has_feature(x) -#else -# define FMT_HAS_FEATURE(x) 0 -#endif - -#ifdef __has_builtin -# define FMT_HAS_BUILTIN(x) __has_builtin(x) -#else -# define FMT_HAS_BUILTIN(x) 0 -#endif - -#ifdef __has_cpp_attribute -# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) -#else -# define FMT_HAS_CPP_ATTRIBUTE(x) 0 -#endif - -#ifndef FMT_USE_VARIADIC_TEMPLATES -// Variadic templates are available in GCC since version 4.4 -// (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++ -// since version 2013. -# define FMT_USE_VARIADIC_TEMPLATES \ - (FMT_HAS_FEATURE(cxx_variadic_templates) || \ - (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1800) -#endif - -#ifndef FMT_USE_RVALUE_REFERENCES -// Don't use rvalue references when compiling with clang and an old libstdc++ -// as the latter doesn't provide std::move. -# if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 -# define FMT_USE_RVALUE_REFERENCES 0 -# else -# define FMT_USE_RVALUE_REFERENCES \ - (FMT_HAS_FEATURE(cxx_rvalue_references) || \ - (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600) -# endif -#endif - -#if FMT_USE_RVALUE_REFERENCES -# include // for std::move -#endif - -// Check if exceptions are disabled. -#if defined(__GNUC__) && !defined(__EXCEPTIONS) -# define FMT_EXCEPTIONS 0 -#endif -#if defined(_MSC_VER) && !_HAS_EXCEPTIONS -# define FMT_EXCEPTIONS 0 -#endif -#ifndef FMT_EXCEPTIONS -# define FMT_EXCEPTIONS 1 -#endif - -#ifndef FMT_THROW -# if FMT_EXCEPTIONS -# define FMT_THROW(x) throw x -# else -# define FMT_THROW(x) assert(false) -# endif -#endif - -// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). -#ifndef FMT_USE_NOEXCEPT -# define FMT_USE_NOEXCEPT 0 -#endif - -#ifndef FMT_NOEXCEPT -# if FMT_EXCEPTIONS -# if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ - (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ - _MSC_VER >= 1900 -# define FMT_NOEXCEPT noexcept -# else -# define FMT_NOEXCEPT throw() -# endif -# else -# define FMT_NOEXCEPT -# endif -#endif - -// A macro to disallow the copy constructor and operator= functions -// This should be used in the private: declarations for a class -#ifndef FMT_USE_DELETED_FUNCTIONS -# define FMT_USE_DELETED_FUNCTIONS 0 -#endif - -#if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \ - (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1800 -# define FMT_DELETED_OR_UNDEFINED = delete -# define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&) = delete; \ - TypeName& operator=(const TypeName&) = delete -#else -# define FMT_DELETED_OR_UNDEFINED -# define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - TypeName& operator=(const TypeName&) -#endif - -#ifndef FMT_USE_USER_DEFINED_LITERALS -// All compilers which support UDLs also support variadic templates. This -// makes the fmt::literals implementation easier. However, an explicit check -// for variadic templates is added here just in case. -// For Intel's compiler both it and the system gcc/msc must support UDLs. -# define FMT_USE_USER_DEFINED_LITERALS \ - FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \ - (FMT_HAS_FEATURE(cxx_user_literals) || \ - (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1900) && \ - (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500) -#endif - -#ifndef FMT_ASSERT -# define FMT_ASSERT(condition, message) assert((condition) && message) -#endif - - -#if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) -# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) -#endif - -#if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) -# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) -#endif - -// Some compilers masquerade as both MSVC and GCC-likes or -// otherwise support __builtin_clz and __builtin_clzll, so -// only define FMT_BUILTIN_CLZ using the MSVC intrinsics -// if the clz and clzll builtins are not available. -#if defined(_MSC_VER) && !defined(FMT_BUILTIN_CLZLL) -# include // _BitScanReverse, _BitScanReverse64 - -namespace fmt { -namespace internal { -# pragma intrinsic(_BitScanReverse) -inline uint32_t clz(uint32_t x) { - unsigned long r = 0; - _BitScanReverse(&r, x); - - assert(x != 0); - // Static analysis complains about using uninitialized data - // "r", but the only way that can happen is if "x" is 0, - // which the callers guarantee to not happen. -# pragma warning(suppress: 6102) - return 31 - r; -} -# define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) - -# ifdef _WIN64 -# pragma intrinsic(_BitScanReverse64) -# endif - -inline uint32_t clzll(uint64_t x) { - unsigned long r = 0; -# ifdef _WIN64 - _BitScanReverse64(&r, x); -# else - // Scan the high 32 bits. - if (_BitScanReverse(&r, static_cast(x >> 32))) - return 63 - (r + 32); - - // Scan the low 32 bits. - _BitScanReverse(&r, static_cast(x)); -# endif - - assert(x != 0); - // Static analysis complains about using uninitialized data - // "r", but the only way that can happen is if "x" is 0, - // which the callers guarantee to not happen. -# pragma warning(suppress: 6102) - return 63 - r; -} -# define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) -} -} -#endif - -namespace fmt { -namespace internal { -struct DummyInt { - int data[2]; - operator int() const { return 0; } -}; -typedef std::numeric_limits FPUtil; - -// Dummy implementations of system functions such as signbit and ecvt called -// if the latter are not available. -inline DummyInt signbit(...) { return DummyInt(); } -inline DummyInt _ecvt_s(...) { return DummyInt(); } -inline DummyInt isinf(...) { return DummyInt(); } -inline DummyInt _finite(...) { return DummyInt(); } -inline DummyInt isnan(...) { return DummyInt(); } -inline DummyInt _isnan(...) { return DummyInt(); } - -// A helper function to suppress bogus "conditional expression is constant" -// warnings. -template -inline T check(T value) { return value; } -} -} // namespace fmt - -namespace std { -// Standard permits specialization of std::numeric_limits. This specialization -// is used to resolve ambiguity between isinf and std::isinf in glibc: -// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 -// and the same for isnan and signbit. -template <> -class numeric_limits : - public std::numeric_limits { - public: - // Portable version of isinf. - template - static bool isinfinity(T x) { - using namespace fmt::internal; - // The resolution "priority" is: - // isinf macro > std::isinf > ::isinf > fmt::internal::isinf - if (check(sizeof(isinf(x)) == sizeof(bool) || - sizeof(isinf(x)) == sizeof(int))) { - return isinf(x) != 0; - } - return !_finite(static_cast(x)); - } - - // Portable version of isnan. - template - static bool isnotanumber(T x) { - using namespace fmt::internal; - if (check(sizeof(isnan(x)) == sizeof(bool) || - sizeof(isnan(x)) == sizeof(int))) { - return isnan(x) != 0; - } - return _isnan(static_cast(x)) != 0; - } - - // Portable version of signbit. - static bool isnegative(double x) { - using namespace fmt::internal; - if (check(sizeof(signbit(x)) == sizeof(int))) - return signbit(x) != 0; - if (x < 0) return true; - if (!isnotanumber(x)) return false; - int dec = 0, sign = 0; - char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. - _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign); - return sign != 0; - } -}; -} // namespace std - -namespace fmt { - -// Fix the warning about long long on older versions of GCC -// that don't support the diagnostic pragma. -FMT_GCC_EXTENSION typedef long long LongLong; -FMT_GCC_EXTENSION typedef unsigned long long ULongLong; - -#if FMT_USE_RVALUE_REFERENCES -using std::move; -#endif - -template -class BasicWriter; - -typedef BasicWriter Writer; -typedef BasicWriter WWriter; - -template -class ArgFormatter; - -template > -class BasicFormatter; - -/** - \rst - A string reference. It can be constructed from a C string or ``std::string``. - - You can use one of the following typedefs for common character types: - - +------------+-------------------------+ - | Type | Definition | - +============+=========================+ - | StringRef | BasicStringRef | - +------------+-------------------------+ - | WStringRef | BasicStringRef | - +------------+-------------------------+ - - This class is most useful as a parameter type to allow passing - different types of strings to a function, for example:: - - template - std::string format(StringRef format_str, const Args & ... args); - - format("{}", 42); - format(std::string("{}"), 42); - \endrst - */ -template -class BasicStringRef { - private: - const Char *data_; - std::size_t size_; - - public: - /** Constructs a string reference object from a C string and a size. */ - BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {} - - /** - \rst - Constructs a string reference object from a C string computing - the size with ``std::char_traits::length``. - \endrst - */ - BasicStringRef(const Char *s) - : data_(s), size_(std::char_traits::length(s)) {} - - /** - \rst - Constructs a string reference from an ``std::string`` object. - \endrst - */ - BasicStringRef(const std::basic_string &s) - : data_(s.c_str()), size_(s.size()) {} - - /** - \rst - Converts a string reference to an ``std::string`` object. - \endrst - */ - std::basic_string to_string() const { - return std::basic_string(data_, size_); - } - - /** Returns a pointer to the string data. */ - const Char *data() const { return data_; } - - /** Returns the string size. */ - std::size_t size() const { return size_; } - - // Lexicographically compare this string reference to other. - int compare(BasicStringRef other) const { - std::size_t size = size_ < other.size_ ? size_ : other.size_; - int result = std::char_traits::compare(data_, other.data_, size); - if (result == 0) - result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); - return result; - } - - friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) { - return lhs.compare(rhs) == 0; - } - friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) { - return lhs.compare(rhs) != 0; - } - friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) { - return lhs.compare(rhs) < 0; - } - friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) { - return lhs.compare(rhs) <= 0; - } - friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) { - return lhs.compare(rhs) > 0; - } - friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) { - return lhs.compare(rhs) >= 0; - } -}; - -typedef BasicStringRef StringRef; -typedef BasicStringRef WStringRef; - -/** - \rst - A reference to a null terminated string. It can be constructed from a C - string or ``std::string``. - - You can use one of the following typedefs for common character types: - - +-------------+--------------------------+ - | Type | Definition | - +=============+==========================+ - | CStringRef | BasicCStringRef | - +-------------+--------------------------+ - | WCStringRef | BasicCStringRef | - +-------------+--------------------------+ - - This class is most useful as a parameter type to allow passing - different types of strings to a function, for example:: - - template - std::string format(CStringRef format_str, const Args & ... args); - - format("{}", 42); - format(std::string("{}"), 42); - \endrst - */ -template -class BasicCStringRef { - private: - const Char *data_; - - public: - /** Constructs a string reference object from a C string. */ - BasicCStringRef(const Char *s) : data_(s) {} - - /** - \rst - Constructs a string reference from an ``std::string`` object. - \endrst - */ - BasicCStringRef(const std::basic_string &s) : data_(s.c_str()) {} - - /** Returns the pointer to a C string. */ - const Char *c_str() const { return data_; } -}; - -typedef BasicCStringRef CStringRef; -typedef BasicCStringRef WCStringRef; - -/** - A formatting error such as invalid format string. -*/ -class FormatError : public std::runtime_error { - public: - explicit FormatError(CStringRef message) - : std::runtime_error(message.c_str()) {} -}; - -namespace internal { - -// MakeUnsigned::Type gives an unsigned type corresponding to integer type T. -template -struct MakeUnsigned { typedef T Type; }; - -#define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ - template <> \ - struct MakeUnsigned { typedef U Type; } - -FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char); -FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char); -FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short); -FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned); -FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); -FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); - -// Casts nonnegative integer to unsigned. -template -inline typename MakeUnsigned::Type to_unsigned(Int value) { - FMT_ASSERT(value >= 0, "negative value"); - return static_cast::Type>(value); -} - -// The number of characters to store in the MemoryBuffer object itself -// to avoid dynamic memory allocation. -enum { INLINE_BUFFER_SIZE = 500 }; - -#if FMT_SECURE_SCL -// Use checked iterator to avoid warnings on MSVC. -template -inline stdext::checked_array_iterator make_ptr(T *ptr, std::size_t size) { - return stdext::checked_array_iterator(ptr, size); -} -#else -template -inline T *make_ptr(T *ptr, std::size_t) { return ptr; } -#endif -} // namespace internal - -/** - \rst - A buffer supporting a subset of ``std::vector``'s operations. - \endrst - */ -template -class Buffer { - private: - FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); - - protected: - T *ptr_; - std::size_t size_; - std::size_t capacity_; - - Buffer(T *ptr = 0, std::size_t capacity = 0) - : ptr_(ptr), size_(0), capacity_(capacity) {} - - /** - \rst - Increases the buffer capacity to hold at least *size* elements updating - ``ptr_`` and ``capacity_``. - \endrst - */ - virtual void grow(std::size_t size) = 0; - - public: - virtual ~Buffer() {} - - /** Returns the size of this buffer. */ - std::size_t size() const { return size_; } - - /** Returns the capacity of this buffer. */ - std::size_t capacity() const { return capacity_; } - - /** - Resizes the buffer. If T is a POD type new elements may not be initialized. - */ - void resize(std::size_t new_size) { - if (new_size > capacity_) - grow(new_size); - size_ = new_size; - } - - /** - \rst - Reserves space to store at least *capacity* elements. - \endrst - */ - void reserve(std::size_t capacity) { - if (capacity > capacity_) - grow(capacity); - } - - void clear() FMT_NOEXCEPT { size_ = 0; } - - void push_back(const T &value) { - if (size_ == capacity_) - grow(size_ + 1); - ptr_[size_++] = value; - } - - /** Appends data to the end of the buffer. */ - template - void append(const U *begin, const U *end); - - T &operator[](std::size_t index) { return ptr_[index]; } - const T &operator[](std::size_t index) const { return ptr_[index]; } -}; - -template -template -void Buffer::append(const U *begin, const U *end) { - std::size_t new_size = size_ + internal::to_unsigned(end - begin); - if (new_size > capacity_) - grow(new_size); - std::uninitialized_copy(begin, end, - internal::make_ptr(ptr_, capacity_) + size_); - size_ = new_size; -} - -namespace internal { - -// A memory buffer for trivially copyable/constructible types with the first SIZE -// elements stored in the object itself. -template > -class MemoryBuffer : private Allocator, public Buffer { - private: - T data_[SIZE]; - - // Deallocate memory allocated by the buffer. - void deallocate() { - if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_); - } - - protected: - void grow(std::size_t size); - - public: - explicit MemoryBuffer(const Allocator &alloc = Allocator()) - : Allocator(alloc), Buffer(data_, SIZE) {} - ~MemoryBuffer() { deallocate(); } - -#if FMT_USE_RVALUE_REFERENCES - private: - // Move data from other to this buffer. - void move(MemoryBuffer &other) { - Allocator &this_alloc = *this, &other_alloc = other; - this_alloc = std::move(other_alloc); - this->size_ = other.size_; - this->capacity_ = other.capacity_; - if (other.ptr_ == other.data_) { - this->ptr_ = data_; - std::uninitialized_copy(other.data_, other.data_ + this->size_, - make_ptr(data_, this->capacity_)); - } else { - this->ptr_ = other.ptr_; - // Set pointer to the inline array so that delete is not called - // when deallocating. - other.ptr_ = other.data_; - } - } - - public: - MemoryBuffer(MemoryBuffer &&other) { - move(other); - } - - MemoryBuffer &operator=(MemoryBuffer &&other) { - assert(this != &other); - deallocate(); - move(other); - return *this; - } -#endif - - // Returns a copy of the allocator associated with this buffer. - Allocator get_allocator() const { return *this; } -}; - -template -void MemoryBuffer::grow(std::size_t size) { - std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; - if (size > new_capacity) - new_capacity = size; - T *new_ptr = this->allocate(new_capacity); - // The following code doesn't throw, so the raw pointer above doesn't leak. - std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_, - make_ptr(new_ptr, new_capacity)); - std::size_t old_capacity = this->capacity_; - T *old_ptr = this->ptr_; - this->capacity_ = new_capacity; - this->ptr_ = new_ptr; - // deallocate may throw (at least in principle), but it doesn't matter since - // the buffer already uses the new storage and will deallocate it in case - // of exception. - if (old_ptr != data_) - Allocator::deallocate(old_ptr, old_capacity); -} - -// A fixed-size buffer. -template -class FixedBuffer : public fmt::Buffer { - public: - FixedBuffer(Char *array, std::size_t size) : fmt::Buffer(array, size) {} - - protected: - FMT_API void grow(std::size_t size); -}; - -template -class BasicCharTraits { - public: -#if FMT_SECURE_SCL - typedef stdext::checked_array_iterator CharPtr; -#else - typedef Char *CharPtr; -#endif - static Char cast(int value) { return static_cast(value); } -}; - -template -class CharTraits; - -template <> -class CharTraits : public BasicCharTraits { - private: - // Conversion from wchar_t to char is not allowed. - static char convert(wchar_t); - - public: - static char convert(char value) { return value; } - - // Formats a floating-point number. - template - FMT_API static int format_float(char *buffer, std::size_t size, - const char *format, unsigned width, int precision, T value); -}; - -template <> -class CharTraits : public BasicCharTraits { - public: - static wchar_t convert(char value) { return value; } - static wchar_t convert(wchar_t value) { return value; } - - template - FMT_API static int format_float(wchar_t *buffer, std::size_t size, - const wchar_t *format, unsigned width, int precision, T value); -}; - -// Checks if a number is negative - used to avoid warnings. -template -struct SignChecker { - template - static bool is_negative(T value) { return value < 0; } -}; - -template <> -struct SignChecker { - template - static bool is_negative(T) { return false; } -}; - -// Returns true if value is negative, false otherwise. -// Same as (value < 0) but doesn't produce warnings if T is an unsigned type. -template -inline bool is_negative(T value) { - return SignChecker::is_signed>::is_negative(value); -} - -// Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. -template -struct TypeSelector { typedef uint32_t Type; }; - -template <> -struct TypeSelector { typedef uint64_t Type; }; - -template -struct IntTraits { - // Smallest of uint32_t and uint64_t that is large enough to represent - // all values of T. - typedef typename - TypeSelector::digits <= 32>::Type MainType; -}; - -FMT_API void report_unknown_type(char code, const char *type); - -// Static data is placed in this class template to allow header-only -// configuration. -template -struct FMT_API BasicData { - static const uint32_t POWERS_OF_10_32[]; - static const uint64_t POWERS_OF_10_64[]; - static const char DIGITS[]; -}; - -typedef BasicData<> Data; - -#ifdef FMT_BUILTIN_CLZLL -// Returns the number of decimal digits in n. Leading zeros are not counted -// except for n == 0 in which case count_digits returns 1. -inline unsigned count_digits(uint64_t n) { - // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 - // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. - int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; - return to_unsigned(t) - (n < Data::POWERS_OF_10_64[t]) + 1; -} -#else -// Fallback version of count_digits used when __builtin_clz is not available. -inline unsigned count_digits(uint64_t n) { - unsigned count = 1; - for (;;) { - // Integer division is slow so do it for a group of four digits instead - // of for every digit. The idea comes from the talk by Alexandrescu - // "Three Optimization Tips for C++". See speed-test for a comparison. - if (n < 10) return count; - if (n < 100) return count + 1; - if (n < 1000) return count + 2; - if (n < 10000) return count + 3; - n /= 10000u; - count += 4; - } -} -#endif - -#ifdef FMT_BUILTIN_CLZ -// Optional version of count_digits for better performance on 32-bit platforms. -inline unsigned count_digits(uint32_t n) { - int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; - return to_unsigned(t) - (n < Data::POWERS_OF_10_32[t]) + 1; -} -#endif - -// A functor that doesn't add a thousands separator. -struct NoThousandsSep { - template - void operator()(Char *) {} -}; - -// A functor that adds a thousands separator. -class ThousandsSep { - private: - fmt::StringRef sep_; - - // Index of a decimal digit with the least significant digit having index 0. - unsigned digit_index_; - - public: - explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {} - - template - void operator()(Char *&buffer) { - if (++digit_index_ % 3 != 0) - return; - buffer -= sep_.size(); - std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), - internal::make_ptr(buffer, sep_.size())); - } -}; - -// Formats a decimal unsigned integer value writing into buffer. -// thousands_sep is a functor that is called after writing each char to -// add a thousands separator if necessary. -template -inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, - ThousandsSep thousands_sep) { - buffer += num_digits; - while (value >= 100) { - // Integer division is slow so do it for a group of two digits instead - // of for every digit. The idea comes from the talk by Alexandrescu - // "Three Optimization Tips for C++". See speed-test for a comparison. - unsigned index = static_cast((value % 100) * 2); - value /= 100; - *--buffer = Data::DIGITS[index + 1]; - thousands_sep(buffer); - *--buffer = Data::DIGITS[index]; - thousands_sep(buffer); - } - if (value < 10) { - *--buffer = static_cast('0' + value); - return; - } - unsigned index = static_cast(value * 2); - *--buffer = Data::DIGITS[index + 1]; - *--buffer = Data::DIGITS[index]; -} - -template -inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { - return format_decimal(buffer, value, num_digits, NoThousandsSep()); -} - -#ifndef _WIN32 -# define FMT_USE_WINDOWS_H 0 -#elif !defined(FMT_USE_WINDOWS_H) -# define FMT_USE_WINDOWS_H 1 -#endif - -// Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h. -// All the functionality that relies on it will be disabled too. -#if FMT_USE_WINDOWS_H -// A converter from UTF-8 to UTF-16. -// It is only provided for Windows since other systems support UTF-8 natively. -class UTF8ToUTF16 { - private: - MemoryBuffer buffer_; - - public: - FMT_API explicit UTF8ToUTF16(StringRef s); - operator WStringRef() const { return WStringRef(&buffer_[0], size()); } - size_t size() const { return buffer_.size() - 1; } - const wchar_t *c_str() const { return &buffer_[0]; } - std::wstring str() const { return std::wstring(&buffer_[0], size()); } -}; - -// A converter from UTF-16 to UTF-8. -// It is only provided for Windows since other systems support UTF-8 natively. -class UTF16ToUTF8 { - private: - MemoryBuffer buffer_; - - public: - UTF16ToUTF8() {} - FMT_API explicit UTF16ToUTF8(WStringRef s); - operator StringRef() const { return StringRef(&buffer_[0], size()); } - size_t size() const { return buffer_.size() - 1; } - const char *c_str() const { return &buffer_[0]; } - std::string str() const { return std::string(&buffer_[0], size()); } - - // Performs conversion returning a system error code instead of - // throwing exception on conversion error. This method may still throw - // in case of memory allocation error. - FMT_API int convert(WStringRef s); -}; - -FMT_API void format_windows_error(fmt::Writer &out, int error_code, - fmt::StringRef message) FMT_NOEXCEPT; -#endif - -FMT_API void format_system_error(fmt::Writer &out, int error_code, - fmt::StringRef message) FMT_NOEXCEPT; - -// A formatting argument value. -struct Value { - template - struct StringValue { - const Char *value; - std::size_t size; - }; - - typedef void (*FormatFunc)( - void *formatter, const void *arg, void *format_str_ptr); - - struct CustomValue { - const void *value; - FormatFunc format; - }; - - union { - int int_value; - unsigned uint_value; - LongLong long_long_value; - ULongLong ulong_long_value; - double double_value; - long double long_double_value; - const void *pointer; - StringValue string; - StringValue sstring; - StringValue ustring; - StringValue wstring; - CustomValue custom; - }; - - enum Type { - NONE, NAMED_ARG, - // Integer types should go first, - INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR, - // followed by floating-point types. - DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE, - CSTRING, STRING, WSTRING, POINTER, CUSTOM - }; -}; - -// A formatting argument. It is a trivially copyable/constructible type to -// allow storage in internal::MemoryBuffer. -struct Arg : Value { - Type type; -}; - -template -struct NamedArg; - -template -struct Null {}; - -// A helper class template to enable or disable overloads taking wide -// characters and strings in MakeValue. -template -struct WCharHelper { - typedef Null Supported; - typedef T Unsupported; -}; - -template -struct WCharHelper { - typedef T Supported; - typedef Null Unsupported; -}; - -typedef char Yes[1]; -typedef char No[2]; - -template -T &get(); - -// These are non-members to workaround an overload resolution bug in bcc32. -Yes &convert(fmt::ULongLong); -No &convert(...); - -template -struct ConvertToIntImpl { - enum { value = ENABLE_CONVERSION }; -}; - -template -struct ConvertToIntImpl2 { - enum { value = false }; -}; - -template -struct ConvertToIntImpl2 { - enum { - // Don't convert numeric types. - value = ConvertToIntImpl::is_specialized>::value - }; -}; - -template -struct ConvertToInt { - enum { enable_conversion = sizeof(convert(get())) == sizeof(Yes) }; - enum { value = ConvertToIntImpl2::value }; -}; - -#define FMT_DISABLE_CONVERSION_TO_INT(Type) \ - template <> \ - struct ConvertToInt { enum { value = 0 }; } - -// Silence warnings about convering float to int. -FMT_DISABLE_CONVERSION_TO_INT(float); -FMT_DISABLE_CONVERSION_TO_INT(double); -FMT_DISABLE_CONVERSION_TO_INT(long double); - -template -struct EnableIf {}; - -template -struct EnableIf { typedef T type; }; - -template -struct Conditional { typedef T type; }; - -template -struct Conditional { typedef F type; }; - -// For bcc32 which doesn't understand ! in template arguments. -template -struct Not { enum { value = 0 }; }; - -template<> -struct Not { enum { value = 1 }; }; - -// Makes an Arg object from any type. -template -class MakeValue : public Arg { - public: - typedef typename Formatter::Char Char; - - private: - // The following two methods are private to disallow formatting of - // arbitrary pointers. If you want to output a pointer cast it to - // "void *" or "const void *". In particular, this forbids formatting - // of "[const] volatile char *" which is printed as bool by iostreams. - // Do not implement! - template - MakeValue(const T *value); - template - MakeValue(T *value); - - // The following methods are private to disallow formatting of wide - // characters and strings into narrow strings as in - // fmt::format("{}", L"test"); - // To fix this, use a wide format string: fmt::format(L"{}", L"test"). -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) - MakeValue(typename WCharHelper::Unsupported); -#endif - MakeValue(typename WCharHelper::Unsupported); - MakeValue(typename WCharHelper::Unsupported); - MakeValue(typename WCharHelper::Unsupported); - MakeValue(typename WCharHelper::Unsupported); - - void set_string(StringRef str) { - string.value = str.data(); - string.size = str.size(); - } - - void set_string(WStringRef str) { - wstring.value = str.data(); - wstring.size = str.size(); - } - - // Formats an argument of a custom type, such as a user-defined class. - template - static void format_custom_arg( - void *formatter, const void *arg, void *format_str_ptr) { - format(*static_cast(formatter), - *static_cast(format_str_ptr), - *static_cast(arg)); - } - - public: - MakeValue() {} - -#define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \ - MakeValue(Type value) { field = rhs; } \ - static uint64_t type(Type) { return Arg::TYPE; } - -#define FMT_MAKE_VALUE(Type, field, TYPE) \ - FMT_MAKE_VALUE_(Type, field, TYPE, value) - - FMT_MAKE_VALUE(bool, int_value, BOOL) - FMT_MAKE_VALUE(short, int_value, INT) - FMT_MAKE_VALUE(unsigned short, uint_value, UINT) - FMT_MAKE_VALUE(int, int_value, INT) - FMT_MAKE_VALUE(unsigned, uint_value, UINT) - - MakeValue(long value) { - // To minimize the number of types we need to deal with, long is - // translated either to int or to long long depending on its size. - if (check(sizeof(long) == sizeof(int))) - int_value = static_cast(value); - else - long_long_value = value; - } - static uint64_t type(long) { - return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG; - } - - MakeValue(unsigned long value) { - if (check(sizeof(unsigned long) == sizeof(unsigned))) - uint_value = static_cast(value); - else - ulong_long_value = value; - } - static uint64_t type(unsigned long) { - return sizeof(unsigned long) == sizeof(unsigned) ? - Arg::UINT : Arg::ULONG_LONG; - } - - FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG) - FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG) - FMT_MAKE_VALUE(float, double_value, DOUBLE) - FMT_MAKE_VALUE(double, double_value, DOUBLE) - FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE) - FMT_MAKE_VALUE(signed char, int_value, INT) - FMT_MAKE_VALUE(unsigned char, uint_value, UINT) - FMT_MAKE_VALUE(char, int_value, CHAR) - -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) - MakeValue(typename WCharHelper::Supported value) { - int_value = value; - } - static uint64_t type(wchar_t) { return Arg::CHAR; } -#endif - -#define FMT_MAKE_STR_VALUE(Type, TYPE) \ - MakeValue(Type value) { set_string(value); } \ - static uint64_t type(Type) { return Arg::TYPE; } - - FMT_MAKE_VALUE(char *, string.value, CSTRING) - FMT_MAKE_VALUE(const char *, string.value, CSTRING) - FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING) - FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING) - FMT_MAKE_STR_VALUE(const std::string &, STRING) - FMT_MAKE_STR_VALUE(StringRef, STRING) - FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str()) - -#define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ - MakeValue(typename WCharHelper::Supported value) { \ - set_string(value); \ - } \ - static uint64_t type(Type) { return Arg::TYPE; } - - FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING) - FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING) - FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING) - FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING) - - FMT_MAKE_VALUE(void *, pointer, POINTER) - FMT_MAKE_VALUE(const void *, pointer, POINTER) - - template - MakeValue(const T &value, - typename EnableIf::value>::value, int>::type = 0) { - custom.value = &value; - custom.format = &format_custom_arg; - } - - template - MakeValue(const T &value, - typename EnableIf::value, int>::type = 0) { - int_value = value; - } - - template - static uint64_t type(const T &) { - return ConvertToInt::value ? Arg::INT : Arg::CUSTOM; - } - - // Additional template param `Char_` is needed here because make_type always - // uses char. - template - MakeValue(const NamedArg &value) { pointer = &value; } - - template - static uint64_t type(const NamedArg &) { return Arg::NAMED_ARG; } -}; - -template -class MakeArg : public Arg { -public: - MakeArg() { - type = Arg::NONE; - } - - template - MakeArg(const T &value) - : Arg(MakeValue(value)) { - type = static_cast(MakeValue::type(value)); - } -}; - -template -struct NamedArg : Arg { - BasicStringRef name; - - template - NamedArg(BasicStringRef argname, const T &value) - : Arg(MakeArg< BasicFormatter >(value)), name(argname) {} -}; - -class RuntimeError : public std::runtime_error { - protected: - RuntimeError() : std::runtime_error("") {} -}; - -template -class PrintfArgFormatter; - -template -class ArgMap; -} // namespace internal - -/** An argument list. */ -class ArgList { - private: - // To reduce compiled code size per formatting function call, types of first - // MAX_PACKED_ARGS arguments are passed in the types_ field. - uint64_t types_; - union { - // If the number of arguments is less than MAX_PACKED_ARGS, the argument - // values are stored in values_, otherwise they are stored in args_. - // This is done to reduce compiled code size as storing larger objects - // may require more code (at least on x86-64) even if the same amount of - // data is actually copied to stack. It saves ~10% on the bloat test. - const internal::Value *values_; - const internal::Arg *args_; - }; - - internal::Arg::Type type(unsigned index) const { - unsigned shift = index * 4; - uint64_t mask = 0xf; - return static_cast( - (types_ & (mask << shift)) >> shift); - } - - template - friend class internal::ArgMap; - - public: - // Maximum number of arguments with packed types. - enum { MAX_PACKED_ARGS = 16 }; - - ArgList() : types_(0) {} - - ArgList(ULongLong types, const internal::Value *values) - : types_(types), values_(values) {} - ArgList(ULongLong types, const internal::Arg *args) - : types_(types), args_(args) {} - - /** Returns the argument at specified index. */ - internal::Arg operator[](unsigned index) const { - using internal::Arg; - Arg arg; - bool use_values = type(MAX_PACKED_ARGS - 1) == Arg::NONE; - if (index < MAX_PACKED_ARGS) { - Arg::Type arg_type = type(index); - internal::Value &val = arg; - if (arg_type != Arg::NONE) - val = use_values ? values_[index] : args_[index]; - arg.type = arg_type; - return arg; - } - if (use_values) { - // The index is greater than the number of arguments that can be stored - // in values, so return a "none" argument. - arg.type = Arg::NONE; - return arg; - } - for (unsigned i = MAX_PACKED_ARGS; i <= index; ++i) { - if (args_[i].type == Arg::NONE) - return args_[i]; - } - return args_[index]; - } -}; - -#define FMT_DISPATCH(call) static_cast(this)->call - -/** - \rst - An argument visitor based on the `curiously recurring template pattern - `_. - - To use `~fmt::ArgVisitor` define a subclass that implements some or all of the - visit methods with the same signatures as the methods in `~fmt::ArgVisitor`, - for example, `~fmt::ArgVisitor::visit_int()`. - Pass the subclass as the *Impl* template parameter. Then calling - `~fmt::ArgVisitor::visit` for some argument will dispatch to a visit method - specific to the argument type. For example, if the argument type is - ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass - will be called. If the subclass doesn't contain a method with this signature, - then a corresponding method of `~fmt::ArgVisitor` will be called. - - **Example**:: - - class MyArgVisitor : public fmt::ArgVisitor { - public: - void visit_int(int value) { fmt::print("{}", value); } - void visit_double(double value) { fmt::print("{}", value ); } - }; - \endrst - */ -template -class ArgVisitor { - private: - typedef internal::Arg Arg; - - public: - void report_unhandled_arg() {} - - Result visit_unhandled_arg() { - FMT_DISPATCH(report_unhandled_arg()); - return Result(); - } - - /** Visits an ``int`` argument. **/ - Result visit_int(int value) { - return FMT_DISPATCH(visit_any_int(value)); - } - - /** Visits a ``long long`` argument. **/ - Result visit_long_long(LongLong value) { - return FMT_DISPATCH(visit_any_int(value)); - } - - /** Visits an ``unsigned`` argument. **/ - Result visit_uint(unsigned value) { - return FMT_DISPATCH(visit_any_int(value)); - } - - /** Visits an ``unsigned long long`` argument. **/ - Result visit_ulong_long(ULongLong value) { - return FMT_DISPATCH(visit_any_int(value)); - } - - /** Visits a ``bool`` argument. **/ - Result visit_bool(bool value) { - return FMT_DISPATCH(visit_any_int(value)); - } - - /** Visits a ``char`` or ``wchar_t`` argument. **/ - Result visit_char(int value) { - return FMT_DISPATCH(visit_any_int(value)); - } - - /** Visits an argument of any integral type. **/ - template - Result visit_any_int(T) { - return FMT_DISPATCH(visit_unhandled_arg()); - } - - /** Visits a ``double`` argument. **/ - Result visit_double(double value) { - return FMT_DISPATCH(visit_any_double(value)); - } - - /** Visits a ``long double`` argument. **/ - Result visit_long_double(long double value) { - return FMT_DISPATCH(visit_any_double(value)); - } - - /** Visits a ``double`` or ``long double`` argument. **/ - template - Result visit_any_double(T) { - return FMT_DISPATCH(visit_unhandled_arg()); - } - - /** Visits a null-terminated C string (``const char *``) argument. **/ - Result visit_cstring(const char *) { - return FMT_DISPATCH(visit_unhandled_arg()); - } - - /** Visits a string argument. **/ - Result visit_string(Arg::StringValue) { - return FMT_DISPATCH(visit_unhandled_arg()); - } - - /** Visits a wide string argument. **/ - Result visit_wstring(Arg::StringValue) { - return FMT_DISPATCH(visit_unhandled_arg()); - } - - /** Visits a pointer argument. **/ - Result visit_pointer(const void *) { - return FMT_DISPATCH(visit_unhandled_arg()); - } - - /** Visits an argument of a custom (user-defined) type. **/ - Result visit_custom(Arg::CustomValue) { - return FMT_DISPATCH(visit_unhandled_arg()); - } - - /** - \rst - Visits an argument dispatching to the appropriate visit method based on - the argument type. For example, if the argument type is ``double`` then - the `~fmt::ArgVisitor::visit_double()` method of the *Impl* class will be - called. - \endrst - */ - Result visit(const Arg &arg) { - switch (arg.type) { - default: - FMT_ASSERT(false, "invalid argument type"); - return Result(); - case Arg::INT: - return FMT_DISPATCH(visit_int(arg.int_value)); - case Arg::UINT: - return FMT_DISPATCH(visit_uint(arg.uint_value)); - case Arg::LONG_LONG: - return FMT_DISPATCH(visit_long_long(arg.long_long_value)); - case Arg::ULONG_LONG: - return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value)); - case Arg::BOOL: - return FMT_DISPATCH(visit_bool(arg.int_value != 0)); - case Arg::CHAR: - return FMT_DISPATCH(visit_char(arg.int_value)); - case Arg::DOUBLE: - return FMT_DISPATCH(visit_double(arg.double_value)); - case Arg::LONG_DOUBLE: - return FMT_DISPATCH(visit_long_double(arg.long_double_value)); - case Arg::CSTRING: - return FMT_DISPATCH(visit_cstring(arg.string.value)); - case Arg::STRING: - return FMT_DISPATCH(visit_string(arg.string)); - case Arg::WSTRING: - return FMT_DISPATCH(visit_wstring(arg.wstring)); - case Arg::POINTER: - return FMT_DISPATCH(visit_pointer(arg.pointer)); - case Arg::CUSTOM: - return FMT_DISPATCH(visit_custom(arg.custom)); - } - } -}; - -enum Alignment { - ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC -}; - -// Flags. -enum { - SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8, - CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. -}; - -// An empty format specifier. -struct EmptySpec {}; - -// A type specifier. -template -struct TypeSpec : EmptySpec { - Alignment align() const { return ALIGN_DEFAULT; } - unsigned width() const { return 0; } - int precision() const { return -1; } - bool flag(unsigned) const { return false; } - char type() const { return TYPE; } - char fill() const { return ' '; } -}; - -// A width specifier. -struct WidthSpec { - unsigned width_; - // Fill is always wchar_t and cast to char if necessary to avoid having - // two specialization of WidthSpec and its subclasses. - wchar_t fill_; - - WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {} - - unsigned width() const { return width_; } - wchar_t fill() const { return fill_; } -}; - -// An alignment specifier. -struct AlignSpec : WidthSpec { - Alignment align_; - - AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT) - : WidthSpec(width, fill), align_(align) {} - - Alignment align() const { return align_; } - - int precision() const { return -1; } -}; - -// An alignment and type specifier. -template -struct AlignTypeSpec : AlignSpec { - AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {} - - bool flag(unsigned) const { return false; } - char type() const { return TYPE; } -}; - -// A full format specifier. -struct FormatSpec : AlignSpec { - unsigned flags_; - int precision_; - char type_; - - FormatSpec( - unsigned width = 0, char type = 0, wchar_t fill = ' ') - : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {} - - bool flag(unsigned f) const { return (flags_ & f) != 0; } - int precision() const { return precision_; } - char type() const { return type_; } -}; - -// An integer format specifier. -template , typename Char = char> -class IntFormatSpec : public SpecT { - private: - T value_; - - public: - IntFormatSpec(T val, const SpecT &spec = SpecT()) - : SpecT(spec), value_(val) {} - - T value() const { return value_; } -}; - -// A string format specifier. -template -class StrFormatSpec : public AlignSpec { - private: - const Char *str_; - - public: - template - StrFormatSpec(const Char *str, unsigned width, FillChar fill) - : AlignSpec(width, fill), str_(str) { - internal::CharTraits::convert(FillChar()); - } - - const Char *str() const { return str_; } -}; - -/** - Returns an integer format specifier to format the value in base 2. - */ -IntFormatSpec > bin(int value); - -/** - Returns an integer format specifier to format the value in base 8. - */ -IntFormatSpec > oct(int value); - -/** - Returns an integer format specifier to format the value in base 16 using - lower-case letters for the digits above 9. - */ -IntFormatSpec > hex(int value); - -/** - Returns an integer formatter format specifier to format in base 16 using - upper-case letters for the digits above 9. - */ -IntFormatSpec > hexu(int value); - -/** - \rst - Returns an integer format specifier to pad the formatted argument with the - fill character to the specified width using the default (right) numeric - alignment. - - **Example**:: - - MemoryWriter out; - out << pad(hex(0xcafe), 8, '0'); - // out.str() == "0000cafe" - - \endrst - */ -template -IntFormatSpec, Char> pad( - int value, unsigned width, Char fill = ' '); - -#define FMT_DEFINE_INT_FORMATTERS(TYPE) \ -inline IntFormatSpec > bin(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'b'>()); \ -} \ - \ -inline IntFormatSpec > oct(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'o'>()); \ -} \ - \ -inline IntFormatSpec > hex(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'x'>()); \ -} \ - \ -inline IntFormatSpec > hexu(TYPE value) { \ - return IntFormatSpec >(value, TypeSpec<'X'>()); \ -} \ - \ -template \ -inline IntFormatSpec > pad( \ - IntFormatSpec > f, unsigned width) { \ - return IntFormatSpec >( \ - f.value(), AlignTypeSpec(width, ' ')); \ -} \ - \ -/* For compatibility with older compilers we provide two overloads for pad, */ \ -/* one that takes a fill character and one that doesn't. In the future this */ \ -/* can be replaced with one overload making the template argument Char */ \ -/* default to char (C++11). */ \ -template \ -inline IntFormatSpec, Char> pad( \ - IntFormatSpec, Char> f, \ - unsigned width, Char fill) { \ - return IntFormatSpec, Char>( \ - f.value(), AlignTypeSpec(width, fill)); \ -} \ - \ -inline IntFormatSpec > pad( \ - TYPE value, unsigned width) { \ - return IntFormatSpec >( \ - value, AlignTypeSpec<0>(width, ' ')); \ -} \ - \ -template \ -inline IntFormatSpec, Char> pad( \ - TYPE value, unsigned width, Char fill) { \ - return IntFormatSpec, Char>( \ - value, AlignTypeSpec<0>(width, fill)); \ -} - -FMT_DEFINE_INT_FORMATTERS(int) -FMT_DEFINE_INT_FORMATTERS(long) -FMT_DEFINE_INT_FORMATTERS(unsigned) -FMT_DEFINE_INT_FORMATTERS(unsigned long) -FMT_DEFINE_INT_FORMATTERS(LongLong) -FMT_DEFINE_INT_FORMATTERS(ULongLong) - -/** - \rst - Returns a string formatter that pads the formatted argument with the fill - character to the specified width using the default (left) string alignment. - - **Example**:: - - std::string s = str(MemoryWriter() << pad("abc", 8)); - // s == "abc " - - \endrst - */ -template -inline StrFormatSpec pad( - const Char *str, unsigned width, Char fill = ' ') { - return StrFormatSpec(str, width, fill); -} - -inline StrFormatSpec pad( - const wchar_t *str, unsigned width, char fill = ' ') { - return StrFormatSpec(str, width, fill); -} - -namespace internal { - -template -class ArgMap { - private: - typedef std::vector< - std::pair, internal::Arg> > MapType; - typedef typename MapType::value_type Pair; - - MapType map_; - - public: - FMT_API void init(const ArgList &args); - - const internal::Arg* find(const fmt::BasicStringRef &name) const { - // The list is unsorted, so just return the first matching name. - for (typename MapType::const_iterator it = map_.begin(), end = map_.end(); - it != end; ++it) { - if (it->first == name) - return &it->second; - } - return 0; - } -}; - -template -class ArgFormatterBase : public ArgVisitor { - private: - BasicWriter &writer_; - FormatSpec &spec_; - - FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatterBase); - - void write_pointer(const void *p) { - spec_.flags_ = HASH_FLAG; - spec_.type_ = 'x'; - writer_.write_int(reinterpret_cast(p), spec_); - } - - protected: - BasicWriter &writer() { return writer_; } - FormatSpec &spec() { return spec_; } - - void write(bool value) { - const char *str_value = value ? "true" : "false"; - Arg::StringValue str = { str_value, std::strlen(str_value) }; - writer_.write_str(str, spec_); - } - - void write(const char *value) { - Arg::StringValue str = {value, value != 0 ? std::strlen(value) : 0}; - writer_.write_str(str, spec_); - } - - public: - ArgFormatterBase(BasicWriter &w, FormatSpec &s) - : writer_(w), spec_(s) {} - - template - void visit_any_int(T value) { writer_.write_int(value, spec_); } - - template - void visit_any_double(T value) { writer_.write_double(value, spec_); } - - void visit_bool(bool value) { - if (spec_.type_) - return visit_any_int(value); - write(value); - } - - void visit_char(int value) { - if (spec_.type_ && spec_.type_ != 'c') { - spec_.flags_ |= CHAR_FLAG; - writer_.write_int(value, spec_); - return; - } - if (spec_.align_ == ALIGN_NUMERIC || spec_.flags_ != 0) - FMT_THROW(FormatError("invalid format specifier for char")); - typedef typename BasicWriter::CharPtr CharPtr; - Char fill = internal::CharTraits::cast(spec_.fill()); - CharPtr out = CharPtr(); - const unsigned CHAR_WIDTH = 1; - if (spec_.width_ > CHAR_WIDTH) { - out = writer_.grow_buffer(spec_.width_); - if (spec_.align_ == ALIGN_RIGHT) { - std::uninitialized_fill_n(out, spec_.width_ - CHAR_WIDTH, fill); - out += spec_.width_ - CHAR_WIDTH; - } else if (spec_.align_ == ALIGN_CENTER) { - out = writer_.fill_padding(out, spec_.width_, - internal::check(CHAR_WIDTH), fill); - } else { - std::uninitialized_fill_n(out + CHAR_WIDTH, - spec_.width_ - CHAR_WIDTH, fill); - } - } else { - out = writer_.grow_buffer(CHAR_WIDTH); - } - *out = internal::CharTraits::cast(value); - } - - void visit_cstring(const char *value) { - if (spec_.type_ == 'p') - return write_pointer(value); - write(value); - } - - void visit_string(Arg::StringValue value) { - writer_.write_str(value, spec_); - } - - using ArgVisitor::visit_wstring; - - void visit_wstring(Arg::StringValue value) { - writer_.write_str(value, spec_); - } - - void visit_pointer(const void *value) { - if (spec_.type_ && spec_.type_ != 'p') - report_unknown_type(spec_.type_, "pointer"); - write_pointer(value); - } -}; - -class FormatterBase { - private: - ArgList args_; - int next_arg_index_; - - // Returns the argument with specified index. - FMT_API Arg do_get_arg(unsigned arg_index, const char *&error); - - protected: - const ArgList &args() const { return args_; } - - explicit FormatterBase(const ArgList &args) { - args_ = args; - next_arg_index_ = 0; - } - - // Returns the next argument. - Arg next_arg(const char *&error) { - if (next_arg_index_ >= 0) - return do_get_arg(internal::to_unsigned(next_arg_index_++), error); - error = "cannot switch from manual to automatic argument indexing"; - return Arg(); - } - - // Checks if manual indexing is used and returns the argument with - // specified index. - Arg get_arg(unsigned arg_index, const char *&error) { - return check_no_auto_index(error) ? do_get_arg(arg_index, error) : Arg(); - } - - bool check_no_auto_index(const char *&error) { - if (next_arg_index_ > 0) { - error = "cannot switch from automatic to manual argument indexing"; - return false; - } - next_arg_index_ = -1; - return true; - } - - template - void write(BasicWriter &w, const Char *start, const Char *end) { - if (start != end) - w << BasicStringRef(start, internal::to_unsigned(end - start)); - } -}; - -// A printf formatter. -template -class PrintfFormatter : private FormatterBase { - private: - void parse_flags(FormatSpec &spec, const Char *&s); - - // Returns the argument with specified index or, if arg_index is equal - // to the maximum unsigned value, the next argument. - Arg get_arg(const Char *s, - unsigned arg_index = (std::numeric_limits::max)()); - - // Parses argument index, flags and width and returns the argument index. - unsigned parse_header(const Char *&s, FormatSpec &spec); - - public: - explicit PrintfFormatter(const ArgList &args) : FormatterBase(args) {} - FMT_API void format(BasicWriter &writer, - BasicCStringRef format_str); -}; -} // namespace internal - -/** - \rst - An argument formatter based on the `curiously recurring template pattern - `_. - - To use `~fmt::BasicArgFormatter` define a subclass that implements some or - all of the visit methods with the same signatures as the methods in - `~fmt::ArgVisitor`, for example, `~fmt::ArgVisitor::visit_int()`. - Pass the subclass as the *Impl* template parameter. When a formatting - function processes an argument, it will dispatch to a visit method - specific to the argument type. For example, if the argument type is - ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass - will be called. If the subclass doesn't contain a method with this signature, - then a corresponding method of `~fmt::BasicArgFormatter` or its superclass - will be called. - \endrst - */ -template -class BasicArgFormatter : public internal::ArgFormatterBase { - private: - BasicFormatter &formatter_; - const Char *format_; - - public: - /** - \rst - Constructs an argument formatter object. - *formatter* is a reference to the main formatter object, *spec* contains - format specifier information for standard argument types, and *fmt* points - to the part of the format string being parsed for custom argument types. - \endrst - */ - BasicArgFormatter(BasicFormatter &formatter, - FormatSpec &spec, const Char *fmt) - : internal::ArgFormatterBase(formatter.writer(), spec), - formatter_(formatter), format_(fmt) {} - - /** Formats argument of a custom (user-defined) type. */ - void visit_custom(internal::Arg::CustomValue c) { - c.format(&formatter_, c.value, &format_); - } -}; - -/** The default argument formatter. */ -template -class ArgFormatter : public BasicArgFormatter, Char> { - public: - /** Constructs an argument formatter object. */ - ArgFormatter(BasicFormatter &formatter, - FormatSpec &spec, const Char *fmt) - : BasicArgFormatter, Char>(formatter, spec, fmt) {} -}; - -/** This template formats data and writes the output to a writer. */ -template -class BasicFormatter : private internal::FormatterBase { - public: - /** The character type for the output. */ - typedef CharType Char; - - private: - BasicWriter &writer_; - internal::ArgMap map_; - - FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter); - - using internal::FormatterBase::get_arg; - - // Checks if manual indexing is used and returns the argument with - // specified name. - internal::Arg get_arg(BasicStringRef arg_name, const char *&error); - - // Parses argument index and returns corresponding argument. - internal::Arg parse_arg_index(const Char *&s); - - // Parses argument name and returns corresponding argument. - internal::Arg parse_arg_name(const Char *&s); - - public: - /** - \rst - Constructs a ``BasicFormatter`` object. References to the arguments and - the writer are stored in the formatter object so make sure they have - appropriate lifetimes. - \endrst - */ - BasicFormatter(const ArgList &args, BasicWriter &w) - : internal::FormatterBase(args), writer_(w) {} - - /** Returns a reference to the writer associated with this formatter. */ - BasicWriter &writer() { return writer_; } - - /** Formats stored arguments and writes the output to the writer. */ - void format(BasicCStringRef format_str); - - // Formats a single argument and advances format_str, a format string pointer. - const Char *format(const Char *&format_str, const internal::Arg &arg); -}; - -// Generates a comma-separated list with results of applying f to -// numbers 0..n-1. -# define FMT_GEN(n, f) FMT_GEN##n(f) -# define FMT_GEN1(f) f(0) -# define FMT_GEN2(f) FMT_GEN1(f), f(1) -# define FMT_GEN3(f) FMT_GEN2(f), f(2) -# define FMT_GEN4(f) FMT_GEN3(f), f(3) -# define FMT_GEN5(f) FMT_GEN4(f), f(4) -# define FMT_GEN6(f) FMT_GEN5(f), f(5) -# define FMT_GEN7(f) FMT_GEN6(f), f(6) -# define FMT_GEN8(f) FMT_GEN7(f), f(7) -# define FMT_GEN9(f) FMT_GEN8(f), f(8) -# define FMT_GEN10(f) FMT_GEN9(f), f(9) -# define FMT_GEN11(f) FMT_GEN10(f), f(10) -# define FMT_GEN12(f) FMT_GEN11(f), f(11) -# define FMT_GEN13(f) FMT_GEN12(f), f(12) -# define FMT_GEN14(f) FMT_GEN13(f), f(13) -# define FMT_GEN15(f) FMT_GEN14(f), f(14) - -namespace internal { -inline uint64_t make_type() { return 0; } - -template -inline uint64_t make_type(const T &arg) { - return MakeValue< BasicFormatter >::type(arg); -} - -template -struct ArgArray; - -template -struct ArgArray { - typedef Value Type[N > 0 ? N : 1]; - - template - static Value make(const T &value) { -#ifdef __clang__ - Value result = MakeValue(value); - // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang: - // https://github.com/fmtlib/fmt/issues/276 - (void)result.custom.format; - return result; -#else - return MakeValue(value); -#endif - } -}; - -template -struct ArgArray { - typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE - - template - static Arg make(const T &value) { return MakeArg(value); } -}; - -#if FMT_USE_VARIADIC_TEMPLATES -template -inline uint64_t make_type(const Arg &first, const Args & ... tail) { - return make_type(first) | (make_type(tail...) << 4); -} - -#else - -struct ArgType { - uint64_t type; - - ArgType() : type(0) {} - - template - ArgType(const T &arg) : type(make_type(arg)) {} -}; - -# define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() - -inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) { - return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | - (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) | - (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | - (t12.type << 48) | (t13.type << 52) | (t14.type << 56); -} -#endif -} // namespace internal - -# define FMT_MAKE_TEMPLATE_ARG(n) typename T##n -# define FMT_MAKE_ARG_TYPE(n) T##n -# define FMT_MAKE_ARG(n) const T##n &v##n -# define FMT_ASSIGN_char(n) \ - arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) -# define FMT_ASSIGN_wchar_t(n) \ - arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) - -#if FMT_USE_VARIADIC_TEMPLATES -// Defines a variadic function returning void. -# define FMT_VARIADIC_VOID(func, arg_type) \ - template \ - void func(arg_type arg0, const Args & ... args) { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } - -// Defines a variadic constructor. -# define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ - template \ - ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } - -#else - -# define FMT_MAKE_REF(n) \ - fmt::internal::MakeValue< fmt::BasicFormatter >(v##n) -# define FMT_MAKE_REF2(n) v##n - -// Defines a wrapper for a function taking one argument of type arg_type -// and n additional arguments of arbitrary types. -# define FMT_WRAP1(func, arg_type, n) \ - template \ - inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ - const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ - func(arg1, fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ - } - -// Emulates a variadic function returning void on a pre-C++11 compiler. -# define FMT_VARIADIC_VOID(func, arg_type) \ - inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \ - FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \ - FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \ - FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \ - FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ - FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) - -# define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ - template \ - ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ - const fmt::internal::ArgArray::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ - func(arg0, arg1, fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ - } - -// Emulates a variadic constructor on a pre-C++11 compiler. -# define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ - FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) -#endif - -// Generates a comma-separated list with results of applying f to pairs -// (argument, index). -#define FMT_FOR_EACH1(f, x0) f(x0, 0) -#define FMT_FOR_EACH2(f, x0, x1) \ - FMT_FOR_EACH1(f, x0), f(x1, 1) -#define FMT_FOR_EACH3(f, x0, x1, x2) \ - FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2) -#define FMT_FOR_EACH4(f, x0, x1, x2, x3) \ - FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) -#define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \ - FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) -#define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \ - FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) -#define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \ - FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) -#define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \ - FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) -#define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \ - FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) -#define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \ - FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) - -/** - An error returned by an operating system or a language runtime, - for example a file opening error. -*/ -class SystemError : public internal::RuntimeError { - private: - void init(int err_code, CStringRef format_str, ArgList args); - - protected: - int error_code_; - - typedef char Char; // For FMT_VARIADIC_CTOR. - - SystemError() {} - - public: - /** - \rst - Constructs a :class:`fmt::SystemError` object with the description - of the form - - .. parsed-literal:: - **: ** - - where ** is the formatted message and ** is - the system message corresponding to the error code. - *error_code* is a system error code as given by ``errno``. - If *error_code* is not a valid error code such as -1, the system message - may look like "Unknown error -1" and is platform-dependent. - - **Example**:: - - // This throws a SystemError with the description - // cannot open file 'madeup': No such file or directory - // or similar (system message may vary). - const char *filename = "madeup"; - std::FILE *file = std::fopen(filename, "r"); - if (!file) - throw fmt::SystemError(errno, "cannot open file '{}'", filename); - \endrst - */ - SystemError(int error_code, CStringRef message) { - init(error_code, message, ArgList()); - } - FMT_VARIADIC_CTOR(SystemError, init, int, CStringRef) - - int error_code() const { return error_code_; } -}; - -/** - \rst - This template provides operations for formatting and writing data into - a character stream. The output is stored in a buffer provided by a subclass - such as :class:`fmt::BasicMemoryWriter`. - - You can use one of the following typedefs for common character types: - - +---------+----------------------+ - | Type | Definition | - +=========+======================+ - | Writer | BasicWriter | - +---------+----------------------+ - | WWriter | BasicWriter | - +---------+----------------------+ - - \endrst - */ -template -class BasicWriter { - private: - // Output buffer. - Buffer &buffer_; - - FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter); - - typedef typename internal::CharTraits::CharPtr CharPtr; - -#if FMT_SECURE_SCL - // Returns pointer value. - static Char *get(CharPtr p) { return p.base(); } -#else - static Char *get(Char *p) { return p; } -#endif - - // Fills the padding around the content and returns the pointer to the - // content area. - static CharPtr fill_padding(CharPtr buffer, - unsigned total_size, std::size_t content_size, wchar_t fill); - - // Grows the buffer by n characters and returns a pointer to the newly - // allocated area. - CharPtr grow_buffer(std::size_t n) { - std::size_t size = buffer_.size(); - buffer_.resize(size + n); - return internal::make_ptr(&buffer_[size], n); - } - - // Writes an unsigned decimal integer. - template - Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) { - unsigned num_digits = internal::count_digits(value); - Char *ptr = get(grow_buffer(prefix_size + num_digits)); - internal::format_decimal(ptr + prefix_size, value, num_digits); - return ptr; - } - - // Writes a decimal integer. - template - void write_decimal(Int value) { - typedef typename internal::IntTraits::MainType MainType; - MainType abs_value = static_cast(value); - if (internal::is_negative(value)) { - abs_value = 0 - abs_value; - *write_unsigned_decimal(abs_value, 1) = '-'; - } else { - write_unsigned_decimal(abs_value, 0); - } - } - - // Prepare a buffer for integer formatting. - CharPtr prepare_int_buffer(unsigned num_digits, - const EmptySpec &, const char *prefix, unsigned prefix_size) { - unsigned size = prefix_size + num_digits; - CharPtr p = grow_buffer(size); - std::uninitialized_copy(prefix, prefix + prefix_size, p); - return p + size - 1; - } - - template - CharPtr prepare_int_buffer(unsigned num_digits, - const Spec &spec, const char *prefix, unsigned prefix_size); - - // Formats an integer. - template - void write_int(T value, Spec spec); - - // Formats a floating-point number (double or long double). - template - void write_double(T value, const FormatSpec &spec); - - // Writes a formatted string. - template - CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); - - template - void write_str(const internal::Arg::StringValue &str, - const FormatSpec &spec); - - // This following methods are private to disallow writing wide characters - // and strings to a char stream. If you want to print a wide string as a - // pointer as std::ostream does, cast it to const void*. - // Do not implement! - void operator<<(typename internal::WCharHelper::Unsupported); - void operator<<( - typename internal::WCharHelper::Unsupported); - - // Appends floating-point length specifier to the format string. - // The second argument is only used for overload resolution. - void append_float_length(Char *&format_ptr, long double) { - *format_ptr++ = 'L'; - } - - template - void append_float_length(Char *&, T) {} - - template - friend class internal::ArgFormatterBase; - - friend class internal::PrintfArgFormatter; - - protected: - /** - Constructs a ``BasicWriter`` object. - */ - explicit BasicWriter(Buffer &b) : buffer_(b) {} - - public: - /** - \rst - Destroys a ``BasicWriter`` object. - \endrst - */ - virtual ~BasicWriter() {} - - /** - Returns the total number of characters written. - */ - std::size_t size() const { return buffer_.size(); } - - /** - Returns a pointer to the output buffer content. No terminating null - character is appended. - */ - const Char *data() const FMT_NOEXCEPT { return &buffer_[0]; } - - /** - Returns a pointer to the output buffer content with terminating null - character appended. - */ - const Char *c_str() const { - std::size_t size = buffer_.size(); - buffer_.reserve(size + 1); - buffer_[size] = '\0'; - return &buffer_[0]; - } - - /** - \rst - Returns the content of the output buffer as an `std::string`. - \endrst - */ - std::basic_string str() const { - return std::basic_string(&buffer_[0], buffer_.size()); - } - - /** - \rst - Writes formatted data. - - *args* is an argument list representing arbitrary arguments. - - **Example**:: - - MemoryWriter out; - out.write("Current point:\n"); - out.write("({:+f}, {:+f})", -3.14, 3.14); - - This will write the following output to the ``out`` object: - - .. code-block:: none - - Current point: - (-3.140000, +3.140000) - - The output can be accessed using :func:`data()`, :func:`c_str` or - :func:`str` methods. - - See also :ref:`syntax`. - \endrst - */ - void write(BasicCStringRef format, ArgList args) { - BasicFormatter(args, *this).format(format); - } - FMT_VARIADIC_VOID(write, BasicCStringRef) - - BasicWriter &operator<<(int value) { - write_decimal(value); - return *this; - } - BasicWriter &operator<<(unsigned value) { - return *this << IntFormatSpec(value); - } - BasicWriter &operator<<(long value) { - write_decimal(value); - return *this; - } - BasicWriter &operator<<(unsigned long value) { - return *this << IntFormatSpec(value); - } - BasicWriter &operator<<(LongLong value) { - write_decimal(value); - return *this; - } - - /** - \rst - Formats *value* and writes it to the stream. - \endrst - */ - BasicWriter &operator<<(ULongLong value) { - return *this << IntFormatSpec(value); - } - - BasicWriter &operator<<(double value) { - write_double(value, FormatSpec()); - return *this; - } - - /** - \rst - Formats *value* using the general format for floating-point numbers - (``'g'``) and writes it to the stream. - \endrst - */ - BasicWriter &operator<<(long double value) { - write_double(value, FormatSpec()); - return *this; - } - - /** - Writes a character to the stream. - */ - BasicWriter &operator<<(char value) { - buffer_.push_back(value); - return *this; - } - - BasicWriter &operator<<( - typename internal::WCharHelper::Supported value) { - buffer_.push_back(value); - return *this; - } - - /** - \rst - Writes *value* to the stream. - \endrst - */ - BasicWriter &operator<<(fmt::BasicStringRef value) { - const Char *str = value.data(); - buffer_.append(str, str + value.size()); - return *this; - } - - BasicWriter &operator<<( - typename internal::WCharHelper::Supported value) { - const char *str = value.data(); - buffer_.append(str, str + value.size()); - return *this; - } - - template - BasicWriter &operator<<(IntFormatSpec spec) { - internal::CharTraits::convert(FillChar()); - write_int(spec.value(), spec); - return *this; - } - - template - BasicWriter &operator<<(const StrFormatSpec &spec) { - const StrChar *s = spec.str(); - write_str(s, std::char_traits::length(s), spec); - return *this; - } - - void clear() FMT_NOEXCEPT { buffer_.clear(); } - - Buffer &buffer() FMT_NOEXCEPT { return buffer_; } -}; - -template -template -typename BasicWriter::CharPtr BasicWriter::write_str( - const StrChar *s, std::size_t size, const AlignSpec &spec) { - CharPtr out = CharPtr(); - if (spec.width() > size) { - out = grow_buffer(spec.width()); - Char fill = internal::CharTraits::cast(spec.fill()); - if (spec.align() == ALIGN_RIGHT) { - std::uninitialized_fill_n(out, spec.width() - size, fill); - out += spec.width() - size; - } else if (spec.align() == ALIGN_CENTER) { - out = fill_padding(out, spec.width(), size, fill); - } else { - std::uninitialized_fill_n(out + size, spec.width() - size, fill); - } - } else { - out = grow_buffer(size); - } - std::uninitialized_copy(s, s + size, out); - return out; -} - -template -template -void BasicWriter::write_str( - const internal::Arg::StringValue &s, const FormatSpec &spec) { - // Check if StrChar is convertible to Char. - internal::CharTraits::convert(StrChar()); - if (spec.type_ && spec.type_ != 's') - internal::report_unknown_type(spec.type_, "string"); - const StrChar *str_value = s.value; - std::size_t str_size = s.size; - if (str_size == 0) { - if (!str_value) { - FMT_THROW(FormatError("string pointer is null")); - return; - } - } - std::size_t precision = static_cast(spec.precision_); - if (spec.precision_ >= 0 && precision < str_size) - str_size = precision; - write_str(str_value, str_size, spec); -} - -template -typename BasicWriter::CharPtr - BasicWriter::fill_padding( - CharPtr buffer, unsigned total_size, - std::size_t content_size, wchar_t fill) { - std::size_t padding = total_size - content_size; - std::size_t left_padding = padding / 2; - Char fill_char = internal::CharTraits::cast(fill); - std::uninitialized_fill_n(buffer, left_padding, fill_char); - buffer += left_padding; - CharPtr content = buffer; - std::uninitialized_fill_n(buffer + content_size, - padding - left_padding, fill_char); - return content; -} - -template -template -typename BasicWriter::CharPtr - BasicWriter::prepare_int_buffer( - unsigned num_digits, const Spec &spec, - const char *prefix, unsigned prefix_size) { - unsigned width = spec.width(); - Alignment align = spec.align(); - Char fill = internal::CharTraits::cast(spec.fill()); - if (spec.precision() > static_cast(num_digits)) { - // Octal prefix '0' is counted as a digit, so ignore it if precision - // is specified. - if (prefix_size > 0 && prefix[prefix_size - 1] == '0') - --prefix_size; - unsigned number_size = - prefix_size + internal::to_unsigned(spec.precision()); - AlignSpec subspec(number_size, '0', ALIGN_NUMERIC); - if (number_size >= width) - return prepare_int_buffer(num_digits, subspec, prefix, prefix_size); - buffer_.reserve(width); - unsigned fill_size = width - number_size; - if (align != ALIGN_LEFT) { - CharPtr p = grow_buffer(fill_size); - std::uninitialized_fill(p, p + fill_size, fill); - } - CharPtr result = prepare_int_buffer( - num_digits, subspec, prefix, prefix_size); - if (align == ALIGN_LEFT) { - CharPtr p = grow_buffer(fill_size); - std::uninitialized_fill(p, p + fill_size, fill); - } - return result; - } - unsigned size = prefix_size + num_digits; - if (width <= size) { - CharPtr p = grow_buffer(size); - std::uninitialized_copy(prefix, prefix + prefix_size, p); - return p + size - 1; - } - CharPtr p = grow_buffer(width); - CharPtr end = p + width; - if (align == ALIGN_LEFT) { - std::uninitialized_copy(prefix, prefix + prefix_size, p); - p += size; - std::uninitialized_fill(p, end, fill); - } else if (align == ALIGN_CENTER) { - p = fill_padding(p, width, size, fill); - std::uninitialized_copy(prefix, prefix + prefix_size, p); - p += size; - } else { - if (align == ALIGN_NUMERIC) { - if (prefix_size != 0) { - p = std::uninitialized_copy(prefix, prefix + prefix_size, p); - size -= prefix_size; - } - } else { - std::uninitialized_copy(prefix, prefix + prefix_size, end - size); - } - std::uninitialized_fill(p, end - size, fill); - p = end; - } - return p - 1; -} - -template -template -void BasicWriter::write_int(T value, Spec spec) { - unsigned prefix_size = 0; - typedef typename internal::IntTraits::MainType UnsignedType; - UnsignedType abs_value = static_cast(value); - char prefix[4] = ""; - if (internal::is_negative(value)) { - prefix[0] = '-'; - ++prefix_size; - abs_value = 0 - abs_value; - } else if (spec.flag(SIGN_FLAG)) { - prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' '; - ++prefix_size; - } - switch (spec.type()) { - case 0: case 'd': { - unsigned num_digits = internal::count_digits(abs_value); - CharPtr p = prepare_int_buffer(num_digits, spec, prefix, prefix_size) + 1; - internal::format_decimal(get(p), abs_value, 0); - break; - } - case 'x': case 'X': { - UnsignedType n = abs_value; - if (spec.flag(HASH_FLAG)) { - prefix[prefix_size++] = '0'; - prefix[prefix_size++] = spec.type(); - } - unsigned num_digits = 0; - do { - ++num_digits; - } while ((n >>= 4) != 0); - Char *p = get(prepare_int_buffer( - num_digits, spec, prefix, prefix_size)); - n = abs_value; - const char *digits = spec.type() == 'x' ? - "0123456789abcdef" : "0123456789ABCDEF"; - do { - *p-- = digits[n & 0xf]; - } while ((n >>= 4) != 0); - break; - } - case 'b': case 'B': { - UnsignedType n = abs_value; - if (spec.flag(HASH_FLAG)) { - prefix[prefix_size++] = '0'; - prefix[prefix_size++] = spec.type(); - } - unsigned num_digits = 0; - do { - ++num_digits; - } while ((n >>= 1) != 0); - Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); - n = abs_value; - do { - *p-- = static_cast('0' + (n & 1)); - } while ((n >>= 1) != 0); - break; - } - case 'o': { - UnsignedType n = abs_value; - if (spec.flag(HASH_FLAG)) - prefix[prefix_size++] = '0'; - unsigned num_digits = 0; - do { - ++num_digits; - } while ((n >>= 3) != 0); - Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); - n = abs_value; - do { - *p-- = static_cast('0' + (n & 7)); - } while ((n >>= 3) != 0); - break; - } - case 'n': { - unsigned num_digits = internal::count_digits(abs_value); - fmt::StringRef sep = std::localeconv()->thousands_sep; - unsigned size = static_cast( - num_digits + sep.size() * (num_digits - 1) / 3); - CharPtr p = prepare_int_buffer(size, spec, prefix, prefix_size) + 1; - internal::format_decimal(get(p), abs_value, 0, internal::ThousandsSep(sep)); - break; - } - default: - internal::report_unknown_type( - spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); - break; - } -} - -template -template -void BasicWriter::write_double(T value, const FormatSpec &spec) { - // Check type. - char type = spec.type(); - bool upper = false; - switch (type) { - case 0: - type = 'g'; - break; - case 'e': case 'f': case 'g': case 'a': - break; - case 'F': -#ifdef _MSC_VER - // MSVC's printf doesn't support 'F'. - type = 'f'; -#endif - // Fall through. - case 'E': case 'G': case 'A': - upper = true; - break; - default: - internal::report_unknown_type(type, "double"); - break; - } - - char sign = 0; - // Use isnegative instead of value < 0 because the latter is always - // false for NaN. - if (internal::FPUtil::isnegative(static_cast(value))) { - sign = '-'; - value = -value; - } else if (spec.flag(SIGN_FLAG)) { - sign = spec.flag(PLUS_FLAG) ? '+' : ' '; - } - - if (internal::FPUtil::isnotanumber(value)) { - // Format NaN ourselves because sprintf's output is not consistent - // across platforms. - std::size_t nan_size = 4; - const char *nan = upper ? " NAN" : " nan"; - if (!sign) { - --nan_size; - ++nan; - } - CharPtr out = write_str(nan, nan_size, spec); - if (sign) - *out = sign; - return; - } - - if (internal::FPUtil::isinfinity(value)) { - // Format infinity ourselves because sprintf's output is not consistent - // across platforms. - std::size_t inf_size = 4; - const char *inf = upper ? " INF" : " inf"; - if (!sign) { - --inf_size; - ++inf; - } - CharPtr out = write_str(inf, inf_size, spec); - if (sign) - *out = sign; - return; - } - - std::size_t offset = buffer_.size(); - unsigned width = spec.width(); - if (sign) { - buffer_.reserve(buffer_.size() + (width > 1u ? width : 1u)); - if (width > 0) - --width; - ++offset; - } - - // Build format string. - enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg - Char format[MAX_FORMAT_SIZE]; - Char *format_ptr = format; - *format_ptr++ = '%'; - unsigned width_for_sprintf = width; - if (spec.flag(HASH_FLAG)) - *format_ptr++ = '#'; - if (spec.align() == ALIGN_CENTER) { - width_for_sprintf = 0; - } else { - if (spec.align() == ALIGN_LEFT) - *format_ptr++ = '-'; - if (width != 0) - *format_ptr++ = '*'; - } - if (spec.precision() >= 0) { - *format_ptr++ = '.'; - *format_ptr++ = '*'; - } - - append_float_length(format_ptr, value); - *format_ptr++ = type; - *format_ptr = '\0'; - - // Format using snprintf. - Char fill = internal::CharTraits::cast(spec.fill()); - unsigned n = 0; - Char *start = 0; - for (;;) { - std::size_t buffer_size = buffer_.capacity() - offset; -#ifdef _MSC_VER - // MSVC's vsnprintf_s doesn't work with zero size, so reserve - // space for at least one extra character to make the size non-zero. - // Note that the buffer's capacity will increase by more than 1. - if (buffer_size == 0) { - buffer_.reserve(offset + 1); - buffer_size = buffer_.capacity() - offset; - } -#endif - start = &buffer_[offset]; - int result = internal::CharTraits::format_float( - start, buffer_size, format, width_for_sprintf, spec.precision(), value); - if (result >= 0) { - n = internal::to_unsigned(result); - if (offset + n < buffer_.capacity()) - break; // The buffer is large enough - continue with formatting. - buffer_.reserve(offset + n + 1); - } else { - // If result is negative we ask to increase the capacity by at least 1, - // but as std::vector, the buffer grows exponentially. - buffer_.reserve(buffer_.capacity() + 1); - } - } - if (sign) { - if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || - *start != ' ') { - *(start - 1) = sign; - sign = 0; - } else { - *(start - 1) = fill; - } - ++n; - } - if (spec.align() == ALIGN_CENTER && spec.width() > n) { - width = spec.width(); - CharPtr p = grow_buffer(width); - std::memmove(get(p) + (width - n) / 2, get(p), n * sizeof(Char)); - fill_padding(p, spec.width(), n, fill); - return; - } - if (spec.fill() != ' ' || sign) { - while (*start == ' ') - *start++ = fill; - if (sign) - *(start - 1) = sign; - } - grow_buffer(n); -} - -/** - \rst - This class template provides operations for formatting and writing data - into a character stream. The output is stored in a memory buffer that grows - dynamically. - - You can use one of the following typedefs for common character types - and the standard allocator: - - +---------------+-----------------------------------------------------+ - | Type | Definition | - +===============+=====================================================+ - | MemoryWriter | BasicMemoryWriter> | - +---------------+-----------------------------------------------------+ - | WMemoryWriter | BasicMemoryWriter> | - +---------------+-----------------------------------------------------+ - - **Example**:: - - MemoryWriter out; - out << "The answer is " << 42 << "\n"; - out.write("({:+f}, {:+f})", -3.14, 3.14); - - This will write the following output to the ``out`` object: - - .. code-block:: none - - The answer is 42 - (-3.140000, +3.140000) - - The output can be converted to an ``std::string`` with ``out.str()`` or - accessed as a C string with ``out.c_str()``. - \endrst - */ -template > -class BasicMemoryWriter : public BasicWriter { - private: - internal::MemoryBuffer buffer_; - - public: - explicit BasicMemoryWriter(const Allocator& alloc = Allocator()) - : BasicWriter(buffer_), buffer_(alloc) {} - -#if FMT_USE_RVALUE_REFERENCES - /** - \rst - Constructs a :class:`fmt::BasicMemoryWriter` object moving the content - of the other object to it. - \endrst - */ - BasicMemoryWriter(BasicMemoryWriter &&other) - : BasicWriter(buffer_), buffer_(std::move(other.buffer_)) { - } - - /** - \rst - Moves the content of the other ``BasicMemoryWriter`` object to this one. - \endrst - */ - BasicMemoryWriter &operator=(BasicMemoryWriter &&other) { - buffer_ = std::move(other.buffer_); - return *this; - } -#endif -}; - -typedef BasicMemoryWriter MemoryWriter; -typedef BasicMemoryWriter WMemoryWriter; - -/** - \rst - This class template provides operations for formatting and writing data - into a fixed-size array. For writing into a dynamically growing buffer - use :class:`fmt::BasicMemoryWriter`. - - Any write method will throw ``std::runtime_error`` if the output doesn't fit - into the array. - - You can use one of the following typedefs for common character types: - - +--------------+---------------------------+ - | Type | Definition | - +==============+===========================+ - | ArrayWriter | BasicArrayWriter | - +--------------+---------------------------+ - | WArrayWriter | BasicArrayWriter | - +--------------+---------------------------+ - \endrst - */ -template -class BasicArrayWriter : public BasicWriter { - private: - internal::FixedBuffer buffer_; - - public: - /** - \rst - Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the - given size. - \endrst - */ - BasicArrayWriter(Char *array, std::size_t size) - : BasicWriter(buffer_), buffer_(array, size) {} - - /** - \rst - Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the - size known at compile time. - \endrst - */ - template - explicit BasicArrayWriter(Char (&array)[SIZE]) - : BasicWriter(buffer_), buffer_(array, SIZE) {} -}; - -typedef BasicArrayWriter ArrayWriter; -typedef BasicArrayWriter WArrayWriter; - -// Reports a system error without throwing an exception. -// Can be used to report errors from destructors. -FMT_API void report_system_error(int error_code, - StringRef message) FMT_NOEXCEPT; - -#if FMT_USE_WINDOWS_H - -/** A Windows error. */ -class WindowsError : public SystemError { - private: - FMT_API void init(int error_code, CStringRef format_str, ArgList args); - - public: - /** - \rst - Constructs a :class:`fmt::WindowsError` object with the description - of the form - - .. parsed-literal:: - **: ** - - where ** is the formatted message and ** is the - system message corresponding to the error code. - *error_code* is a Windows error code as given by ``GetLastError``. - If *error_code* is not a valid error code such as -1, the system message - will look like "error -1". - - **Example**:: - - // This throws a WindowsError with the description - // cannot open file 'madeup': The system cannot find the file specified. - // or similar (system message may vary). - const char *filename = "madeup"; - LPOFSTRUCT of = LPOFSTRUCT(); - HFILE file = OpenFile(filename, &of, OF_READ); - if (file == HFILE_ERROR) { - throw fmt::WindowsError(GetLastError(), - "cannot open file '{}'", filename); - } - \endrst - */ - WindowsError(int error_code, CStringRef message) { - init(error_code, message, ArgList()); - } - FMT_VARIADIC_CTOR(WindowsError, init, int, CStringRef) -}; - -// Reports a Windows error without throwing an exception. -// Can be used to report errors from destructors. -FMT_API void report_windows_error(int error_code, - StringRef message) FMT_NOEXCEPT; - -#endif - -enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; - -/** - Formats a string and prints it to stdout using ANSI escape sequences - to specify color (experimental). - Example: - print_colored(fmt::RED, "Elapsed time: {0:.2f} seconds", 1.23); - */ -FMT_API void print_colored(Color c, CStringRef format, ArgList args); - -/** - \rst - Formats arguments and returns the result as a string. - - **Example**:: - - std::string message = format("The answer is {}", 42); - \endrst -*/ -inline std::string format(CStringRef format_str, ArgList args) { - MemoryWriter w; - w.write(format_str, args); - return w.str(); -} - -inline std::wstring format(WCStringRef format_str, ArgList args) { - WMemoryWriter w; - w.write(format_str, args); - return w.str(); -} - -/** - \rst - Prints formatted data to the file *f*. - - **Example**:: - - print(stderr, "Don't {}!", "panic"); - \endrst - */ -FMT_API void print(std::FILE *f, CStringRef format_str, ArgList args); - -/** - \rst - Prints formatted data to ``stdout``. - - **Example**:: - - print("Elapsed time: {0:.2f} seconds", 1.23); - \endrst - */ -FMT_API void print(CStringRef format_str, ArgList args); - -template -void printf(BasicWriter &w, BasicCStringRef format, ArgList args) { - internal::PrintfFormatter(args).format(w, format); -} - -/** - \rst - Formats arguments and returns the result as a string. - - **Example**:: - - std::string message = fmt::sprintf("The answer is %d", 42); - \endrst -*/ -inline std::string sprintf(CStringRef format, ArgList args) { - MemoryWriter w; - printf(w, format, args); - return w.str(); -} - -inline std::wstring sprintf(WCStringRef format, ArgList args) { - WMemoryWriter w; - printf(w, format, args); - return w.str(); -} - -/** - \rst - Prints formatted data to the file *f*. - - **Example**:: - - fmt::fprintf(stderr, "Don't %s!", "panic"); - \endrst - */ -FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args); - -/** - \rst - Prints formatted data to ``stdout``. - - **Example**:: - - fmt::printf("Elapsed time: %.2f seconds", 1.23); - \endrst - */ -inline int printf(CStringRef format, ArgList args) { - return fprintf(stdout, format, args); -} - -/** - Fast integer formatter. - */ -class FormatInt { - private: - // Buffer should be large enough to hold all digits (digits10 + 1), - // a sign and a null character. - enum {BUFFER_SIZE = std::numeric_limits::digits10 + 3}; - mutable char buffer_[BUFFER_SIZE]; - char *str_; - - // Formats value in reverse and returns the number of digits. - char *format_decimal(ULongLong value) { - char *buffer_end = buffer_ + BUFFER_SIZE - 1; - while (value >= 100) { - // Integer division is slow so do it for a group of two digits instead - // of for every digit. The idea comes from the talk by Alexandrescu - // "Three Optimization Tips for C++". See speed-test for a comparison. - unsigned index = static_cast((value % 100) * 2); - value /= 100; - *--buffer_end = internal::Data::DIGITS[index + 1]; - *--buffer_end = internal::Data::DIGITS[index]; - } - if (value < 10) { - *--buffer_end = static_cast('0' + value); - return buffer_end; - } - unsigned index = static_cast(value * 2); - *--buffer_end = internal::Data::DIGITS[index + 1]; - *--buffer_end = internal::Data::DIGITS[index]; - return buffer_end; - } - - void FormatSigned(LongLong value) { - ULongLong abs_value = static_cast(value); - bool negative = value < 0; - if (negative) - abs_value = 0 - abs_value; - str_ = format_decimal(abs_value); - if (negative) - *--str_ = '-'; - } - - public: - explicit FormatInt(int value) { FormatSigned(value); } - explicit FormatInt(long value) { FormatSigned(value); } - explicit FormatInt(LongLong value) { FormatSigned(value); } - explicit FormatInt(unsigned value) : str_(format_decimal(value)) {} - explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {} - explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {} - - /** Returns the number of characters written to the output buffer. */ - std::size_t size() const { - return internal::to_unsigned(buffer_ - str_ + BUFFER_SIZE - 1); - } - - /** - Returns a pointer to the output buffer content. No terminating null - character is appended. - */ - const char *data() const { return str_; } - - /** - Returns a pointer to the output buffer content with terminating null - character appended. - */ - const char *c_str() const { - buffer_[BUFFER_SIZE - 1] = '\0'; - return str_; - } - - /** - \rst - Returns the content of the output buffer as an ``std::string``. - \endrst - */ - std::string str() const { return std::string(str_, size()); } -}; - -// Formats a decimal integer value writing into buffer and returns -// a pointer to the end of the formatted string. This function doesn't -// write a terminating null character. -template -inline void format_decimal(char *&buffer, T value) { - typedef typename internal::IntTraits::MainType MainType; - MainType abs_value = static_cast(value); - if (internal::is_negative(value)) { - *buffer++ = '-'; - abs_value = 0 - abs_value; - } - if (abs_value < 100) { - if (abs_value < 10) { - *buffer++ = static_cast('0' + abs_value); - return; - } - unsigned index = static_cast(abs_value * 2); - *buffer++ = internal::Data::DIGITS[index]; - *buffer++ = internal::Data::DIGITS[index + 1]; - return; - } - unsigned num_digits = internal::count_digits(abs_value); - internal::format_decimal(buffer, abs_value, num_digits); - buffer += num_digits; -} - -/** - \rst - Returns a named argument for formatting functions. - - **Example**:: - - print("Elapsed time: {s:.2f} seconds", arg("s", 1.23)); - - \endrst - */ -template -inline internal::NamedArg arg(StringRef name, const T &arg) { - return internal::NamedArg(name, arg); -} - -template -inline internal::NamedArg arg(WStringRef name, const T &arg) { - return internal::NamedArg(name, arg); -} - -// The following two functions are deleted intentionally to disable -// nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``. -template -void arg(StringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; -template -void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; -} - -#if FMT_GCC_VERSION -// Use the system_header pragma to suppress warnings about variadic macros -// because suppressing -Wvariadic-macros with the diagnostic pragma doesn't -// work. It is used at the end because we want to suppress as little warnings -// as possible. -# pragma GCC system_header -#endif - -// This is used to work around VC++ bugs in handling variadic macros. -#define FMT_EXPAND(args) args - -// Returns the number of arguments. -// Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s. -#define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N()) -#define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__)) -#define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N -#define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 - -#define FMT_CONCAT(a, b) a##b -#define FMT_FOR_EACH_(N, f, ...) \ - FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) -#define FMT_FOR_EACH(f, ...) \ - FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) - -#define FMT_ADD_ARG_NAME(type, index) type arg##index -#define FMT_GET_ARG_NAME(type, index) arg##index - -#if FMT_USE_VARIADIC_TEMPLATES -# define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ - template \ - ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ - const Args & ... args) { \ - typedef fmt::internal::ArgArray ArgArray; \ - typename ArgArray::Type array{ \ - ArgArray::template make >(args)...}; \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \ - fmt::ArgList(fmt::internal::make_type(args...), array)); \ - } -#else -// Defines a wrapper for a function taking __VA_ARGS__ arguments -// and n additional arguments of arbitrary types. -# define FMT_WRAP(Char, ReturnType, func, call, n, ...) \ - template \ - inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ - FMT_GEN(n, FMT_MAKE_ARG)) { \ - fmt::internal::ArgArray::Type arr; \ - FMT_GEN(n, FMT_ASSIGN_##Char); \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ - fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \ - } - -# define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ - inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \ - call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ - } \ - FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__) -#endif // FMT_USE_VARIADIC_TEMPLATES - -/** - \rst - Defines a variadic function with the specified return type, function name - and argument types passed as variable arguments to this macro. - - **Example**:: - - void print_error(const char *file, int line, const char *format, - fmt::ArgList args) { - fmt::print("{}: {}: ", file, line); - fmt::print(format, args); - } - FMT_VARIADIC(void, print_error, const char *, int, const char *) - - ``FMT_VARIADIC`` is used for compatibility with legacy C++ compilers that - don't implement variadic templates. You don't have to use this macro if - you don't need legacy compiler support and can use variadic templates - directly:: - - template - void print_error(const char *file, int line, const char *format, - const Args & ... args) { - fmt::print("{}: {}: ", file, line); - fmt::print(format, args...); - } - \endrst - */ -#define FMT_VARIADIC(ReturnType, func, ...) \ - FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__) - -#define FMT_VARIADIC_W(ReturnType, func, ...) \ - FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__) - -#define FMT_CAPTURE_ARG_(id, index) ::fmt::arg(#id, id) - -#define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L###id, id) - -/** - \rst - Convenient macro to capture the arguments' names and values into several - ``fmt::arg(name, value)``. - - **Example**:: - - int x = 1, y = 2; - print("point: ({x}, {y})", FMT_CAPTURE(x, y)); - // same as: - // print("point: ({x}, {y})", arg("x", x), arg("y", y)); - - \endrst - */ -#define FMT_CAPTURE(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_, __VA_ARGS__) - -#define FMT_CAPTURE_W(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_W_, __VA_ARGS__) - -namespace fmt { -FMT_VARIADIC(std::string, format, CStringRef) -FMT_VARIADIC_W(std::wstring, format, WCStringRef) -FMT_VARIADIC(void, print, CStringRef) -FMT_VARIADIC(void, print, std::FILE *, CStringRef) - -FMT_VARIADIC(void, print_colored, Color, CStringRef) -FMT_VARIADIC(std::string, sprintf, CStringRef) -FMT_VARIADIC_W(std::wstring, sprintf, WCStringRef) -FMT_VARIADIC(int, printf, CStringRef) -FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef) - -namespace internal { -template -inline bool is_name_start(Char c) { - return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; -} - -// Parses an unsigned integer advancing s to the end of the parsed input. -// This function assumes that the first character of s is a digit. -template -unsigned parse_nonnegative_int(const Char *&s) { - assert('0' <= *s && *s <= '9'); - unsigned value = 0; - do { - unsigned new_value = value * 10 + (*s++ - '0'); - // Check if value wrapped around. - if (new_value < value) { - value = (std::numeric_limits::max)(); - break; - } - value = new_value; - } while ('0' <= *s && *s <= '9'); - // Convert to unsigned to prevent a warning. - unsigned max_int = (std::numeric_limits::max)(); - if (value > max_int) - FMT_THROW(FormatError("number is too big")); - return value; -} - -inline void require_numeric_argument(const Arg &arg, char spec) { - if (arg.type > Arg::LAST_NUMERIC_TYPE) { - std::string message = - fmt::format("format specifier '{}' requires numeric argument", spec); - FMT_THROW(fmt::FormatError(message)); - } -} - -template -void check_sign(const Char *&s, const Arg &arg) { - char sign = static_cast(*s); - require_numeric_argument(arg, sign); - if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { - FMT_THROW(FormatError(fmt::format( - "format specifier '{}' requires signed argument", sign))); - } - ++s; -} -} // namespace internal - -template -inline internal::Arg BasicFormatter::get_arg( - BasicStringRef arg_name, const char *&error) { - if (check_no_auto_index(error)) { - map_.init(args()); - const internal::Arg *arg = map_.find(arg_name); - if (arg) - return *arg; - error = "argument not found"; - } - return internal::Arg(); -} - -template -inline internal::Arg BasicFormatter::parse_arg_index(const Char *&s) { - const char *error = 0; - internal::Arg arg = *s < '0' || *s > '9' ? - next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); - if (error) { - FMT_THROW(FormatError( - *s != '}' && *s != ':' ? "invalid format string" : error)); - } - return arg; -} - -template -inline internal::Arg BasicFormatter::parse_arg_name(const Char *&s) { - assert(internal::is_name_start(*s)); - const Char *start = s; - Char c; - do { - c = *++s; - } while (internal::is_name_start(c) || ('0' <= c && c <= '9')); - const char *error = 0; - internal::Arg arg = get_arg(BasicStringRef(start, s - start), error); - if (error) - FMT_THROW(FormatError(error)); - return arg; -} - -template -const Char *BasicFormatter::format( - const Char *&format_str, const internal::Arg &arg) { - using internal::Arg; - const Char *s = format_str; - FormatSpec spec; - if (*s == ':') { - if (arg.type == Arg::CUSTOM) { - arg.custom.format(this, arg.custom.value, &s); - return s; - } - ++s; - // Parse fill and alignment. - if (Char c = *s) { - const Char *p = s + 1; - spec.align_ = ALIGN_DEFAULT; - do { - switch (*p) { - case '<': - spec.align_ = ALIGN_LEFT; - break; - case '>': - spec.align_ = ALIGN_RIGHT; - break; - case '=': - spec.align_ = ALIGN_NUMERIC; - break; - case '^': - spec.align_ = ALIGN_CENTER; - break; - } - if (spec.align_ != ALIGN_DEFAULT) { - if (p != s) { - if (c == '}') break; - if (c == '{') - FMT_THROW(FormatError("invalid fill character '{'")); - s += 2; - spec.fill_ = c; - } else ++s; - if (spec.align_ == ALIGN_NUMERIC) - require_numeric_argument(arg, '='); - break; - } - } while (--p >= s); - } - - // Parse sign. - switch (*s) { - case '+': - check_sign(s, arg); - spec.flags_ |= SIGN_FLAG | PLUS_FLAG; - break; - case '-': - check_sign(s, arg); - spec.flags_ |= MINUS_FLAG; - break; - case ' ': - check_sign(s, arg); - spec.flags_ |= SIGN_FLAG; - break; - } - - if (*s == '#') { - require_numeric_argument(arg, '#'); - spec.flags_ |= HASH_FLAG; - ++s; - } - - // Parse zero flag. - if (*s == '0') { - require_numeric_argument(arg, '0'); - spec.align_ = ALIGN_NUMERIC; - spec.fill_ = '0'; - ++s; - } - - // Parse width. - if ('0' <= *s && *s <= '9') { - spec.width_ = internal::parse_nonnegative_int(s); - } else if (*s == '{') { - ++s; - Arg width_arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); - if (*s++ != '}') - FMT_THROW(FormatError("invalid format string")); - ULongLong value = 0; - switch (width_arg.type) { - case Arg::INT: - if (width_arg.int_value < 0) - FMT_THROW(FormatError("negative width")); - value = width_arg.int_value; - break; - case Arg::UINT: - value = width_arg.uint_value; - break; - case Arg::LONG_LONG: - if (width_arg.long_long_value < 0) - FMT_THROW(FormatError("negative width")); - value = width_arg.long_long_value; - break; - case Arg::ULONG_LONG: - value = width_arg.ulong_long_value; - break; - default: - FMT_THROW(FormatError("width is not integer")); - } - if (value > (std::numeric_limits::max)()) - FMT_THROW(FormatError("number is too big")); - spec.width_ = static_cast(value); - } - - // Parse precision. - if (*s == '.') { - ++s; - spec.precision_ = 0; - if ('0' <= *s && *s <= '9') { - spec.precision_ = internal::parse_nonnegative_int(s); - } else if (*s == '{') { - ++s; - Arg precision_arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); - if (*s++ != '}') - FMT_THROW(FormatError("invalid format string")); - ULongLong value = 0; - switch (precision_arg.type) { - case Arg::INT: - if (precision_arg.int_value < 0) - FMT_THROW(FormatError("negative precision")); - value = precision_arg.int_value; - break; - case Arg::UINT: - value = precision_arg.uint_value; - break; - case Arg::LONG_LONG: - if (precision_arg.long_long_value < 0) - FMT_THROW(FormatError("negative precision")); - value = precision_arg.long_long_value; - break; - case Arg::ULONG_LONG: - value = precision_arg.ulong_long_value; - break; - default: - FMT_THROW(FormatError("precision is not integer")); - } - if (value > (std::numeric_limits::max)()) - FMT_THROW(FormatError("number is too big")); - spec.precision_ = static_cast(value); - } else { - FMT_THROW(FormatError("missing precision specifier")); - } - if (arg.type <= Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) { - FMT_THROW(FormatError( - fmt::format("precision not allowed in {} format specifier", - arg.type == Arg::POINTER ? "pointer" : "integer"))); - } - } - - // Parse type. - if (*s != '}' && *s) - spec.type_ = static_cast(*s++); - } - - if (*s++ != '}') - FMT_THROW(FormatError("missing '}' in format string")); - - // Format argument. - ArgFormatter(*this, spec, s - 1).visit(arg); - return s; -} - -template -void BasicFormatter::format(BasicCStringRef format_str) { - const Char *s = format_str.c_str(); - const Char *start = s; - while (*s) { - Char c = *s++; - if (c != '{' && c != '}') continue; - if (*s == c) { - write(writer_, start, s); - start = ++s; - continue; - } - if (c == '}') - FMT_THROW(FormatError("unmatched '}' in format string")); - write(writer_, start, s - 1); - internal::Arg arg = internal::is_name_start(*s) ? - parse_arg_name(s) : parse_arg_index(s); - start = s = format(s, arg); - } - write(writer_, start, s); -} -} // namespace fmt - -#if FMT_USE_USER_DEFINED_LITERALS -namespace fmt { -namespace internal { - -template -struct UdlFormat { - const Char *str; - - template - auto operator()(Args && ... args) const - -> decltype(format(str, std::forward(args)...)) { - return format(str, std::forward(args)...); - } -}; - -template -struct UdlArg { - const Char *str; - - template - NamedArg operator=(T &&value) const { - return {str, std::forward(value)}; - } -}; - -} // namespace internal - -inline namespace literals { - -/** - \rst - C++11 literal equivalent of :func:`fmt::format`. - - **Example**:: - - using namespace fmt::literals; - std::string message = "The answer is {}"_format(42); - \endrst - */ -inline internal::UdlFormat -operator"" _format(const char *s, std::size_t) { return {s}; } -inline internal::UdlFormat -operator"" _format(const wchar_t *s, std::size_t) { return {s}; } - -/** - \rst - C++11 literal equivalent of :func:`fmt::arg`. - - **Example**:: - - using namespace fmt::literals; - print("Elapsed time: {s:.2f} seconds", "s"_a=1.23); - \endrst - */ -inline internal::UdlArg -operator"" _a(const char *s, std::size_t) { return {s}; } -inline internal::UdlArg -operator"" _a(const wchar_t *s, std::size_t) { return {s}; } - -} // inline namespace literals -} // namespace fmt -#endif // FMT_USE_USER_DEFINED_LITERALS - -// Restore warnings. -#if FMT_GCC_VERSION >= 406 -# pragma GCC diagnostic pop -#endif - -#if defined(__clang__) && !defined(FMT_ICC_VERSION) -# pragma clang diagnostic pop -#endif - -#ifdef FMT_HEADER_ONLY -# define FMT_FUNC inline -# include "format.cc" -#else -# define FMT_FUNC -#endif - -#endif // FMT_FORMAT_H_ diff --git a/install/osx/.gitignore b/install/osx/.gitignore deleted file mode 100644 index 0b3178f5b..000000000 --- a/install/osx/.gitignore +++ /dev/null @@ -1 +0,0 @@ -!Uninstall.app diff --git a/install/osx/Uninstall.app/Contents/Info.plist b/install/osx/Uninstall.app/Contents/Info.plist deleted file mode 100644 index da9e93378..000000000 --- a/install/osx/Uninstall.app/Contents/Info.plist +++ /dev/null @@ -1,84 +0,0 @@ - - - - - AMIsApplet - - AMStayOpen - - BuildMachineOSBuild - 13A563a - CFBundleDevelopmentRegion - English - CFBundleDocumentTypes - - - CFBundleTypeExtensions - - * - - CFBundleTypeName - Automator workflow file - CFBundleTypeOSTypes - - **** - - CFBundleTypeRole - Viewer - - - CFBundleExecutable - Application Stub - CFBundleIdentifier - com.apple.automator.Uninstall - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - Uninstall - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.2 - CFBundleSignature - ???? - CFBundleURLTypes - - CFBundleVersion - 381 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 5A11344p - DTPlatformVersion - GM - DTSDKBuild - 13A563a - DTSDKName - - DTXcode - 0500 - DTXcodeBuild - 5A11344p - LSMinimumSystemVersion - 10.5 - LSMinimumSystemVersionByArchitecture - - x86_64 - 10.6 - - LSUIElement - - NSAppleScriptEnabled - YES - NSMainNibFile - ApplicationStub - NSPrincipalClass - NSApplication - NSServices - - UTExportedTypeDeclarations - - UTImportedTypeDeclarations - - - diff --git a/install/osx/Uninstall.app/Contents/MacOS/Application Stub b/install/osx/Uninstall.app/Contents/MacOS/Application Stub deleted file mode 100755 index 1a7061cce..000000000 Binary files a/install/osx/Uninstall.app/Contents/MacOS/Application Stub and /dev/null differ diff --git a/install/osx/Uninstall.app/Contents/Resources/English.lproj/ApplicationStub.nib b/install/osx/Uninstall.app/Contents/Resources/English.lproj/ApplicationStub.nib deleted file mode 100644 index 80dce3747..000000000 Binary files a/install/osx/Uninstall.app/Contents/Resources/English.lproj/ApplicationStub.nib and /dev/null differ diff --git a/install/osx/Uninstall.app/Contents/document.wflow b/install/osx/Uninstall.app/Contents/document.wflow deleted file mode 100644 index ef3228de8..000000000 --- a/install/osx/Uninstall.app/Contents/document.wflow +++ /dev/null @@ -1,447 +0,0 @@ - - - - - AMApplicationBuild - 381 - AMApplicationVersion - 2.4 - AMDocumentVersion - 2 - actions - - - action - - AMAccepts - - Container - List - Optional - - Types - - - AMActionVersion - 1.0.2 - AMApplication - - Automator - - AMParameterProperties - - affirmativeTitle - - displayWarning - - explanationText - - negativeTitle - - questionText - - tokenizedValue - - Uninstall OBS Browser Plugin - - - - AMProvides - - Container - List - Types - - - ActionBundlePath - /System/Library/Automator/Ask for Confirmation.action - ActionName - Ask for Confirmation - ActionParameters - - affirmativeTitle - Uninstall - displayWarning - - explanationText - Are you sure you want to uninstall the OBS Browser Plugin? - -Uninstaller actions: - * Forget the package (pkgutil —forget) - * Delete ~/Library/Application Support/obs-studio/plugins/obs-browser - negativeTitle - Cancel - questionText - Uninstall OBS Browser Plugin - - BundleIdentifier - com.apple.Automator.Ask for Confirmation - CFBundleVersion - 1.0.2 - CanShowSelectedItemsWhenRun - - CanShowWhenRun - - Category - - AMCategoryUtilities - - Class Name - AMAskForConfirmationAction - InputUUID - 46AEAE3D-C928-4E77-B42A-D340E65FFF80 - Keywords - - Message - Ask - Display - Prompt - Show - - OutputUUID - DEB7B685-0E4F-46FD-B76F-F3D38B30BF70 - UUID - A0D2FA32-458D-4B9B-A6AE-B4128CFD3871 - UnlocalizedApplications - - Automator - - arguments - - 0 - - default value - - name - questionText - required - 0 - type - 0 - uuid - 0 - - 1 - - default value - - name - displayWarning - required - 0 - type - 0 - uuid - 1 - - 2 - - default value - - name - explanationText - required - 0 - type - 0 - uuid - 2 - - 3 - - default value - OK - name - affirmativeTitle - required - 0 - type - 0 - uuid - 3 - - 4 - - default value - Cancel - name - negativeTitle - required - 0 - type - 0 - uuid - 4 - - - isViewVisible - - location - 1089.500000:1090.000000 - nibPath - /System/Library/Automator/Ask for Confirmation.action/Contents/Resources/English.lproj/main.nib - - isViewVisible - - - - action - - AMAccepts - - Container - List - Optional - - Types - - com.apple.applescript.object - - - AMActionVersion - 1.0.2 - AMApplication - - Automator - - AMParameterProperties - - source - - - AMProvides - - Container - List - Types - - com.apple.applescript.object - - - ActionBundlePath - /System/Library/Automator/Run AppleScript.action - ActionName - Run AppleScript - ActionParameters - - source - on run {input, parameters} try do shell script "pkgutil --volume ~ --forget org.catchexception.obs-browser" end try do shell script "rm -rf ~/Library/Application\\ Support/obs-studio/plugins/obs-browser" return input end run - - BundleIdentifier - com.apple.Automator.RunScript - CFBundleVersion - 1.0.2 - CanShowSelectedItemsWhenRun - - CanShowWhenRun - - Category - - AMCategoryUtilities - - Class Name - RunScriptAction - InputUUID - B123E45E-5466-4D99-8AF9-B086A96E35C0 - Keywords - - Run - - OutputUUID - 105179FE-5E58-4944-BE3F-8AABE3836901 - UUID - 7E2BCAA2-DCAD-46EE-A210-64C2E3A4D5E2 - UnlocalizedApplications - - Automator - - arguments - - 0 - - default value - on run {input, parameters} - - (* Your script goes here *) - - return input -end run - name - source - required - 0 - type - 0 - uuid - 0 - - - conversionLabel - 0 - isViewVisible - - location - 1089.500000:893.000000 - nibPath - /System/Library/Automator/Run AppleScript.action/Contents/Resources/English.lproj/main.nib - - isViewVisible - - - - action - - AMAccepts - - Container - List - Optional - - Types - - - AMActionVersion - 1.0 - AMApplication - - Automator - - AMParameterProperties - - message - - subtitle - - title - - tokenizedValue - - OBS Browser Plugin uninstalled - - - - AMProvides - - Container - List - Types - - - ActionBundlePath - /System/Library/Automator/Display Notification.action - ActionName - Display Notification - ActionParameters - - message - - subtitle - - title - OBS Browser Plugin uninstalled - - BundleIdentifier - com.apple.Automator.Display-Notification - CFBundleVersion - 1.0 - CanShowSelectedItemsWhenRun - - CanShowWhenRun - - Category - - AMCategoryUtilities - - Class Name - AMDisplayNotificationAction - InputUUID - 29F40CE4-DED9-471B-B4FF-AE6BDC630CA1 - Keywords - - OutputUUID - 668D0124-39EF-484A-8D74-53D03E0232C3 - UUID - BC24E59E-4A42-4744-B54C-C9A87BE0FE88 - UnlocalizedApplications - - Automator - - arguments - - 0 - - default value - - name - subtitle - required - 0 - type - 0 - uuid - 0 - - 1 - - default value - - name - title - required - 0 - type - 0 - uuid - 1 - - 2 - - default value - - name - message - required - 0 - type - 0 - uuid - 2 - - - conversionLabel - 0 - isViewVisible - - location - 1089.500000:400.000000 - nibPath - /System/Library/Automator/Display Notification.action/Contents/Resources/Base.lproj/main.nib - - isViewVisible - - - - connectors - - D2D1EE49-E4B4-4DBE-AFD9-33B67803833D - - from - 7E2BCAA2-DCAD-46EE-A210-64C2E3A4D5E2 - 7E2BCAA2-DCAD-46EE-A210-64C2E3A4D5E2 - to - BC24E59E-4A42-4744-B54C-C9A87BE0FE88 - BC24E59E-4A42-4744-B54C-C9A87BE0FE88 - - FA88613E-9255-459F-89AA-F040F20641B0 - - from - A0D2FA32-458D-4B9B-A6AE-B4128CFD3871 - A0D2FA32-458D-4B9B-A6AE-B4128CFD3871 - to - 7E2BCAA2-DCAD-46EE-A210-64C2E3A4D5E2 - 7E2BCAA2-DCAD-46EE-A210-64C2E3A4D5E2 - - - workflowMetaData - - workflowTypeIdentifier - com.apple.Automator.application - - - diff --git a/install/osx/gpl.txt b/install/osx/gpl.txt deleted file mode 100644 index d7f105139..000000000 --- a/install/osx/gpl.txt +++ /dev/null @@ -1,339 +0,0 @@ -GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - {description} - Copyright (C) {year} {fullname} - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - {signature of Ty Coon}, 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/install/osx/logo.png b/install/osx/logo.png deleted file mode 100644 index e391920fc..000000000 Binary files a/install/osx/logo.png and /dev/null differ diff --git a/install/osx/obs-browser-install.pkgproj b/install/osx/obs-browser-install.pkgproj deleted file mode 100755 index 4a9835972..000000000 --- a/install/osx/obs-browser-install.pkgproj +++ /dev/null @@ -1,989 +0,0 @@ - - - - - PACKAGES - - - PACKAGE_FILES - - DEFAULT_INSTALL_LOCATION - / - HIERARCHY - - CHILDREN - - - CHILDREN - - - CHILDREN - - GID - 80 - PATH - Utilities - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - GID - 80 - PATH - Applications - PATH_TYPE - 0 - PERMISSIONS - 509 - TYPE - 1 - UID - 0 - - - CHILDREN - - - CHILDREN - - - CHILDREN - - - CHILDREN - - - CHILDREN - - - CHILDREN - - - CHILDREN - - GID - 80 - PATH - ../../../../build/plugins/obs-browser/CEF.app - PATH_TYPE - 3 - PERMISSIONS - 493 - TYPE - 3 - UID - 0 - - - CHILDREN - - GID - 80 - PATH - ../../../../build/plugins/obs-browser/obs-browser.so - PATH_TYPE - 3 - PERMISSIONS - 493 - TYPE - 3 - UID - 0 - - - GID - 80 - PATH - bin - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 2 - UID - 0 - - - GID - 80 - PATH - obs-browser - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 2 - UID - 0 - - - GID - 80 - PATH - plugins - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 2 - UID - 0 - - - GID - 80 - PATH - obs-studio - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 2 - UID - 0 - - - GID - 80 - PATH - Application Support - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Documentation - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Filesystems - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Frameworks - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Input Methods - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Internet Plug-Ins - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - LaunchAgents - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - LaunchDaemons - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - PreferencePanes - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Preferences - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 80 - PATH - Printers - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - PrivilegedHelperTools - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - QuickLook - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - QuickTime - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Screen Savers - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Scripts - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Services - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - GID - 0 - PATH - Widgets - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - GID - 0 - PATH - Library - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - - CHILDREN - - - CHILDREN - - GID - 0 - PATH - Extensions - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - GID - 0 - PATH - Library - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - GID - 0 - PATH - System - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - CHILDREN - - - CHILDREN - - GID - 0 - PATH - Shared - PATH_TYPE - 0 - PERMISSIONS - 1023 - TYPE - 1 - UID - 0 - - - GID - 80 - PATH - Users - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - - GID - 0 - PATH - / - PATH_TYPE - 0 - PERMISSIONS - 493 - TYPE - 1 - UID - 0 - - PAYLOAD_TYPE - 0 - VERSION - 2 - - PACKAGE_SCRIPTS - - RESOURCES - - - PACKAGE_SETTINGS - - AUTHENTICATION - - CONCLUSION_ACTION - 0 - IDENTIFIER - org.catchexception.obs-browser - NAME - obs-browser-install - OVERWRITE_PERMISSIONS - - VERSION - 1.0 - - UUID - 903F543B-DCA1-48CE-8C60-5A24889DED85 - - - PROJECT - - PROJECT_COMMENTS - - NOTES - - PCFET0NUWVBFIGh0bWwgUFVCTElDICItLy9XM0MvL0RURCBIVE1M - IDQuMDEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvVFIvaHRtbDQv - c3RyaWN0LmR0ZCI+CjxodG1sPgo8aGVhZD4KPG1ldGEgaHR0cC1l - cXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7 - IGNoYXJzZXQ9VVRGLTgiPgo8bWV0YSBodHRwLWVxdWl2PSJDb250 - ZW50LVN0eWxlLVR5cGUiIGNvbnRlbnQ9InRleHQvY3NzIj4KPHRp - dGxlPjwvdGl0bGU+CjxtZXRhIG5hbWU9IkdlbmVyYXRvciIgY29u - dGVudD0iQ29jb2EgSFRNTCBXcml0ZXIiPgo8bWV0YSBuYW1lPSJD - b2NvYVZlcnNpb24iIGNvbnRlbnQ9IjE1MDQuNzYiPgo8c3R5bGUg - dHlwZT0idGV4dC9jc3MiPgo8L3N0eWxlPgo8L2hlYWQ+Cjxib2R5 - Pgo8L2JvZHk+CjwvaHRtbD4K - - - PROJECT_PRESENTATION - - BACKGROUND - - ALIGNMENT - 7 - BACKGROUND_PATH - - PATH - logo.png - PATH_TYPE - 1 - - CUSTOM - 1 - SCALING - 0 - - INSTALLATION TYPE - - HIERARCHIES - - INSTALLER - - LIST - - - DESCRIPTION - - OPTIONS - - HIDDEN - - STATE - 1 - - PACKAGE_UUID - 903F543B-DCA1-48CE-8C60-5A24889DED85 - REQUIREMENTS - - TITLE - - - LANGUAGE - English - VALUE - OBS Studio Browser Plugin - - - TOOLTIP - - TYPE - 0 - UUID - 32074DAC-F666-424B-9B94-20F750104525 - - - REMOVED - - - - INSTALLATION TYPE - 0 - MODE - 1 - - INSTALLATION_STEPS - - - ICPRESENTATION_CHAPTER_VIEW_CONTROLLER_CLASS - ICPresentationViewIntroductionController - INSTALLER_PLUGIN - Introduction - LIST_TITLE_KEY - InstallerSectionTitle - - - ICPRESENTATION_CHAPTER_VIEW_CONTROLLER_CLASS - ICPresentationViewReadMeController - INSTALLER_PLUGIN - ReadMe - LIST_TITLE_KEY - InstallerSectionTitle - - - ICPRESENTATION_CHAPTER_VIEW_CONTROLLER_CLASS - ICPresentationViewLicenseController - INSTALLER_PLUGIN - License - LIST_TITLE_KEY - InstallerSectionTitle - - - ICPRESENTATION_CHAPTER_VIEW_CONTROLLER_CLASS - ICPresentationViewDestinationSelectController - INSTALLER_PLUGIN - TargetSelect - LIST_TITLE_KEY - InstallerSectionTitle - - - ICPRESENTATION_CHAPTER_VIEW_CONTROLLER_CLASS - ICPresentationViewInstallationTypeController - INSTALLER_PLUGIN - PackageSelection - LIST_TITLE_KEY - InstallerSectionTitle - - - ICPRESENTATION_CHAPTER_VIEW_CONTROLLER_CLASS - ICPresentationViewInstallationController - INSTALLER_PLUGIN - Install - LIST_TITLE_KEY - InstallerSectionTitle - - - ICPRESENTATION_CHAPTER_VIEW_CONTROLLER_CLASS - ICPresentationViewSummaryController - INSTALLER_PLUGIN - Summary - LIST_TITLE_KEY - InstallerSectionTitle - - - INTRODUCTION - - LOCALIZATIONS - - - LICENSE - - KEYWORDS - - LOCALIZATIONS - - - LANGUAGE - English - VALUE - - PATH - gpl.txt - PATH_TYPE - 1 - - - - MODE - 0 - TEMPLATE - APSL License - - README - - LOCALIZATIONS - - - LANGUAGE - English - VALUE - - PATH - readme.rtf - PATH_TYPE - 1 - - - - - TITLE - - LOCALIZATIONS - - - LANGUAGE - English - VALUE - OBS Studio Browser Plugin - - - - - PROJECT_REQUIREMENTS - - LIST - - POSTINSTALL_PATH - - PREINSTALL_PATH - - RESOURCES - - ROOT_VOLUME_ONLY - - - PROJECT_SETTINGS - - ADVANCED_OPTIONS - - installer-script.domains:enable_currentUserHome - - - BUILD_FORMAT - 0 - BUILD_PATH - - PATH - build - PATH_TYPE - 3 - - EXCLUDED_FILES - - - PATTERNS_ARRAY - - - REGULAR_EXPRESSION - - STRING - .DS_Store - TYPE - 0 - - - PROTECTED - - PROXY_NAME - Remove .DS_Store files - PROXY_TOOLTIP - Remove ".DS_Store" files created by the Finder. - STATE - - - - PATTERNS_ARRAY - - - REGULAR_EXPRESSION - - STRING - .pbdevelopment - TYPE - 0 - - - PROTECTED - - PROXY_NAME - Remove .pbdevelopment files - PROXY_TOOLTIP - Remove ".pbdevelopment" files created by ProjectBuilder or Xcode. - STATE - - - - PATTERNS_ARRAY - - - REGULAR_EXPRESSION - - STRING - CVS - TYPE - 1 - - - REGULAR_EXPRESSION - - STRING - .cvsignore - TYPE - 0 - - - REGULAR_EXPRESSION - - STRING - .cvspass - TYPE - 0 - - - REGULAR_EXPRESSION - - STRING - .svn - TYPE - 1 - - - REGULAR_EXPRESSION - - STRING - .git - TYPE - 1 - - - REGULAR_EXPRESSION - - STRING - .gitignore - TYPE - 0 - - - PROTECTED - - PROXY_NAME - Remove SCM metadata - PROXY_TOOLTIP - Remove helper files and folders used by the CVS, SVN or Git Source Code Management systems. - STATE - - - - PATTERNS_ARRAY - - - REGULAR_EXPRESSION - - STRING - classes.nib - TYPE - 0 - - - REGULAR_EXPRESSION - - STRING - designable.db - TYPE - 0 - - - REGULAR_EXPRESSION - - STRING - info.nib - TYPE - 0 - - - PROTECTED - - PROXY_NAME - Optimize nib files - PROXY_TOOLTIP - Remove "classes.nib", "info.nib" and "designable.nib" files within .nib bundles. - STATE - - - - PATTERNS_ARRAY - - - REGULAR_EXPRESSION - - STRING - Resources Disabled - TYPE - 1 - - - PROTECTED - - PROXY_NAME - Remove Resources Disabled folders - PROXY_TOOLTIP - Remove "Resources Disabled" folders. - STATE - - - - SEPARATOR - - - - NAME - obs-browser-install - - - TYPE - 0 - VERSION - 2 - - diff --git a/install/osx/readme.rtf b/install/osx/readme.rtf deleted file mode 100644 index 3218402d7..000000000 --- a/install/osx/readme.rtf +++ /dev/null @@ -1,20 +0,0 @@ -{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf210 -{\fonttbl\f0\fswiss\fcharset0 Helvetica;} -{\colortbl;\red255\green255\blue255;} -{\*\listtable{\list\listtemplateid1\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid1\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid1}} -{\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}} -\margl1440\margr1440\vieww10800\viewh8400\viewkind0 -\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural - -\f0\b\fs24 \cf0 OBS Studio Browser Source Plugin\ -\ - -\b0 This plugin allows you to add a browser element to your scene.\ -\ -Features include:\ -\pard\tx220\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\li720\fi-720\pardirnatural -\ls1\ilvl0\cf0 {\listtext \'95 }